Reputation: 597
I have a global javascript array and i am able to call values from it at the beginning of the function but after that, when i alert leaders[i], it shows as undefined: It appears the problem occurs when there are two ajax calls nested in each other, JS cannot seem to find the values in the array.
JS
function getLeaders(bool) {
var leaders = new Array();
leaders.push('444');
leaders.push('111');
$.ajax({
url: 'url',
crossDomain: true,
type: 'post',
data: {
'clubID': curClub
},
success: function (data) {
for (var i = 0; i < leaders.length; i++)
{
alert(leaders[i]); <===== working fine here
$.ajax({
url: 'someurl',
crossDomain: true,
type: 'post',
data: {
'id': leaders[i] <====== works here
},
success: function(data3) {
alert(leaders[i]); <======= undefined here
var json3 = jQuery.parseJSON(data3);
}
});
}
}
});
};
Upvotes: 0
Views: 286
Reputation: 865
Since the call is asynchronous the value of i is more than likely leader.length by the time the call returns. So you are probably accessing an index that is out-of bounds.
Upvotes: 2