user3861559
user3861559

Reputation: 993

AJAX not receiving response from servlet

I have an AJAX making a POST to a servlet. Servlet does some computation and returns a response. AJAX success function reads the response and does certain things.

AJAX CALL

$.ajax( {
     type: "POST",
     url: "/bin/path/to/Servlet",
     data: $(this).serialize(),
     dataType: "html",
     success: function(responseValue) {
         if(responseValue == '200') {
              // Do something
          }else {
              console.log("it is not 200");
          }
     },
     error: trialForm.trialError
     }).done(function(status) {
             $(trialForm.submitButton).show();
             $(trialForm.loader).hide();
     });
}

SERVLET

protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
     response.setContentType("text/html");    

     URL url = new URL("www.apriurl.com");
     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     conn.setDoOutput(true);
     conn.setRequestMethod("POST");
     conn.setRequestProperty("Content-Type","application/json");
     conn.setRequestProperty("Authorization","XXXXZZZZ " + strSig);
     conn.setRequestProperty("Accept","application/json");
     conn.setRequestProperty("ZZZZZ",clientID);

     OutputStream os = conn.getOutputStream();
     os.write(inputParameters.getBytes());
     os.flush(); 

     System.out.println(conn.getResponseCode());
     response.getWriter().write(conn.getResponseCode());
}

Upvotes: 1

Views: 1226

Answers (1)

Scary Wombat
Scary Wombat

Reputation: 44813

This is doing a write (int) rather than a write (String) so if you do write(200) it is sending the ascii value of 200

try sending 200 as a String

as

response.getWriter().write(String.valueOf (conn.getResponseCode()));

see https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#write(int)

public void write(int c)

Writes a single character.

Upvotes: 1

Related Questions