Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax - avoiding error() callback when statusCode() callback invoked

I'm using jQuery.ajax() to connect to my back end service. I have configured an error() handler and a statusCode() handler. They both work fine, but when my statusCode handler gets fired the error handler also fires (the error handler is actually fired first). I would prefer this not to happen. I am assuming this is possible without having to hack the error handler code?

My code looks something like this:

$.ajax({
    ...
    error: function(...) { 
        // process a general type of error here
    },
    statusCode: {
        401: function() {
            // process a specific authentication failure
        }
    }                 
});

So how can I avoid the error() handler firing when the HTTP status code is 401?

Thanks for bothering to read!

like image 539
Lee Francis Avatar asked Feb 27 '12 12:02

Lee Francis


People also ask

What triggers jQuery AJAX error?

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event.

How do I force AJAX call error?

If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function. @dallin because it allows you to not duplicate code. The server might respond with code 200 which triggers the "success" callback.

How does AJAX work in jQuery?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!


1 Answers

You can easily check the status code inside the error callback. The first parameter should be XMLHttpRequest (or jqHXR depeding on your version of jQuery) object. Check the 'status' property for the status code of the error handle accordingly.

E.g.

error: function(a, b, c){
  if(a.status != 401){
    // handle other errors except authentication

  }
}
like image 129
Dave Becker Avatar answered Oct 16 '22 17:10

Dave Becker