AJAX onreadystatechange function not always called

Clash Royale CLAN TAG#URR8PPP
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?
onreadystatechange
"www.webpage.com/" + arrayValue
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!");
);
1 Answer
1
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);
This has solved my issue, thank you very much
– Nick
Aug 6 at 15:17
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Exactly what I was going to write. From the Mozilla WebAPI -- "Note: Calling this method for an already active request (one for which open() has already been called) is the equivalent of calling abort()."
– Andy Foster
Aug 6 at 15:10