tags:

views:

23

answers:

3

My webserver returns an json response to any ajax request no matter what. If the response was a success, it returns the json with the status code of 200. If there was something wrong, it'll return the json with a status code of 400 or 500. I need to get that information, even if the request is a 400 or 500 because the json response has the error message with it, which needs to be presented to the user.

The problem is that the jquery $.ajax function does not give you access to the response object if the status code is anything other than 200, correct? Is there a way to do this?

+2  A: 

Sure it does. The success function is called only when the call was successful, but the error callback is called when there's been an error — including an HTTP status other than 200.

$.ajax({..., error: function(XMLHttpRequest, textStatus, errorThrown) { ... } });
VoteyDisciple
This isn't the same, since you don't have a JSON object here like he has in `success`.
Nick Craver
Ooh. Quite right. I misread the question. I agree with klausbyskov here that the idea of returning non-200 HTTP status codes for a situation where the server can still generate a valid JSON response is a little unnerving.
VoteyDisciple
@VoteyDicipline, what would be the correct way to do this then? The user tries to fire an ajax POST request, but the request contains invalid data, the response code should be not 200, correct? Returning a 200 response with "Error" somewhere in the json seems more wrong, IMO.
nbv4
The HTTP status describes whether the server was able to process the HTTP request. If your server gets data, looks at the data, and returns a result, that's a `200`. For comparison, consider what happens if you Google "khjafhkagjf ahkfgahjkgdf" — that's a completely invalid query, but Google can still receive it, understand that it's invalid, and return a result — the page you get is `200`. That's different than visiting www.google.com/404 where the server cannot possibly service your request.
VoteyDisciple
+2  A: 

You could override the jQuery.httpSuccess method used internally to determine if a request is successful, for example:

jQuery.httpSuccess = function() { return true; }

This will let your success handler execute even on status codes in the 400/500 range.

Note: this may change to jQuery.ajax.httpSuccess later.

Nick Craver
+1, interesting stuff..
Gaby
A: 

You can retrieve it easily :

$.ajax({
    // your options
    success: function(data, xhr) {
      alert(xhr.status);
    }
});
Arnaud F.
`success` does not get called when the status code is anything other than 200.
nbv4
Hum, i should say no, other statuses are consider as a success, see : `// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status `
Arnaud F.