-2
function getData() {
    var photo,
        comment,
        url;

    $.getJSON('http://url.info/verify/settings.php', function (data) {
        photo = data.photoMSG;
        comment = data.commentMSG;
        url = data.photoURL
    });
    console.log(photo); //undefined
    console.log(comment); //undefined
    console.log(url); //undefined
}

I'm getting undefined in console log for all of them... How to get these 3 vars visible outside of getJOSN block? I know this have been asked x100 times, I tried windiw.varName but still the same thing..

  • 1
    Asynchronous calls are *asynchronous*. Add a `console.log('response received now');` into the callback function...! – deceze Jul 25 '13 at 21:45

2 Answers2

1

It's not a scope issue, it's an asynchronous issue. Everything inside the getJSON handler is asynchronous -- so the console.log calls will usually happen after the variables get assigned. Use an async callback instead:

$.getJSON('http://url.info/verify/settings.php', function (data) {
    photo = data.photoMSG;
    comment = data.commentMSG;
    url = data.photoURL;
    callback(photo, comment, url);
});
function(photo, comment, url) {
    console.log(photo); //undefined
    console.log(comment); //undefined
    console.log(url); //undefined
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
0

Because $.getJSON is doing an ajax call, but the code after that is called before the callback within the getJSON is called. So the vars are still undefined. A typical "problem" with asynchronous behaviors.

calamari
  • 80
  • 5