1

Possible Duplicate:
JavaScript asynchronous return value / assignment with jQuery

I have the following javascript code, the time.php file has minute and hour output using json_encode function. If I move console.log inside the getJSON function it finds the correct values, however when I move it outside the function it shows as undefined.

var my_hour;

$.getJSON('../scripts/time.php', function(data) {
    my_hour = data.hour;
});

console.log(my_hour);
Community
  • 1
  • 1
bland_dan
  • 448
  • 3
  • 8
  • 19

3 Answers3

1

it's because it's asynchronous. Ajax request made by $.getJson async call your script and variables my_hour is initialized after your console.log(my_hour).

If you want it to work that way, then you should put console.log in some setInterval.

http://www.w3schools.com/jsref/met_win_setinterval.asp

var interval = setInterval(function(){
   if (my_hour != undefined){
     console.log(my_hour);
     clearInterval(interval);
   }
}, 200);

But it's it's not a good practice anyway.., your code should be placed in callback function as mentioned above.

Kamil Lach
  • 4,519
  • 2
  • 19
  • 20
1

The "$.getJSON" call is asynchronous; the interaction with the server takes time but the browser does not wait for it to finish. Thus, your code after the function call runs immediately, a long time before the callback runs.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0
var my_hour;

$.getJSON('../scripts/time.php', function(data) {
    my_hour = data.hour;
    console.log(my_hour);
});
thinkdevcode
  • 921
  • 1
  • 8
  • 13