1

I'm trying to send json data to servlet using ajax jquery call... below is the code

 $(function() {
     $( "#mybutton").click(function() {
            var testdata = JSON.stringify({
                'name': 'name',
                'desc':'test'
            });


        $.ajax({
           type: "POST",                     
           url:"/Alert/ReportServlet",  
           data: testdata,       
           dataType: "json",
           contentType: "application/json",
           success : function(data){            
               console.log("success:", data);
            },
            error : function(data) {
                console.log("error:", data);
            }

     });
     });
     });

and the servlet code is

public class ReportingServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
            System.out.println("The data is" + request.getParameter("testdata"));    
      }     
}

The value is coming as null...Please suggest

upog
  • 4,965
  • 8
  • 42
  • 81
  • possible duplicate of [Get parameter sent via jquery ajax in Java Servlet](http://stackoverflow.com/questions/19374345/get-parameter-sent-via-jquery-ajax-in-java-servlet) – Hirak May 09 '14 at 03:37
  • show us `web.xml` for servlet mapping. In your code, url is `/Alert/ReportServlet` but server class name `ReportingServlet`. – Wundwin Born May 09 '14 at 04:14
  • please use request.getQueryString() because you sent "{'name':'name' ,'desc':'test'}" to backend, there is no parameter called testdata – Ted Shaw May 09 '14 at 06:32
  • i got the data from request input stream, as given the other post – upog May 09 '14 at 13:33

2 Answers2

0

In servlet try with

request.getParameter("name");
request.getParameter("dest");
Wundwin Born
  • 3,467
  • 19
  • 37
0

In your Ajax call do something like this

 $(function() {
     $( "#mybutton").click(function() {
            var testdata = JSON.stringify({
                'name': 'name',
                'desc':'test'
            });


        $.ajax({
           type: "POST",                     
           url:"/Alert/ReportServlet",  
           data: { d : testdata },       
           dataType: "json",
           contentType: "application/json",
           success : function(data){            
               console.log("success:", data);
            },
            error : function(data) {
                console.log("error:", data);
            }

     });
     });
     });

then in java try :

request.getParameter("d");

this you can use some library (like jackson) to convert d into HashMap

LNT
  • 876
  • 8
  • 18