-1

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?

aitor
  • 2,281
  • 3
  • 22
  • 44
  • getJson is asynchronized function, it's means your interpreter not wait for json request. locations variable show data after JSON request complete – Sandeep Feb 03 '19 at 08:39

1 Answers1

0

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>
Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
  • As Andy had mentioned in his answer already, you can not put a console outside the function. You will always get `undefined` in this scenario. Possible solutions are given in the marked duplicate question. – palaѕн Feb 03 '19 at 09:12
  • 1
    Ok, I'm reading. It has a lot of info. Thank you very much! I think, I'm understanding now. – aitor Feb 03 '19 at 09:16
  • Finally, this answer solves the question. Thank you for your patient. – aitor Feb 03 '19 at 09:23