2

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.

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
Karthik Amar
  • 217
  • 5
  • 17
  • Try removing `.java` from your `post` method. Use `$.post("AjaxpostloginServlet")` instead of `$.post("AjaxpostloginServlet.java")` – Joe Nov 24 '14 at 14:00
  • Your ajax request must be send to the url that your servlet is mapped. https://docs.oracle.com/cd/E13222_01/wls/docs92/webapp/configureservlet.html – giannis christofakis Nov 24 '14 at 14:12
  • Check also http://stackoverflow.com/questions/2484556/how-to-ouput-text-to-java-console-from-servlet – giannis christofakis Nov 24 '14 at 14:37

1 Answers1

2

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!

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65