Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when an AJAX request starts

Following the spec I've been given for this particular item, I have a few dozen AJAX requests all initiated at the same time, and the results displayed as they complete to give responses as soon as possible.

Currently I have all of the items show as "Loading...", then gradually getting replaced as the requests complete.

Due to limitations placed by the browser, only about five of them actually load at any given time, the others are blocked until earlier ones have completed.

I'd like to know if there's any way of finding out when the block ends and the request is actually sent.

Initial tests using onreadystatechange to detect readyState values other than 4 are not promising - no event is fired until it's complete, at which point I get 2, 3 and 4 in immediate succession (note that for testing, the AJAX responses are artificially delayed by usleeping for a random time)

Any ideas? Or is my only real option to manually implement the blocking part?

like image 934
Niet the Dark Absol Avatar asked Nov 27 '22 07:11

Niet the Dark Absol


1 Answers

The best approximation of this you can actually get is to watch for readyState "1".. which signifies the server connection has been established. This will give you a pretty close estimation as to when the connection actually went live.

I've hacked up at http://jsfiddle.net/r0gknr3w/. Just watch the JS console, and you'll see "1" logged. You say you never saw a readyState 1... but it's definitely there.

var xhr = $.ajax({
    url: "/echo/html",
    xhr: function () {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            console.log(xhr.readyState);
        }
        return xhr;

    }
});
like image 190
joeltine Avatar answered Mar 16 '23 16:03

joeltine