i like to catch any ajax 401 Unauthorised
exception, but do no like to change all my ajax queries. Is there a way to change it for any $.ajax call like (overwrite any error
handler) ?
The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.
Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the . ajaxError() method are executed at this time. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
This occurs when jQuery falls into its error callback handler (this callback built into DataTables), which will typically occur when the server responds with anything other than a 2xx HTTP status code.
you can use the global ajax event handlers .ajaxError()
$( document ).ajaxError(function( event, jqxhr, settings, exception ) {
if ( jqxhr.status== 401 ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
}
});
You can do something like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 401) {
alert('HTTP Error 401 Unauthorized.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
This will catch error in any of your ajax
calls.
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