views:

120

answers:

2

I've used jQuery's ajaxSend and ajaxStop to show a spinner whenever ajax requests are active. It works except when some of my plugins abort their ajax requests, ajaxStop does not trigger and will not trigger until after the page is refreshed. It seems like the aborted request still counts to jQuery. Can I make ajaxStop trigger or is there a better way?

+1  A: 

I would use the complete event instead - that runs no matter what:

complete (Local Event)
This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

$.ajax({
   complete: function(){
     // hide your spinner
   }
 });

not sure if you need this, but you can trigger the ajaxStop event. $(this).trigger('ajaxStop');

Dan Heberden
As I understand it `complete` runs whenever any ajax event completes. That means that if I use it to hide my spinner it will hide when one request completes even if others are still running.
Jake
+1  A: 

Well I figured out a way that I quite like. Patch the XMLHttpRequest abort method so that it will decrease jQuery's ajax counter and trigger the handler if it's the last request. Not sure yet how well it will work across browsers.

var old_abort = XMLHttpRequest.prototype.abort;
XMLHttpRequest.prototype.abort = function(){
    jQuery.proxy(old_abort, this)();
    if ( jQuery.active-- === 1 )
        jQuery.event.trigger( "ajaxStop" );
};
Jake