Alex
Alex

Reputation: 5705

ReferenceError: Can't find variable error

I have this code:

$(document).ready(function(){
    var callPage = function(){
        $.post('/pageToCall.php');
    };

    setInterval('callPage()', 60000);
});

and it gives me the error ReferenceError: Can't find variable: callPage. Why?

Upvotes: 4

Views: 10498

Answers (3)

DenisPostu
DenisPostu

Reputation: 599

function callPage()
{
    $.post('/pageToCall.php');
};

$(document).ready(function()
{
    setInterval('callPage()', 60000);
});

It happens because callPage's scope is the anonymous function

Upvotes: 1

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26739

Try setInterval(callPage, 60000);.

If you pass a string to setInterval, then this string is evaluated in global scope. The problem is that callPage is local to the ready callback, it is not global.

There is hardly ever a reason to pass a string to setInterval (setTimeout). Always pass a function (to avoid exactly this kind of errors).

Upvotes: 9

Quinn
Quinn

Reputation: 71

I suspect it's because callPage is a variable scoped to the anonymous function you're creating in the document.ready event. If you move the callPage definition outside that, does it work?

Upvotes: 2

Related Questions