Reputation: 422
The php script parses xml file and print output on page inside div:
<?php
$playlistUrl = 'http://url/to/playlist.xml';
$xmldata = file_get_contents($playlistUrl);
$xml = new SimpleXMLElement($xmldata);
foreach( $xml->trackList->track as $track ) {
echo $track->title .' - '. $track->annotation .'<br>';
}
?>
I want to update the output every 25sec without reloading the page, using some AJAX method. I find some code samples that set time interval:
// Poll the server each 60 seconds
window.setInterval(function()
}, 60000);
also
setInterval(function(){
SomeAjaxFunction();
}, 1000);
How to implement this properly in my case?
Upvotes: 0
Views: 2825
Reputation: 17666
setTimeout executes the function after X seconds... then if you make it recursive you will always have X seconds to wait after the code has been executed. This is preferred over setInterval which executes exactly every X seconds.
Think about when the server is lagging and the load() takes a few seconds to actually load... well now the animation is half timed out and is doing to reload / fade again....
function loopy_function() {
// ajax call
// on success
setTimeout(loopy_function, 1000 * 10 );
}
The key here is to only call your setTimeout on a completed response.
Upvotes: 1
Reputation: 25745
check out my answer here.
Refresh page element after specific time
i have answered about how to reload the div after specific time, you can tweak it a bit to keep reloading after a time interval.
the basics goes as follows.
<div id="reload">
//your PHP code and content are here.
</div>
and your jQuery code.
<script>
setInterval(function() {
$('#reload').fadeOut("slow").load('reponse.php').fadeIn("slow");
}, 10000);
</script>
Upvotes: 6