I'm sure this question is not uncommon and has been answered yet, but i can only find questions where it is answered in JQuery (which i dont understand).
I'm having a AJAX Function in which data from a php script is retrieved. One of the parameters of the AJAX function is a callback-function, which gets called after the data has been successfully retrieved.
However, if the AJAX Function gets called multiple times, only the last callback-function gets called. I've already read that this might be some variable scope issue.
Now my question is: How can i get it to work so that every time i call the AJAX function, the corresponding callback function gets correctly called?
What I've tried so far:
I figured out that if i made the AJAX call synchronous i would not have this issue. But that's something i really dont want to do, because sometimes it takes very long to retrieve the data.
Here's the AJAX function:
function getData(callback)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
var data = JSON.parse(xmlhttp.responseText);
callback(data);
}
};
xmlhttp.open("GET", "../PHPScripts/getData.php?q1=someparameters", true);
xmlhttp.send();
}
And here are the two callers:
function createElements()
{
[...]
createAnotherElement();
var callback = function()
{
[gets successfully called]
};
getData(callback);
}
function createAnotherElement()
{
var callback = function()
{
[Never gets called]
};
getData(callback);
}
Any help is greatly appreciated.