Cjueden
Cjueden

Reputation: 1210

setInterval not working in jquery

I can't figure out why its says ajaxcall() doesn't exist, but the $('button').click(function(){ ajaxcall(); }); works just fine

var nameid = 1;
$(document).ready(function(){
    $('button').click(function(){
            ajaxcall();
        });
    function ajaxcall(){
        $.get('mysqlquery.php?id='+nameid, function(data){
            $('#loadbox').append(data+'  ');
        });
        nameid++; 

    }
    setInterval("ajaxcall",1000);
});

Please help me understand why, I think it has to do with scope But I'm stumped. (may be time for a break)

Upvotes: 2

Views: 2405

Answers (4)

Jaspreet Chahal
Jaspreet Chahal

Reputation: 2750

or use the code below

replace setInterval line to

setInterval(function() {
$.get('mysqlquery.php?id='+nameid, function(data){
        $('#loadbox').append(data+'  ');
    });
    nameid++; 
}, 1000); 

or use this

setInterval(ajaxcall, 1000);

or use this

setInterval("ajaxcall()", 1000);

hoep this helps

Upvotes: 0

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

Define the function outside of document.ready, and use the overload of setInterval that takes a function reference:

var nameid = 1;

function ajaxcall() {
    $.get('mysqlquery.php?id='+nameid, function(data){
        $('#loadbox').append(data+'  ');
    });
    nameid++; 
}

$(document).ready(function(){
    $('button').click(function(){
            ajaxcall();
        });
    setInterval(ajaxcall,1000);
});

Upvotes: 4

dkamins
dkamins

Reputation: 21948

Remove the quotes around "ajaxcall" to pass the actual function to setInterval.

Upvotes: 0

Gabe
Gabe

Reputation: 50533

Call setInterval without the quotes for the function argument. (Preferred Method)

Example:

setInterval(ajaxcall, 1000);

If you're calling it with the quotes you need to include the parenthesis. But this forces eval() to be called.

Example:

setInterval("ajaxcall()", 1000);

The former is the preferred method.

Upvotes: 1

Related Questions