Here's the code snippet I'm working with:
for (var i = 0; i < list.length; i++) {
$.when(
$.ajax({url: "./dorequest.php?id=" + list[i],
success: function(response){ jsonFriendlist = response; }}) ).done(
function(jsonFriendlist) {
var friendListObject = JSON.parse(jsonFriendlist);
if (!jQuery.isEmptyObject(friendListObject)) {
var rawListFriend = friendListObject.friendslist.friends;
for (var j = 0; j < rawListFriend.length; j++) {
console.log(i);
playerLinkList[i].listFriends.push(rawListFriend[j].id);
}
}
}
);
}
The issue I'm encountering is that each call to the "done" function is returning with i = 13, which is the length of the list variable. This happens because the asynchronous nature of the AJAX request means that by the time the done function is called, the main thread has already finished the loop and i equals 13.
My query is how can I prevent this behavior and ensure that i is frozen or passed by copy when the ajax request is sent?
Thank you,