Essentially, I have a standard ajax function set up like this:
function ajax_request(rest_req, url, success_callback, fail_callback) {
var xhttp = new XMLHttpRequest;
xhttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
success_callback(this);
}
else {
fail_callback(this);
}
}
};
xhttp.open(rest_req, url, true);
xhttp.send();
}
When using the ajax function in this manner:
(function() {
function setup() {
ajax_request("GET", "url1", function(xhttp) {
response = JSON.parse(xhttp.responseText);
if (response["error"] != 100)
document.getElementById('url1-reading').innerHTML = '---';
else
document.getElementById('url1-reading').innerText = response["response"];
},
function() {}
);
ajax_request("GET", "url2" , function(xhttp) {
response = JSON.parse(xhttp.responseText);
if (response["error"] != 100)
document.getElementById('url2-reading').innerHTML = '---';
else
document.getElementById('url2-reading').innerText = response["response"];
},
function() {}
);
console.log('Refresh');
}
setInterval(setup, 1000);
})();
This code is not behaving as expected. Sometimes, the results intended for url1's success_callback end up inside url2's success_callback.
In other words, the response
variable within the ajax_call for url1 is mistakenly being used as the response variable for url2. It seems that the ajax_call does not correctly associate the success_callback with its designated URL despite it being passed as a parameter.
Coming from a C++ background, this concept is challenging to grasp. How can I ensure the correct assignment of success_callbacks to their respective URLs? Please let me know if there are any unclear points that need clarification.