Reputation: 446
I have the following code which retrieves the variable hf using getJSON
$.getJSON('../scripts/json.php', function(json) {
var user_function = json.hf;
});
I have the following auto_refresh function
// Refresh dashboard stats
var auto_refresh = setInterval(function(){
$('#today').load('index.php #today');
$('#_7days').load('index.php #_7days');
$('#_30days').load('index.php #_30days');
$('#allTime').load('index.php #allTime');
$('#sidebar').load('../' + user_function + '/index.php #sidemenu', function() {
$('#sidebar li:not(.complete)').each(function () {
if($('a', this).attr('href') == document.URL) {
$(this).toggleClass('inactive active');
}
});
});
}, 20000);
I want to pass the variable user_function from the getJSON call to the auto_refresh, but keep getting back 'undefined'
Upvotes: 0
Views: 161
Reputation: 5703
You have two issues here.
Issue #1: Out of Scope.
You instantiate var user_function inside an anonymous function. Since javascript has function level scope, your auto-refresh function will not have access to view this variable.
Solution: Instantiate user_function outside of both functions:
var user_function;
$.getJSON('../scripts/json.php', function(json) {
user_function = json.hf;
});
var auto_refresh = setInterval(function(){
//access user_function
}, 20000);
Unfortunately, this will not completely solve your problem as you have a second problem.
Issue #2: Asynchronous
Because user_func gets set based off some ajax respone, the remainder of your code will not have access to it until this ajax response returns something. This means that you need to ensure the kickoff of any logic requiring user_func takes place inside of a callback.
Solution:
var user_function;
$.getJSON('../scripts/json.php', function(json) {
user_function = json.hf;
createAutoRefresh();
});
function createAutoRefresh() {
var auto_refresh = setInterval(function(){
//access user_function
}, 20000);
}
Upvotes: 2
Reputation: 24226
I suspect the user_function
variable will be out of scope before your auto_refresh
function is called.
Try calling the auto_refresh
function inside the JSON call-back.
Upvotes: 0