JQuery: clean handling for faulty state code from ajax

I have a very simple ajax request:

$.get(url, data)
   .done(function () { })
   .fail(function () { })

      

If url

there is an error, it will return a status code such as "500". Apparently jQuery is considering its promise for the object jqxhr

at this point as it will fulfill .done

, not .fail

. My question is twofold:

Default when .fail

triggered with respect to ajax and is there a way to change this default?

Second, the only way to have special handling for a bad request is something like this:

.done(function (msg, tm, jqxhr) {
   if (jqxhr.status < 200 || jqxhr.status >= 300) performFailure();
});

      

Is there a better way to find and handle responses that would be considered "bad?"

+3


source to share


3 answers


Looking at this, it seems that jQuery is actually using it .fail()

correctly. The problem was that my server was throwing 200 for certain errors. In other words, this is not a jQuery problem to start with.



0


source


From jQuery doc . get () :

If a request with jQuery.get () returns an error code, it will fail silently unless the script also called the global .ajaxError () method. Alternatively, as of jQuery 1.5, the .error () method The jqXHR object returned by jQuery.get () is also available for error handling.



(emphasis mine)

I haven't done much with error handling, but it looks like you might need to call an ajaxError to fail the error condition.

0


source


Check the docs for the .ajax function, it has a very nice error handler: http://api.jquery.com/jQuery.ajax/ You can use this instead of the get () function. (the two are essentially the same, as you can see on this page: http://api.jquery.com/jQuery.get/ );

An example with your code:

     $.ajax({
       url: url,
       data: data,
       error: /*error function*/,
       success: /*success function*/,
     });

      

0


source







All Articles