First we will make a customize function called getRefresh() -

function getRefresh(){
$(”#auto”).load(”data.php”, ”, callback);
}

Here we have used load( url, [data], [callback] ) ajax api. This api load HTML output from a remote file (data.php) and inject it into the div (auto). Below we have created a callback function named callback() -

function callback(){
setTimeout(”getRefresh()”, 1000);
}

setTimeout() function is used to call getRefresh() after a specified number of milliseconds (1000). Now we can add some jQuery effect to realize that the div is refreshing automatically

function getRefresh(){
$(”#auto”).fadeIn(”slow”);
$(”#auto”).load(”data.php”, ”, callback);
}
function callback(){
$(”#auto”).fadeOut(”slow”);
setTimeout(”getRefresh();”, 1000);
}

And finally here is the complete code -

// for jQuery html
<html>
  <head>
  <script src=”http://code.jquery.com/jquery-latest.js”></script>
  <script type=”text/javascript”>
  function getRefresh() {
  $(”#auto”).fadeIn(”slow”);
  $(”#auto”).load(”data.php”, ”, callback);
  }
function callback() {
  $(”#auto”).fadeOut(”slow”);
  setTimeout(”getRefresh();”, 1000);
  }
  $(document).ready(getRefresh);
  </script>
  </head>
  <body>
  <h1>Auto refresh div by jQuery </h1>
  <div id=”auto”>
  Random text goes here
  </div>
  </body>
  </html>
  

// for php server scripting language
// data.php

  mysql_connect(”localhost”, “root”, “”);
  mysql_select_db(”dbname”);
  $result = mysql_query(”select * from tblname”);
  while ($row = mysql_fetch_object($result)) {
  echo $row->username.’’;
  }
  mysql_free_result($result);
  

Tags: , , , , , , , , , , , , ,