0

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'

1
  • To greatly improve the efficiency of your script, load index.php once and use find to extract the relevant elements. Commented Sep 13, 2011 at 12:26

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ideal Skylar, I'd tried instantiating user_function outside both functions but couldn't understand why this still hadn't resolved the issue, but I now understand that I had a second issue. I have used your suggestions and it's working perfectly.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.