priestc
priestc

Reputation: 35150

getting the error response from an ajax request in jquery

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?

Upvotes: 0

Views: 2959

Answers (3)

Arnaud F.
Arnaud F.

Reputation: 8452

You can retrieve it easily :

$.ajax({
    // your options
    success: function(data, xhr) {
      alert(xhr.status);
    }
});

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630349

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.

Upvotes: 3

VoteyDisciple
VoteyDisciple

Reputation: 37803

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) { ... } });

Upvotes: 2

Related Questions