Set a global error for Ajax requests

Asked

Viewed 37 times

3

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

2 answers

3

2


If you are using jQuery’s AJAX you can use the .ajaxError() which is an event receiver. When you add it to document it records in practice all the errors on that page. An example would be:

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

There is still a possibility in jQuery, using the .ajaxSetup() but jQuery himself advises against and says that it is better to use the method I put on top.

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: http://jsfiddle.net/0q7r97ky/

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

You can use the same logic for other events, such as suggested on MDN:

xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
  • 1

    Thank you! Sanou until my future doubt was whether I could expand this form to other types of event..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.