Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, how can I test if any AJAX call is running in the background at a given moment?

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.

like image 823
Shahar Avatar asked May 15 '14 09:05

Shahar


1 Answers

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.

like image 70
lonesomeday Avatar answered Sep 28 '22 15:09

lonesomeday