1

I am using Servlet as controller and jquery to send request to server. Following is my jquery request

$.post("login", {userName:$userName, password:$password}, function(data, textStatus) {
alert(textStatus);
});

And in server side i have written following code

response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.println("" + strError + "");
            out.flush();
            out.close();

I want to set error message and error error status code in servlet and read the same status code in jquery. How can I achieve the same?

Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243

2 Answers2

0

You can return a json encoded string from the server. How do you return a JSON object from a Java Servlet

For example if you sent the following json encoded string back. {'error': 'This is some error message' }

Then on the client side you would do the following

$.post("login", {userName:$userName, password:$password}, function(data, textStatus) {
    alert(data.error); // your error message will show up here in the data object 
 },'json');
Community
  • 1
  • 1
aziz punjani
  • 25,586
  • 9
  • 47
  • 56
0

In a java servlet, to set the HTTP status, you have to use the following:

response.setStatus( code );

The code part can be several things like HttpServletResponse.SC_NOT_FOUND to emulate an error 404 (page not found). A exhaustive list can be found here.

On the jQuery side, you can use the following:

$.post( 'login', { /* ... */ }, function( data, textStatus, xhrObject ) {
    // You can read the status returned with
    xhrObject.status;
} );

I guess the textStatus variable holds the status, but the documentation doesn't say anything about what it can return.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
  • If I set status in servlet i am not getting status code in jquery. I did the same as you suggested now. – Sunil Kumar Sahoo May 04 '12 at 16:08
  • You tried to see in the debugger what the `textStatus` variable had in it? Same for `xhrObject`? – Florian Margaine May 04 '12 at 16:26
  • Debugger doesnt come inside that function if i set status code. if i dont set status code then it is showing status code as 200. I have written the following in servlet response.setStatus(response.SC_BAD_REQUEST); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("" + strError + ""); out.flush(); out.close(); – Sunil Kumar Sahoo May 04 '12 at 16:32