When i running Ajax request in loop, ajax on success does not displays returned data…
Here is code:
url = ["../siteAdmin/statistics/queriesAjax.php", "../siteAdmin/statistics/geographyAjax.php"];
tabContainerId = ['tabs-2', 'tabs-3'];
for(var i=0, len=url.length; i < len; i++){
console.log(tabContainerId[i]);
jQuery("#"+tabContainerId[i]).html('<img src="../assets/images/loading.gif"/>');
jQuery.ajax({
type:"GET",
url:url[i],
data:{ from:from, to:to },
success: function (msg) {
jQuery("#"+tabContainerId[i]).html(msg);
},
error: function (msg) {
showError("Error occurred.", tabContainerId[i]);
}
});
}
In HTML element i just see loading.gif.
Console.log(msg) on ajax success in browser console are displayed. But in HTML element- not.
If i set var i = 0 or var i = 1 data is displayed.
Where i made a mistake?
You’re using the variable
iwithin your success callback, but by the time your callbacks are executed,ihas almost certainly changed.You have to force i to be part of the callback function’s closure. One way to do this is to put the contents of the for loop into an immediately invoked function expression (IIFE):
In effect, this “saves” the value of
iso it is the same when your callback functions use it.I haven’t run this code through lint or an interpreter, so there may be syntax errors.