0

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>
  • it's a story as old as time. Look [here](https://stackoverflow.com/questions/10652887/is-it-posible-to-use-ajax-respone-outside-of-it) for example or [here](https://stackoverflow.com/questions/21052258/passing-data-outside-ajax-call-jquery)... – dhilt Dec 10 '17 at 22:52

1 Answers1

0

The callback code only runs once the request returns, whereas the printing code runs straight away after the request is sent.

Jackoson
  • 81
  • 6