0

So, here's the code

$(document).ready(function (){

    $.get("json_family.php", {}, function(data) {
        families = data;
    }, 'json');

    console.log(families);

// Some other codes here
});

And here's what happens when I try to run it:

Uncaught ReferenceError: families is not defined

So, what gives? I thought variables declared without the var keyword would be global no matter where it is declared.

starleaf1
  • 2,701
  • 6
  • 37
  • 66
  • This needs some more explanation about when declared/undeclared variables are created. – sabithpocker Feb 24 '16 at 17:42
  • 1
    Undeclared variables will be global, but they are [not created before code execution](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var). Your code `families=data` will be executed only after the requested resource is loaded via ajax. So at the time you are logging the variable `families` does not exist and throws error. – sabithpocker Feb 24 '16 at 17:48
  • I read the possible duplicate. So, to summarize, this won't work unless: a) I call `console.log()` from inside the `get` or b) I wrap `console.log()` inside another function, and call _that_ function from inside the `get`. Is that correct? – starleaf1 Feb 25 '16 at 01:43

0 Answers0