Sometimes your slick Ajax application may have submitted a request that you no longer care about and want to abort. For example, perhaps you've implemented a type-ahead feature and the user has now typed another character prior to the first results returning. Or perhaps you fetch values for other parts of a form based on user selections and the user changed their choice prior to the first response returning.
I was surprised to see that the
prototype.js library does not include an abort method for its Ajax.Request object. So, here's my implementation of Ajax.Request.abort():
/**
* Ajax.Request.abort
* extend the prototype.js Ajax.Request object so that it supports an abort method
*/
Ajax.Request.prototype.abort = function() {
// prevent and state change callbacks from being issued
this.transport.onreadystatechange = Prototype.emptyFunction;
// abort the XHR
this.transport.abort();
// update the request counter
Ajax.activeRequestCount--;
};
To use this function, you need to keep a handle on the Ajax request you want to abort. So, somewhere in you code you'll have something like:
var myAjaxRequest = new Ajax.Request(requestUrl, {[request options]});
If you want to abort that request, simply call:
myAjaxRequest.abort();
Update - Feb. 22, 2008:It was pointed out in the comments that the
Ajax.activeRequestCount
can occasionally become negative. I have been able to replicate that situation, while at the same time confirming that it does not consistently happen. This leads me to believe that it's most likely a timing issue such as the
abort
is issued after the response has already started to be received and/or processed so that both the response processing decrements the counter as well as the abort.
My personal work-around for this is to add these lines to the end of my
onComplete
handler:
if (Ajax.activeRequestCount < 0) {
Ajax.activeRequestCount = 0;
}
I don't want to remove the counter decrement from the
abort
function or else cleanly aborted requests will leave the activeRequestCount > 0 when there are no real outstanding requests.
If anyone has a better solution, I'd be interested to hear from you.