For some reason, I am encountering an issue with my function that involves a large for loop. When I print out the value of j inside the AJAX success call, it consistently shows as 6 (console.log(j) = 6 6 6 6 6 6). However, when I display console.log(j) before the success function, it displays the correct sequence of values from 0 to 5. Can anyone provide any insights into why this discrepancy is occurring or suggest what might be missing in my code?
function loadInfo() {
var knuckles = "";
for (var i = 1; i < channels.length; i++) {
knuckles += "&login=" + channels[i];
}
$.ajax({
url: url1 + channels[0] + knuckles,
type: "GET",
headers: {
"Client-ID": "XXXXX"
},
success: function (json) {
for (var j = 0; j < channels.length; j++) {
console.log(j); // This logs the correct values
$.ajax({
url: url2 + json.data[j].login,
type: "GET",
headers: {
"Client-ID": "aa20kjc6z0zwwogqpz3wqn3245qzc9"
},
success: function (json2) {
console.log(j); // This logs incorrect values
var sonic;
if (json2.stream != null) {
sonic =
json2.stream.game +
"</div>" +
'<div class="info">' +
"Apple" +
"</div>";
} else {
sonic =
'<span class="offlineText">Offline</span>' +
"</div>" +
'<div class="info">' +
"Not currently streaming" +
"</div>";
}
$("#streamerInfo").append(
streamerBoxStart +
'<div class="icon" style="background-image: url(' +
json.data[j].profile_image_url +
'); background-size: cover;">' +
"</div>" +
'<div class="nameGame">' +
json.data[j].display_name +
" ★ " +
" " +
sonic
);
}
});
}
}
});
}
I'm wondering if this could be related to variable scope, loop behavior, or perhaps something crucial that has escaped my attention. Please note that this segment is just one part of my overall code, with other components present above and below it.