0

I have been through almost all Stack overflow answers regarding this issue to solve this problem, I tried so many things, but I am still getting null, I am simply trying to send a java script variable to servlet using AJAX from within an else statement in JS as the following shows, and iam getting null in the alertbox:

else { //begin JS else
                    var somevar="iam the user";

                     $.ajax({
                        type:"POST",
                        url:"Register", 
                       dataType: 'json',
                       contentType:'application/json',

                        data:{
                        Subject:somevar},

                          cache: false,
                        processData:false,
                        success: function(data){
                            alert(data);
                        },
                        error: function(){
                            alert("error");
                        }


            });
} //end else

And my doPost method in my servlet (Register)

 @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
             resp.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
            resp.setCharacterEncoding("UTF-8"); 
        String user = req.getParameter("Subject");
               //resp.sendRedirect("registration.jsp");
                PrintWriter out = resp.getWriter();
                    out.println(user);
                //String pathInfo = req.getRequestURI();


}

I tried many different things, but to name a few:

1-if i uncomment and use this line and comment the other lines : resp.sendRedirect("registration.jsp");

Then i get error in the alertbox as a response.

2-if i send an other string (not the user value) from the servlet back to the ajax as a response for example: out.println("some string"); Then i get that string in the JS alertbox just fine

among other thing I have tried, It's becoming clear that the value is being sent from ajax to servlet successfully, but when the server read it, it's null, the server can send a string response back to ajax (any variable other than the getparameter() value) and the ajax is getting it just fine.

In light of this, i tried following some processing steps (extracting the JSON elements on the servlet) using answers such as this answer. But after i tried this answer, the alert box was giving error again.

I know there are other ways to send data using http (send() method for instance), but I find ajax better only because iam sending multiple data objects not just one (in my example it is only one, but i will use it to send more than one data element). Any help will be appreciated.

UPDATE : Some progress was made, by viewing more answers such as this one I was able to modify both the answer and my code and combine them together, also with the help of @stdunbar 's comment about browser debugging which was EXTREMELY HELPFUL , I was able to trace things in the browser, now the issue is almost solved but not completely, now iam able to extract the value from the request and turn it into a string, but when i sent the string back to the ajax (js), the alertbox shows (error), BUT the good news is, the browser debugger shows the respose as a string, but the alertbox can't display it, here is my updated servlet code:

  @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

            PrintWriter out = resp.getWriter();

             StringBuilder sb = new StringBuilder();
    BufferedReader br = req.getReader();
    String str;
    while( (str = br.readLine()) != null ){
        sb.append(str);
    }    
    try{
    JSONObject jObj = new JSONObject(sb.toString());
    String extracted=jObj.getString("Subject").toString();
   resp.setContentType("application/json");
   resp.setCharacterEncoding("UTF-8"); 
   // resp.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
   // resp.setCharacterEncoding("UTF-8"); 
     out.println(jObj);
    }catch (JSONException e) {
    }


    }

And my AJAX:

else { //begin JS else 
           var somevar="iam the user";

                 $.ajax({
                     type:"POST",
                     url:"Register", 
                    dataType: 'json',
             contentType:'application/json',
                data:JSON.stringify({Subject:somevar}),


                      cache: false,
                    processData:false,
                    success: function(data){
                        alert(data);
                    },
                    error: function(){
                        alert("error");
                    }


        });

            } //end JS else
HMA
  • 81
  • 3
  • 11
  • Have you first validated that the correct data is being sent from the browser using the browser debugging tools? – stdunbar May 30 '17 at 20:05
  • no, i didn't know that's possible, iam trying that...thanks – HMA May 30 '17 at 20:17
  • actually there is something sent : {"Subject":"iam the user"} and the response is null. – HMA May 30 '17 at 20:30
  • Once you sent the AJAX request, go to browser "page console" and check what it is getting from the server – raviraja May 31 '17 at 05:50

1 Answers1

0

So After the update i posted, i further worked on it and finally solved it, the problem was that the content type was set application/json in both the servlet and the JS/ajax (which is correct) , but i was expecting a string to pop up in the alertbox, so in addition to the updated code in the servlet, i changed this line in the ajax:

From

alert(data); // this line trying to get the json object (wrong)

To

 alert(data.Subject); // this line is getting the value of the key (correct)

Thanks for all the replies and comments, they all helped.

HMA
  • 81
  • 3
  • 11