0

I want to store the JSON file in a variable, and use it later in the script. But the variable just shows up as undefined.

Here's what I have done.

var citiesList;
var countryList;
$.getJSON("http://localhost:80/weather/js/country.json", function(data){
    citiesList = data;
    countryList = Object.keys(citiesList.countries);
});

Now when i try to access the contents of citiesList, an error shows up saying cannot read property length of undefined.

This is how I try to access the contents

var country = $('#countrySelect').val();
    $('#citySelect').html('');
    for (var i = 0; i < citiesList.countries[country].length; i++) {
        $('#citySelect').append('<option>' + citiesList.countries[country][i][0] + '</option>');
    }

The same exact code works when async is set to false. But I am looking for the proper way of using getJSON to avoid such errors.

Thanks in advance guys.

Sachin
  • 11
  • 1
  • 4
  • What is content of `country.json` – Satpal Mar 02 '17 at 12:47
  • 2
    See also [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) for more related reading. – James Thorpe Mar 02 '17 at 12:50
  • you haven't shown the flow, but it's likely you're trying to access the variable before the $.getJSON method has returned - it runs asynchronously. So basically, any manipulation of the returned data that you want to do must be within (or triggered from) the callback function that you specify as part of the $.getJSON call. Otherwise, there is no guarantee that the data you want will actually exist. – ADyson Mar 02 '17 at 13:25

0 Answers0