Define a global error for Ajax requests

3

I have several Ajax requests, and I have not set an error option for any of them. Is there a way to set a global error for all requests? Just as there is sucess: {... only globally without me needing to go one by one and add error: {.. ou fail

    
asked by anonymous 30.06.2015 / 20:57

2 answers

2

If you are using jQuery AJAX you can use the .ajaxError () which is an event drop-in. When you add it to document it actually registers all the errors that are on that page. An example would be:

$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
     $( ".log" ).text( "Houve um erro no ajax!." );
});

There's still a possibility in jQuery, using .ajaxSetup() but jQuery itself advises against saying it's better use the method I put above.

  

Note : Global callback functions should be set with their respective global Ajax event handler methods

If you are using native AJAX you can use a constructor function like this:

function erroAjax(e) {
   alert('Houve um erro no ajax!');
}

function novoXHR() {
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("error", erroAjax, false);
    return xhr;
}

var xhr1 = novoXHR(); // deve funcionar
var xhr2 = novoXHR(); // vai dar erro

xhr1.open('POST', '/echo/html/', true);
xhr1.send('foo=bar');

xhr2.open('POST', 'http://stackoverflow.com', true);
xhr2.send('&');

jsFiddle: link

You can expand this idea and even make a class of yours with the methods of the class. So you can save more information and return this info in error. But I think the example above answers your question.

You can use the same logic for other events, such as suggested in MDN a>:

xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
    
30.06.2015 / 21:46
3

The answer is well broken up here: jQuery's $ wrap. ajax () method to define global error handling , but the answer would basically be to use $(document).ajaxError

$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
    alert("Erro ajax!");
});

.

    
30.06.2015 / 21:14