Andrew Bullock
Andrew Bullock

Reputation: 37398

jQuery ajax with non 200 responses

How do I make success* fire for all status codes?

$.ajax({
    url: "/"
    , dataType: 'json'
    , type: 'POST'
    success: function (data) {
        alert('all good');
    }
});

* note i don't care if its the "success" method that fires, i just want to have the response entity parsed as JSON.

My response entity for a 400 might be some JSON with the details as to why it was a bad request, is there some setting to make this work out of the box with jQuery? Or do I have to hand roll this?

Thanks

Upvotes: 3

Views: 1083

Answers (1)

Andy E
Andy E

Reputation: 344733

Use complete: function () { }, instead of success. In this case, the resulting data won't be parsed by jQuery, but you can do that yourself by performing $.parseJSON() on the XHR object's responseText:

$.ajax({
    url: "/"
    , dataType: 'json'
    , type: 'POST'
    complete: function (xhrObj) {
        var data = $.parseJSON(xhrObj.responseText || "");
        alert('all good');
    }
});

Upvotes: 5

Related Questions