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


Hello Friends!

Did you read my last blog “How to auto resize textarea based on the user input?”

If you have noticed that the Facebook/Twitter social networking sites repetitively search for new comments/tweets to display to the end user. It is pretty simple concept, which we can achieve using a simple script. It is approx. 10 lines of code. 

I thought this may be helpful for newbie and here I am going to write about "How to auto reload partial page and display number of tweets" with very few steps.

Step 1:

Create a index.php file and paste below code into it. Don't forget to include Jquery and Ajax framework in your page.


  
  
  $(document).ready(function(){ 
   var auto= $('#tweets'), refreshed_content;	
       refreshed_content = setInterval(function(){
        auto.fadeOut('slow')
            .load("result.php?id=123").fadeIn("slow");
            }, 3000); 										
    console.log(refreshed_content);										 
    return false; 
  });
  

Above script will call result.php page on every 3 seconds and fetch the number of tweet count. Replace id=123 with logged in user id. Next we are going to place a div where tweets count will get displayed. 


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

Now let us create result.php to perform twitter live search and return the tweet count to the user. Copy  below piece of code and paste it into result.php to perform live database search. Here user_id is referred to the logged in user id to search against the database.


$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. 

This small script will automatically fetch the number of tweets on regular interval and display to end user. You may modified this script accordingly to create a live notification system. 

Hope it will be helpful. Please do not forget to leave your comment below & share with friends.



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 appsntech.com. All rights reserved.