It's the second one (chronologically in your code) that doesn't get hit. That's because it hasn't been set yet. The callback inside getJSON
gets invoked asynchronously after returning from the server.
var themeData;
// FIRST -- themeData currently null
$.getJSON("json/sample.js", function(data) {
// THIRD -- now themeData has a value, and gets logged
themeData = data.theme;
console.log(themeData.sample[0].description);
});
// SECOND -- themeData still null
console.log(themeData.sample[0].description);
If you really need to call a method "after" getJSON
, then embrace the idea of callbacks. Use something like this.
var themeData;
function myCallback(data) {
console.log(data.sample[0].description);
}
$.getJSON("json/sample.js", function(data) {
themeData = data.theme;
console.log(themeData.sample[0].description);
myCallback(themeData);
});
Edit
You could also force a synchronous call instead using async: false
of the JQuery ajax function.
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
async: false
});