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’
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:
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: