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);
1
  • The proposed duplicate is not generic enough to be considered as a duplicate to this question. Commented Oct 29, 2011 at 16:20

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0
var my_hour;

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.