Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX error handling with jQuery: should I use $.ajaxSetup() or $.fn.ajaxError()

I want to alert the user whenever there's an AJAX error. You can do this via $.ajaxSetup:

$.ajaxSetup({ 
  error: function() {
    alert("OOPS!")
  }
});

But the jQuery docs recommend against this:

Note: Global callback functions should be set with their respective global Ajax event handler methods-.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()-rather than within the settings object for $.ajaxSetup().

So I guess I'm supposed to do this:

$("#some_random_div").ajaxError(function() {
  alert("OOPS!")
});

This doesn't make sense to me: the AJAX error callback pertains to my application as a whole, not a specific page element. So why should the callback function be associated with an individual page element?

So: why do the jQuery docs recommend using what looks like a less readable approach, and which approach is best?

like image 570
Tom Lehman Avatar asked Jul 27 '10 19:07

Tom Lehman


1 Answers

The typical use is that the specific page element you bind ajaxError to is the div where your error message is going to be displayed; perhaps a "flash" message div at the top of your page. This way you have direct access to that div to append your message.

But if you're not using a particular DOM element as your message display area, you could certainly bind it to $(document) or some other such global element.

like image 109
Jacob Mattison Avatar answered Nov 15 '22 17:11

Jacob Mattison