Question

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?

Was it helpful?

Solution

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? ");
    }
})

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top