Robert
Robert

Reputation: 149

Using a callback function...Jquery .Get

I've been searching and searching for an easy to understand answer, but i can't find one.

I have a jquery .get ajax function to run something, it takes about 10 seconds to run because i have a wait in the php doc. I want to run it again after the 10 seconds pass, so basically when the ajax function finishes. Im thinking of using a callback, but i have no idea how to structure it or should i use a while loop or .. im lost...

heres my code that i have so far

function listen(callbackFn) {
    $.get('thread.php?tag=<? echo $tag ?>&username=<? if($_SESSION['loggedin']=='true'){echo $_SESSION['username '];} ?>', function(data) {
        $('#chats').append(data);
        callbackFn;
    });
};

Upvotes: 2

Views: 888

Answers (4)

Paul
Paul

Reputation: 141877

This should work for you:

(function repeat_request(){
    $.get('thread.php?tag=<? echo $tag ?>&username=<? if($_SESSION['loggedin']=='true'){echo $_SESSION['username'];} ?>', 
        function(data) { 
            $('#chats').append(data); 
            repeat_request();
        }
    );
})();

The function called repeat_request is executed as soon as the previous request succeeds. Note that if any request fails (say the user's internet momentarily disconnects) the request will stop repeating. If you want it to keep repeating you should use .complete() instead of success like this:

(function repeat_request(){
    $.get('thread.php?tag=<? echo $tag ?>&username=<? if($_SESSION['loggedin']=='true'){echo $_SESSION['username'];} ?>', 
        function(data) { 
            $('#chats').append(data); 
        }
    ).complete(repeat_request);
})();

Upvotes: 1

al01
al01

Reputation: 122

You can try:

function listen()
{
$.get('thread.php?tag=<?php echo $tag ?>&username=<?php
if($_SESSION['loggedin']=='true'){echo $_SESSION['username'];} ?>', 
    function(data) { 
        $('#chats').append(data); 
        setTimeout(listen,100); // prevent recursive call
    } 
);  
};

Upvotes: 0

deceze
deceze

Reputation: 522432

Put the code in a function and call it recursively with a timeout of 10 seconds:

function do() {
    $.get('...', function (data) {
        // data processing...

        setTimeout(do, 10000);
    });
}

do();

Upvotes: 1

Daff
Daff

Reputation: 44215

I think your best bet is to wrap that into a function and call it recursively:

function poll() {
    $.get('thread.php?tag=<? echo $tag ?>&username=<? if($_SESSION['loggedin']=='true'){echo $_SESSION['username'];} ?>', function(data) { 

            $('#chats').append(data); 
            poll();
    });
}

poll();

This will pretty much poll forever every time the Ajax call returns.

Upvotes: 0

Related Questions