Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery catch any ajax error

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) ?

like image 482
MR.ABC Avatar asked Aug 01 '13 09:08

MR.ABC


People also ask

How do you handle errors in AJAX call?

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.

What triggers jQuery AJAX error?

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.

What is an AJAX error?

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.


2 Answers

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." );
    }
});
like image 142
Arun P Johny Avatar answered Oct 11 '22 11:10

Arun P Johny


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.

like image 21
palaѕн Avatar answered Oct 11 '22 10:10

palaѕн