-1

I am setting a variable within the

$.getJSON("filename.json", function(data){ ... }); 

method, and printing the variable immediately after calling this function. The console then tells me that my variable does not exist. Why is this happening and how can I resolve it?

Bugged Code:

 function 
     $.getJSON("dimple1.json", function(data){
          var data1 = data;
          console.log(data1);
     });
         console.log(data1); //gives:   "ReferenceError: data1 is not defined"
    }

console output:

[14:40:46.044] Unknown property 'box-sizing'.  Declaration dropped.

[14:40:46.049] ReferenceError: data1 is not defined

[14:40:46.103] not well-formed

[14:40:46.104] ({information:[{month:"January", 'Unit Sales':"18000"}, {month:"February", 'Unit Sales':"6000"}, {month:"March", 'Unit Sales':"20000"}, {month:"April", 'Unit Sales':"35000"}, {month:"May", 'Unit Sales':"13000"}, {month:"June", 'Unit Sales':"4000"}, {month:"July", 'Unit Sales':"6000"}, {month:"August", 'Unit Sales':"9500"}, {month:"September", 'Unit Sales':"28000"}, {month:"October", 'Unit Sales':"21000"}, {month:"November", 'Unit Sales':"10000"}, {month:"December", 'Unit Sales':"6000"}]})
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144

1 Answers1

0

This is because data1 is being defined in the 'closure' of the getJSON call. As far as the rest of the script is concerned, it does not exist.

If you defined the variable outside of the getJSON call, like this:

var data1

function 
 $.getJSON("dimple1.json", function(data){
      data1 = data;
      console.log(data1);
 });
     console.log(data1); //gives:   "ReferenceError: data1 is not defined"
}

you could reference the variable, but the value would still be empty - as the log happens BEFORE the value has been set.

Gary Stevens
  • 693
  • 8
  • 20
  • Ah yes, I started with it like this and the log statement told me that data1 was undefined, then I switched it to my current method not paying attention to scope. Whoops! – user1708754 Mar 17 '14 at 15:21