Ajax – Jquery Auto Refreshing DIV

 
The following demo example display server timestamp on every 2 second. You can easily edit the code and display any database content.
 
 
 
 
You have a div that you would like to be up to date on your website without having the page refresh event, this problem can be solved by using the following script. Let’s say that you want to show the total number of rows in a particular table on every 3 second without performing a page refresh event. Then do the following steps
 
 
Step 1 – Load ajax Script
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
 
This script load ajax script remotely.


 
Step 2 – Specify the target DIV
 
We need to build the script in the “head” section of your page. This script targets a div(refreshdiv) with a loaded php file(count.php) and sets how often the div should be reloaded
 
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#refreshdiv').load('/path/to/count.php');
}, 3000); // the "3000" here refers to the time to refresh the div.  it is in milliseconds. 
});
// ]]></script>


 
Step 3 – Write php code into count.php
 
Here are the contents of "count.php”
 
<?php
 
$conn=mysql_connect("localhost", "database_username", "database_password");
mysql_select_db('database_name',$conn);
$content_count = mysql_query( "SELECT * FROM table_name" ) or die("SELECT Error: ".mysql_error());
$row_count = mysql_num_rows($content_count);
echo $row_count;
 
?>


 
Step 4 – Include target DIV into html file
 
here is the div in the html. you can place “loading Content…” or a “Loading GIF image inside of the div and it will be replaced by the results of “count.php”
 
<div id="refreshdiv">Loading users…</div>


 
You can leave a response, or trackback from your own site.

Leave a Reply