I'm bound to use native javascript (although a jQuery solution can also work if I convert it to native javascript).
Also, I have no handles to existing AJAX requests so I can't access them directly.
I am searching for something like:
var ajaxRequestsInProgress = document.getAllAjaxRunning();
ajaxRequestsInProgress[1].getStatus(); // will return the status of the request, for example
so I can access this object and check / manipulate existing ajax requests.
This is, shall we say, a little tricky. There is no native way to do it. So we need to do a bit of hacking, modifying the native XMLHttpRequest
functions. Something like this:
var getAJAXRequests = (function() {
var oldSend = XMLHttpRequest.prototype.send,
currentRequests = [];
XMLHttpRequest.prototype.send = function() {
currentRequests.push(this); // add this request to the stack
oldSend.apply(this, arguments); // run the original function
// add an event listener to remove the object from the array
// when the request is complete
this.addEventListener('readystatechange', function() {
var idx;
if (this.readyState === XMLHttpRequest.DONE) {
idx = currentRequests.indexOf(this);
if (idx > -1) {
currentRequests.splice(idx, 1);
}
}
}, false);
};
return function() {
return currentRequests;
}
}());
It can be called with getAJAXRequests()
.
You can see it in action on jsFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With