MRA
MRA

Reputation: 3190

How to learn whether an error occured during a jQuery.ajax() call?

I am trying to build a robust

$.ajax()

call in jQuery, but I am having trouble to understand how to notice whether a call failed.

I understand how to implement done() and fail() callbacks, and they work quite nicely if the call actually returned anything. But it seems to me that the registered functions are only called if the call itself did not end in a HTTP errors such as 404 or 502. See this jsFiddle for an example of what I mean.

So what idiom should I use to catch possible HTTP errors and act accordingly?

Upvotes: 1

Views: 268

Answers (2)

face
face

Reputation: 1505

This might help you. In process of editing your fiddle.

 $.ajax({
     statusCode: {
         404: function() {
             alert("page not found");
         }
     }
 });

EDIT: I tweaked your .fail() function to handle multiple response status codes collectively (I think this should serve what you were looking for). FIDDLE

.fail(function (response) {
    if ($.inArray(response.status, [404, 302, 502]) != -1) {
        $('pre').append("My callback fired, ");
    } else {
        $('pre').append("oops, error? ");
    }
})

Upvotes: 1

kalley
kalley

Reputation: 18462

Along with @face's answer, you may want to switch to $.getJSON. I tested it and all the callbacks were working correctly. I think it has to do with JSONP.

Upvotes: 0

Related Questions