2

Here's my script which I type into Firebug:

var jsonData;

$.getJSON("./js/ohno.JSON",function(data){
    jsonData = data;
});

console.log(jsonData);

Here's the .JSON file contents:

{"oh":"no"}

The first time I run the script in Firebug, it returns "undefined"

The second time I run it (without refreshing the page) it returns the Object.

If I refresh, the same thing happens -- first time running returns "undefined", and second time running it returns the Object.

The .JSON file is

How do I make it so that it returns the Object the first time I run the script?

user1626730
  • 3,783
  • 5
  • 20
  • 24

5 Answers5

9

getJSON is async; meaning that script execution will continue, while it still loads the data.

You have to wait until it finishes.

var jsonData;

$.getJSON("./js/ohno.JSON",function(data){
    jsonData = data;
    console.log(jsonData);
});
keune
  • 5,779
  • 4
  • 34
  • 50
4

You need to place the console.log (and any other code you want to run on data) inside the callback function:

$.getJSON("./js/ohno.JSON",function(data){
    jsonData = data;
    console.log(jsonData);
});

You can also use .ajaxComplete if you feel the need to keep it separate.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
3

getJSON is asynchronous, which is why you have to provide a callback to handle the data. The request is fired off, but it hasn't completed by the time you get to your console.log, so the value is undefined. It finishes a short time later and sets the variable.

Move your console.log handler into your callback, and all should work as expected.

Chris Heald
  • 61,439
  • 10
  • 123
  • 137
1

The anonymous function is an asynchronous callback, so it gets called after your console.log. Here is the right way to do it :

var jsonData;

$.getJSON("./js/ohno.JSON",function(data){
    jsonData = data;
    console.log(jsonData);
});
Fabien Quatravaux
  • 3,737
  • 2
  • 27
  • 33
1

The getJSON function is asynchronous, so the success callback function only gets executed once the request finishes. Your console.dir() is initially executing before the response happens.

Put the console.dir() inside your getJson handler function.

pierdevara
  • 406
  • 2
  • 9