Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto refresh a section of a page

Tags:

javascript

php

I have a part of a page that has live data in it, I was thinking of just refreshing the page every couple of minutes, but that isn't right because of other elements of the page.

How can I do it? What language can I use to do this, what's easy to do and what isn't, what works well and what doesn't. Maybe some clear tutorials or even code examples.

I'd live to do this in something like PHP, but don't have a clue where to start, from a bit of research i see that Javascript and Ajax seem to be the standard for this but my knowledge of these languages aren't up to scratch.

Thanks for the time and help people.

Oh, the data that is being displayed is coming from a database if that's any help.

Thanks again.

like image 569
ragebunny Avatar asked Oct 05 '11 11:10

ragebunny


1 Answers

You could use a Javascript library such as jQuery and do something like the following simplified example:

$("document").ready(function(){
  var interval = setInterval(refresh_box(), 60000);
  function refresh_box() {
    $("#myDiv").load('path/to/databasepage.php');
  }
} /*<= The closer ) bracket is missing in this line*/

and in your path/to/databasepage.php page you can have your select query and echo the results out.

What this does is sets a timeout to call a function (in this case, refresh_box() ) every 60 seconds (which is 60,000 miliseconds) and loads the data from path/to/databasepage.php in to your div with the id myDiv.

edit:

If you want to stop the auto-refresh you can bind an element to clear the interval by doing the following:

// assuming you have a clickable element 
// (typically a button or so) id called 'stop_refresh'
$("#stop_refresh").click(function(){
  clearInterval(interval);
}
like image 167
dan Avatar answered Oct 16 '22 17:10

dan