-5

I have already read Surprised that global variable has undefined value in JavaScript.

But my problem is differ because I have not created same variable name inside..

$(document).ready(function() {
    var all_ap;
    var url = "http://localhost/example/php-code/json.php";
    $.getJSON(url, function(result) {
        all_ap = result;
        console.log(result);
    });
    console.log(all_ap);
});

These are the console results.

undefined
(6) [{…}, {…}, {…}, {…}, {…}, {…}]

Seems like console.log(all_ap); works before console.log(result); according to results of above.

Why is that? How should I make all_ap variable works?

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

Because $.getJSON is asynchronous function thus callback provided to it gets called after it's finished in the future. That's why your console.log(all_app) gets called first because it's called synchronously just after $.getJSON.

lukaleli
  • 3,427
  • 3
  • 22
  • 32
  • Thanks for the answer. Can you please tell me that how I modify above code to getJSON result to global variable? I read https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call. But It is hard to understand it. Can you please edit your answer how I correct my issuie? – I am the Most Stupid Person Sep 27 '17 at 04:16