Ad
Level Up Javascript Variabe To Global Scope
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad