How do I make it so that the browser calls up a php page and posts the results in a div every 10 seconds or so?
Thanks. I am just learning jquery.
How do I make it so that the browser calls up a php page and posts the results in a div every 10 seconds or so?
Thanks. I am just learning jquery.
You need a periodic updater. Something like:
function callMeAtInterval()
{
$.ajax({
method: 'get',
url : 'status.php',
dataType : 'text',
success: function (text) { $('#updateMe').html(text); }
});
}
//causes callMeAtInterval() to get called every 5 seconds.
var holdTheInterval = setInterval(callMeAtInterval, 5000);
jQuery's $.ajax function gets the output of the resource specified by url, and the success callback allows you to do some processing with the results, in the example above:
('#updateMe').html(text);
fills up the page element of id updateMe
with the text returned from the server.
This should work:
function loadResults(){
$('div.to.update').load('yourpage.php')
setTimeOut(arguments.callee, 10000)
}
loadResults()
How it works:
$('div.to.update').load('yourpage.php')
This line makes an ajax call to 'yourpage.php' and fills the div with the results of that page (note that the result of calling yourpage should not be a whole page but just a snippet)
setTimeOut(arguments.callee, 10000)
setTimeOut schedules a function call in the future, in this case 10 seconds. the function to call its the function itself, taken from the variable 'arguments' that every function has access to. It's like a recursive function, but with a delay of 10 seconds.
Lastly, you call the function for the first time to start the loop.
EDIT:
you can also call the function with setInterval() if you need to stop the loop later, just do this:
function loadResults(){
$('div.to.update').load('yourpage.php')
}
var interval_id = setInterval(loadResults,10000)
// Later on when you want to stop the refresh...
clearInterval(interval_id)
It's worth noting that setInterval will execute this function every 5 seconds (in the example karim79 provided) regardless of the progress of pending AJAX requests. If the first request takes 3 seconds to complete, setInterval will send the next request 2 seconds later, not 5. If you actually want there to be 5 seconds between a successful refresh and the next request, you might want to use setTimeout within the success
callback function. This looks like this:
function callMeAtInterval() {
$.ajax({
method: 'get',
url : 'status.php',
dataType : 'text',
success: function (text) {
$('#updateMe').html(text);
setTimeout(callMeAtInterval, 5000);
}
});
}
The drawback to this approach is that one failed setTimeout means that the section won't be refreshed again.