I have what is probably a pretty simple question about how to make use of a JSON object returned by an Ajax call for use later in my program. I am trying to do it by declaring my own local array of object and putting the values I want in it, but that is failing because it is apparently unable to find my array.
Here is the code:
function getUsers() {
var users = [
{ name: "ESL_SC2", displayName:"", logo:"", url:"" },
{ name: "OgamingSC2", displayName: "", logo: "", url: "" },
{ name: "cretetion", displayName: "", logo: "", url: "" },
{ name: "freecodecamp", displayName: "", logo: "", url: "" },
{ name: "storbeck", displayName: "", logo: "", url: "" },
{ name: "habathcx", displayName: "", logo: "", url: "" },
{ name: "RobotCaleb", displayName: "", logo: "", url: "" },
{ name: "noobs2ninjas", displayName: "", logo: "", url: "" },
{ name: "MedryBW", displayName: "", logo: "", url: "" }
];
for (var i = 0; i < users.length; i++) {
var user = users[i].name;
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/channels/' + user,
headers: {
'Client-ID': 'xxxxx'
},
success: function (data) {
console.log(users[i].displayName + " is the display name");
users[i].displayName = data.display_name;
users[i].logo = data.logo;
users[i].url = data.url;
}
});
}
}
This immediately fails with this error:
getStreamData.js:22 Uncaught TypeError: Cannot read property 'displayName' of undefined(…)
Obviously, this is not the correct way to do this. So, my question is what is the correct way to store results from an Ajax call so I can use/manipulate them in my code later?
Thanks for the help!