This may be pretty simple but it’s stumping me. I’m trying to return a variable in javascript to another variable outside of the function’s scope. For some reason, the assignment isn’t occurring. Here’s my code:
var time = Math.round(((new Date()).getTime())/1000);
// first call to get data
var power_now = get_data(<%= @user.id %>, time);
function get_data(user_id, timestamp){
var targetURL = "get/user_data?time_now="+timestamp+"&user_id="+user_id;
var power = 0;
$.get(targetURL, function(data){
power = data[0]['power'];
alert(power);
})
return power;
}
$('body').html('<h1>'+power_now+','+power_then+'</h1>')
If I place alert(power) within the .get function, the value is correct; however if I place it outside of the .get function, the value is 0.
Maybe I’m missing something about scoping in javascript?
Thanks!
getis a synonym for.ajaxwith some specific parameters set. The first A in AJAX is Asynchronous. This means that the code is not executed immediately, it sends off the request and moves on. Therefore the assignment of that variable does not occur until after the return statement.Instead, you should move the code into the callback: