I'm trying to write specific elements from a JSON file from an external REST API to a local dictionary variable that I can use in my JS code. My AJAX GET request works fine, but I can't seem to access the obtained data outside the code when I print my variable outside the AJAX request, it returns undefined. I know I need to use callback functions to make this work, but I can't seem to do it properly. This is what it looked like before I used callback functions:
<script>
var LeagueTable = []
$.ajax({
url: 'http://api.football-data.org/v1/competitions/445/leagueTable/?',
headers: {
'X-Auth-Token':''
},
method: 'GET',
dataType: 'json',
success: function(data) {
console.log(data)
for ( i = 0; i < 20; i++) {
LeagueTable[data.standing[i].teamName] = data.standing[i].position
}
}
});
// LeagueTableAppend(LeagueTable)
console.log(LeagueTable["Watford FC"])
</script>
But the dictionary isn't appended outside of the ajax request, so I tried altering this with callback functions, but I'm not really sure how to implement them. I just wanted the LeagueTable dictionary to retain the values added to it in the for loop. And then this was my attempt at using callback functions, but it doesn't work.
<script>
var LeagueTable = []
function getdata(){
$.ajax({
url: 'http://api.football-data.org/v1/competitions/445/leagueTable/?',
headers: {
'X-Auth-Token':''
},
method: 'GET',
dataType: 'json',
success: handleData
});
}
function handleData(data){
// console.log('success: '+ JSON.stringify(data));
for ( i = 0; i < 20; i++) {
LeagueTable[data.standing[i].teamName] = data.standing[i].position
// console.log(JSON.stringify(data.standing[i].teamName) + ':' + data.standing[i].position);
}
}
getdata(handleData)
// LeagueTableAppend(LeagueTable)
console.log(LeagueTable["Watford FC"])
</script>