Ad

Level Up Javascript Variabe To Global Scope

- 1 answer

I'm trying to include an external JSON file in a script:

var locations;

$.getJSON(themeUri + '/resources/location.json', function(result){
  locations = result;
  console.log(locations); // it shows right results.
});

console.log(locations); // undef

locations isn't in the global scope. As I read, this is because async function.

So, I tried:

var locations;

function jsonCallback(result){
  locations = result;
}

$.getJSON(themeUri + '/resources/location.json', jsonCallback);

Doesn't work neither. How can I put the JSON contents in a global variable?

Ad

Answer

The problem in your initial example is that the console.log happens before the async call.

// 1. declaration happens
var locations;

// 3. this happens
$.getJSON(themeUri + '/resources/location.json', function(result){
  locations = result;
  console.log(locations); // it shows the right results.
});

// 2. console.log happens
console.log(locations); // undefined

So it makes sense that 2. is undefined, since the callback has not yet happened.

Possible solution:

var locations;

function fillLocations(responseJSON) {
  locations = responseJSON;
  console.log(locations); 
  // Continue to next operation…
}

$.getJSON( 'https://jsonplaceholder.typicode.com/todos/1', function(result){
  fillLocations(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ad
source: stackoverflow.com
Ad