0

With the following jQuery, why can't I use the json var outside of the $.getJSON() function? If i put the console.log() inside the $.getJSON callback function it works, but why not outside?

function getMyJson() {
    var json;
    $.getJSON('/cdnBuffet.json', function (data) {
        json = data;
    });

    console.log(json);  // nothing is shown in console here. Why?
}
Ben
  • 2,917
  • 10
  • 28
  • 47
  • 2
    It's an asynchronous call, do the `console.log(json)` on `.done(function(){})` function [api getJSON](http://api.jquery.com/jquery.getjson/) – SerCrAsH Sep 04 '15 at 22:15
  • 2
    Your getJson function is asynchronous. This means it will get the answer to your console.log before your getJson. – klauskpm Sep 04 '15 at 22:15

3 Answers3

2

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
    });
}
Sergey
  • 1,608
  • 1
  • 27
  • 40
Soren
  • 14,402
  • 4
  • 41
  • 67
0

When the line console.log(json); is executed, your callback function that populates it has not fired yet.

But, if afterwards, you enter the same line in console, you should see that it has some data (assuming $.getJSON did return json).

Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127
-2

The reason your data is not printing out is because the $.getJSON(...) call is asynchronous, which means it executes in the background, and does not block (wait) until it completes before moving on to the next statement (printing). That means that while you are trying to print your data, that data is still being retrieved in the background.

There are many benefits to executing HTTP request in the background, but most commonly it is done so that your application doesn't halt and appear to freeze while the request completes.

In any case, if you really must write functional-style code, then you can always make the call asynchronous by configuring your ajax request at the beginning. You can do so like:

$.ajaxSetup({ async: false });
GPicazo
  • 6,516
  • 3
  • 21
  • 24