I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm going wrong... but I don't want to make the calls synchronous for obvious reasons.
Here is the JavaScript code I'm using to create a new XMLHttpRequest:
function createRequest(){
if(window.XMLHttpRequest)
return new XMLHttpRequest;
else
return new ActiveXObject("Microsoft.XMLHTTP");
}
This is my send request function (to send the requests):
function sendRequest( url, callback){
request = createRequest();
if(typeof callback === 'function'){
request.onreadystatechange = callback();
}
request.open("GET", url, true);
request.send();
}
And finally, my callback function:
function handleData(){
return function(){
if (request.readyState == 4 && request.status == 200) {
serverResponse = JSON.parse(request.responseText);
switch(Object.keys(serverResponse)[0]){
case "a": function1(serverResponse.a,"a"); break;
case "b": function2(serverResponse.b,"b"); break;
}
}
}
I am making my calls like this:
window.onload = function () {
sendRequest('url' , handleData);
sendRequest('url2', handleData);
}
Please note that this is a simplified version of my code. In the switch statement, I am calling function1 and function2 to handle the JSON response from the server. The problem occurs when I try to make two consecutive calls - only the second one succeeds. It seems like the second call is overwriting the first one.
I attempted to create separate functions for handling the data, so I had handleData1()
and handleData2()
instead of a single handleData()
. But again, only the second call was successful. When I added console.log(request)
in both functions, I only saw JSON data for the second function being processed. Sometimes the second function was called multiple times, up to 4.
For clarification, handleData2
does not depend on data from handleData1
.
If you have any further questions, please feel free to ask. Thank you!