javascriptajaxxmlreadystateonreadystatechange

AJAX onreadystatechange function not always called


I have a AJAX call to retrieve some XML using the below method. Often when I run the code it does not enter the onreadystatechange function until the last iterations of my foreach loop. I'm assuming this is because the calls to "www.webpage.com/" + arrayValue are taking enough time that before the state is updated to "Ready" and then the next request beings. The method probably only runs for the last iteration of the loop because there is no other request to override it and thus has time to become "Ready". From what I've seen online you can't really do a tradition Wait() statement in javascipt or AJAX to give the calls time to complete. So how can I overcome this issue?

var getXML = new XMLHttpRequest();

myArray.forEach((arrayValue, index) => {
    getXML.open("GET", "www.webpage.com/" + arrayValue, true);
    getXML.setRequestHeader('Access-Control-Allow-Credentials', true);
    getXML.setRequestHeader('Authorization', "Basic " + btoa(":something"));
    getXML.send(null);
    getXML.onreadystatechange = function () {
        if(this.readyState == this.DONE) {
             Console.Log("We made it in!");
        }
    }
});

Solution

  • The problem here is that you are trying to use the same XMLHttpRequest object for multiple requests.

    Don't do that. Create a new, clean instance of XMLHttpRequest for each request.

    myArray.forEach((arrayValue, index) => {
        var getXML = new XMLHttpRequest();
        getXML.open("GET", "www.webpage.com/" + arrayValue, true);