Geuis
Geuis

Reputation: 42267

Async xmlhttprequests failing, synchronous aren't

I'm running into a strange problem. In the following sample code, if I set asynchronous to true the request fails and Chrome tells me 'failed to load resource'. However, if I switch it to synchronous it goes through fine.

Additionally, if I do multiple xhr requests using this code and its set to async, all requests exhibit the same problem, but the last one is successful. If I set the xhr to synchronous (i.e. false) then all requests go through fine.

To all who will say, 'Just use jQuery', this is for a project that needs to run independently of any libraries. I love jQuery, but not for this.

I am testing this in Chrome6.0.458.1 and Firefox 3.6.4. Here's the code:

    var xhr = window.XMLHttpRequest?
        new XMLHttpRequest():
        new ActiveXObject('Microsoft.XMLHTTP');

    var doxhr = function(url,cb){
        xhr.open('get',url,true);
        xhr.onreadystatechange = function(ev){
            console.log(xhr.readyState, xhr.status );
            //if(xhr.readyState === 4 && xhr.status === 200){
            //  cb(xhr.responseText);
            //}
        }
        xhr.send(null);
    }

Upvotes: 0

Views: 3217

Answers (1)

Andrew
Andrew

Reputation: 14526

I'm not sure the two problems are related, but if you plan on making multiple XHR requests, you shouldn't reuse the same XHR for each request or you should build a queuing system to stop later requests from stomping the earlier requests. You can probably solve the problem of only the last request completing successfully by wrapping your xhr inside doxhr():

var doxhr = function(url,cb){
    var xhr = window.XMLHttpRequest?
        new XMLHttpRequest():
        new ActiveXObject('Microsoft.XMLHTTP');
        xhr.open('get',url,true);
    xhr.onreadystatechange = function(ev){
        console.log(xhr.readyState, xhr.status );
        //if(xhr.readyState === 4 && xhr.status === 200){
        //  cb(xhr.responseText);
        //}
    }
    xhr.send(null);
}

Upvotes: 4

Related Questions