JavaScript generally works as async functions with callbacks -- trying to force this into sync functions is generally a beginners mistake which people regret later.
Your ajax call is typically such a async call, and the function
you specify is the call back which is executed when the ajax call completes.
In your code, the console.log executes before the ajax call completes.
Just move the console.log inside the callback like this:
function getMyJson() {
var json;
$.getJSON('/cdnBuffet.json', function (data) {
json = data;
console.log(json); // will now show the data...
});
}
If you actually need to return it to the calling function getMyJson
, just extend the programming paradigm for getMyJson
to have a callback as well, like:
function getMyJson(myCallback) {
var json;
$.getJSON('/cdnBuffet.json', function (data) {
json = data;
console.log(json);
myCallback(json); // this will return the data to the callback
// specified by the use of the function
});
}