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!
Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event.
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.
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!
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With