Auto reload page content every 3 sec using JQuery, Ajax & PHP

In my last article I wrote “How to auto resize textarea based on the user input.”. While surfing twitter and facebook recently I just noticed both the giant social networking site repetitively search for new comments/tweets to display into end user. Actually it is pretty simple concept, which can achieve via simple script with around 10 lines of code. I drafted this tutorial long back and today I am posting how to auto reload the part of the page and display the number of tweet counts with a simple steps.

Let us create index.php page and paste below code.

<script type="text/javascript" src=""></script>

<script type="text/javascript">

    var auto= $('#tweets'), refreshed_content;	
		refreshed_content = setInterval(function(){
		auto.fadeOut('slow').load("result.php?id="<?php  echo $userid; ?>).fadeIn("slow");}, 
		return false; 

The above script will call result.php page every 3 seconds and fetch the number of tweet count. We will place the count into the div content.

<div class=”container”>
<div id="tweets"> </div> 

Now let us create result.php to perform twitter live search and return the tweet count to the index.php page. Paste below piece of code into your result.php to perform live database search. Here i have used user_id to search against database similar case of facebook/twitter.

$userid = (string) (isset($_GET['id'])) ? $_GET['id'] : '';

$link = mysql_connect("localhost", "root", "");
mysql_select_db("twitter", $link);
$sql = "Select * FROM user_tweets where user_id = '$userId' ";
$result = mysql_query($sql, $link);
$num_rows = mysql_num_rows($result);

echo "Total $num_rows new Tweets ";exit;

That’s it. We are done. Simple script does all the magic behind. You can also use modified version this script for live notification system. Hope it helps! Please do like or share if it is helpful to you, and also leave your comments below. Keep visiting.

No comments:

Post a Comment

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 All rights reserved. Powered By- Sanjoy Dey Productions