Bahman Rouhani Bahman Rouhani - 7 months ago 55
Ajax Question

calling a java servlet from javascript ajax post method

this might seem like a naive question but I'm fairly new to Java servlets and tomcat. I'm trying to call a servlet method by .post method in my javascript file. javascript is used in a .jsp file. everything works fine as long as the servlet is in the same directory with the jsp but when I change the path for file I can't get it to work no matter what I do. I tried these:

$.post("./classes/myServlets/WEB-INF/order", $.param(data), function(response) {
document.getElementById("Table").innerHTML = "Considered table number " + response + " for you";
});


or

$.post("/classes/myServlets/WEB-INF/order", $.param(data), function(response) {
document.getElementById("Table").innerHTML = "Considered table number " + response + " for you";
});


or

$.post("order", $.param(data), function(response) {
document.getElementById("Table").innerHTML = "Considered table number " + response + " for you";
});


or

$.post("/classes/myServlets/WEB-INF/order.java", $.param(data), function(response) {
document.getElementById("Table").innerHTML = "Considered table number " + response + " for you";
});


I know this must be very easy but I can't find the instructions anywhere. thank's in advance.

Answer Source

Your servlet while defined in a .java file and compiled into a class that is stored in your WEB-INF folder, will need to be mapped to a URL (usually in your web.xml). It would not be easy to answer this without more information about what servlet container and framework you are using, but assuming you were just using pure Tomcat (without any framework like Spring) you might look at your web.xml file for something like this:

<servlet>
    <servlet-name>com.project.Order</servlet-name>
    <servlet-class>com.project.Order</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>com.project.Order</servlet-name>
    <url-pattern>/order</url-pattern>
</servlet-mapping>

With this URL mapped you can then send HTTP POST request with some jQuery like this:

$.post("/order", $.param(data), function(response) {
  document.getElementById("Table").innerHTML = "Considered table number  " + response + "  for you";
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download