Karthik Amar
Karthik Amar

Reputation: 217

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.

Upvotes: 2

Views: 5027

Answers (1)

giannis christofakis
giannis christofakis

Reputation: 8311

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!

Upvotes: 2

Related Questions