user2212461
user2212461

Reputation: 3253

Updating html code with javascript when php return changed

I want to continuously update an html document using the return of a php file. Therefore I need to use the jQuery function:

$.get('returnfunction.php', function(data) { 
test=data;
document.getElementById('t1').innerHTML=test; 
}); 

How can I call this function continuously in javascript? setInterval seems not proper for this asynchronous function.

Thanks

Upvotes: 2

Views: 163

Answers (2)

tymeJV
tymeJV

Reputation: 104775

setInterval probably isn't a good idea since the order is not guaranteed, therefore you could be sending requests every X amount of seconds that either come back all at once, not at all, or in a random order. You can use setTimeout in the callback to start another request in X amount of time:

function getStuff() {
    $.get('returnfunction.php', function(data) { 
        test=data;
        document.getElementById('t1').innerHTML=test; 
        setTimeout(getStuff, 5000); //Run this func again in 5 sec
    }); 
}

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382160

The problem with calling an asynchronous function using setInterval is that the unanswered requests might accumulate if the server or the network is slow.

Here's how you might do it :

(function doOne(){
    $.get('returnfunction.php', function(data) { 
       test=data; 
       document.getElementById('t1').innerHTML=test;
       setTimeout(doOne, 1000);
    }); 
})();

This way the next call to $.get occurs one second after the server has answered the last call.

You might also want to act on failures, not just on success, depending on your exact requirements.

Upvotes: 3

Related Questions