Karthik Amar Karthik Amar - 2 months ago 10
Ajax Question

Cannot send ajax post request to servlet

Here is my code.,

Javascript

$(document).ready(function()
{
$("button").click(function(){
$.post("AjaxpostloginServlet.java",
{
name:"kevin",
pass:"Duckburg"
});
});
});


Java servlet

package com.iappuniverse.ajaxpostlogin;

import java.io.IOException;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class AjaxpostloginServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException
{

String name=req.getParameter("name");

System.out.println(name);

}
}


The name here in the servlet doesn't get printed in the console. Trying to send data to the server using ajax
.post()
, but cannot make the servlet linked to the ajax
.post()
call run.

Answer

Change your web.xml to something like the below

<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <display-name>Application</display-name>
    <description>
        Description Example.
    </description>

    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>AjaxpostloginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
</web-app>

lets take it a step further and change your servlet post method

public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException {
       String name=req.getParameter("name");
       response.setContentType("text/plain");
       response.setCharacterEncoding("UTF-8");
       response.getWriter().write(name);

}

finally change the url of the ajax call and use a callback function.

$(document).ready(function() {
        $("button").click(function() {
            $.post("login",{
                 name:"kevin",
                 pass:"Duckburg"
             }).done(function( data ) {
                  alert( "name: " + data );
             })
         });
});

Disclaimer: I haven't test it!