views:

77

answers:

3

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?

A: 

You can wire up the error function to the whole body like this:

$('body').ajaxError(function() {
    alert("OOPS!")
});
Giorgi
But isn't that less readable than the `ajaxSetup()` approach? I.e., the function here has *nothing* to do with the document's body (put another way, if I could achieve the same exact effect by substituting "body" for *any* other element, this seems like the wrong approach)
Horace Loeb
+1  A: 

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.

JacobM
A: 

There may exist circumstances where it might relate to an individual control - such as when you have an autocomplete that round trips to the database via ajax, as opposed to an entire page like on a submit. This would then determine if you want to isolate the error on a component of the page and if so what the response to the error should be rather than with a more generic approach.


Mark Schultheiss