Auto Load and Refresh Div every 10 Seconds with jQuery.
Wall Script
Wall Script
Wednesday, July 15, 2009

Auto Load and Refresh Div every 10 Seconds with jQuery.

Have you seen this Twitter Search and Facebook shows most recent tweets/posts count from the database every 10 seconds on top of the page. I had developed like this with jQuery and Ajax. It's simple just 5 lines of code

Auto Load and Refresh  Div every 10 Seconds with jQuery.

Live Demo

Example 1

Index.html
Contains javascript and HTML code. Take a look at load("record_cound.php")
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js
"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds

<body>
<div id="load_tweets"> </div>
</body>

</script>



record_count.php
Just printing "9lessons | programming" every 10 seconds
<?php
echo "9lessons | Programming blog..............";
?>

Example 2

index.php
Contains PHP code you have to pass the search box value twitter.com/search?q="some thing" to $search_word in facebook pass the user id or user session value.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js
"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php?q=<?php echo $search_word; ?>').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds

<body>
<div id="load_tweets"> </div>
</body>

</script>

record_count.php
Counting tweets/posts from the database.
<?php
include("db.php");
$search_word=$_GET['q'];
$sql = mysqli_query($db,"Select id form Messages where message
LIKE '%$search_word%'");
$record_count=mysqli_num_rows($sql);
//Display count.........
echo $record_count;
?>

db.php
Database configuration file, modify username, password and database values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
web notification

125 comments:

  1. Srinivas, Very nice and useful tutorials.Keep them coming.Already subscribed to your site rss feeds. Also nice pics.Your school pics reminded me of my school-
    Think of having a domain of your own-

    kalyan

    ReplyDelete
  2. cool, but this time no hosted sample

    Yoosuf
    http://eyoosuf.blogspot.com/

    ReplyDelete
  3. Any chance for a demo of this? I'm trying to modify it to do something slightly different, but am struggling just a bit. Also, it doesn't appear to have any sort of fading in it whatsoever; it'd be nice if it faded in and out.

    ReplyDelete
  4. @Evula

    Now live demo available.........

    ReplyDelete
  5. I'd be interested in the memory consumption of this, especially in IE. Can we do a test and let it run for a while? My guess is that having a full closure with Dom access (even if jQuery cleans up) in a setInterval() would use up a lot!

    ReplyDelete
  6. Hi I love this, I have a social network site like myspace and I can use this on the homepage to show new notifications for new mail messages, comments, photo comments, friend request and more.

    1 problem though, lets say I have it refresh every 60 seconds, on initial page load, I need a way for it to load instantly, then start the timer for refreshing instead of waiting 60 seconds, do you know how I can do that, I havent been able to find the solution anywhere on the net for that so far.

    ReplyDelete
  7. This comment has been removed by a blog administrator.

    ReplyDelete
  8. Love your script..

    For some strange reason I cant get it to work...

    Instead of loading external php file could the script load another div and it's contain..

    Thanks in Advance...
    I tried in on my social network for models and signers - http://www.urbaniq.net - I wanted to auto load their profile updates..

    ReplyDelete
  9. Thx for your script! Very good work and help from your side! Thx man!

    ReplyDelete
  10. Awesome plugin!! great job. Tested it and I’m really digging it. can’t wait to use it on my live site!!

    superb work!

    ReplyDelete
  11. I notice that in example 1, you have the body elements within the overall script tag... is that intentional? Shouldn't the script close before the body appears?

    ReplyDelete
  12. Spelling?
    Change form to FROM or from

    Either way, Example 2 still doesn't work!
    Post a demo...

    Works like this:
    record_count.php?q=ui
    Result: 1

    Doesn't work like this:
    index.php?q=ui
    Result: 17 //all rows returned

    Like I say post a demo for example 2.

    ReplyDelete
  13. Ignore last comment;

    Remove all the \ backslashes.

    This works with form being GET or POST...
    ---
    index.php
    ---
    $(\'#load_tweets\').load(\'record.php\?\q=<\?\php echo $q; \?\>\').fadeIn(\"slow\");

    input name="q" type="text" id="q" value="\<\?\php echo $_POST['q']; \?\>"

    ---
    "record_count.php"
    ---
    //connection to the database
    $username = "username";
    $password = "password";
    $hostname = "hostname";
    $dbname = "yourdbname";
    $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
    //echo "Connected to MySQL
    ";
    $selected = mysql_select_db($dbname,$dbhandle) or die("Could not select demo");

    $q=$_GET['q'];
    $sql = mysql_query("SELECT id FROM Messages WHERE message LIKE '%$q%'");
    $record_count=mysql_num_rows($sql);
    //Display count.........
    echo $record_count;

    Remove all the \ backslashes.

    ReplyDelete
  14. Just wondering what the point is of setting the var for setInterval

    ReplyDelete
  15. Hi, this would only show you the total amount of tweets/posts. What if I only wanted to show total since page load?

    ReplyDelete
  16. @chizzle

    javascript
    ----------------------
    load(record_count.php?q=<?php echo $search_word; ?>&last=<?php echo $last_id; ?>)


    record_count.php
    -----------------------
    <?php
    $search_word=$_GET['q'];
    $last_id=$_GET['last'];
    $sql = mysql_query("Select id form Messages where msg_id>$last_id and message
    LIKE '%$search_word%'");
    $record_count=mysql_num_rows($sql);
    //Display count.........
    echo $record_count;
    ?>

    ReplyDelete
  17. sorry for my bad english.

    Although data updates are added?

    Example: monitter.com

    like this how can we do?

    ReplyDelete
  18. ERROR WHEN CODE IS INSIDE A FILES.

    How to use it : $(document).ready(function()

    ReplyDelete
  19. I'm sorry but it doesn't run with IE8 ...

    ReplyDelete
  20. Nice Post. I'm always using jquery load function almost all of the time.
    Thanks for this post.

    ReplyDelete
  21. i try use this code but , when i try to print some string i'ts doesn't show on ie?? and then i try change my header with this :
    < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    < html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">

    and work's fine.thanks

    ReplyDelete
  22. Could anyone share working files of this lesson? I've tried apply this lesson for Joomla module and I can't. Please sent this to [email protected]
    Thanks.

    ReplyDelete
  23. Nice script, but it's not working properly with IE8 :(

    Is any solution for this?

    Thanks.

    ReplyDelete
  24. Nice idea. Is it possible to update on changes only and show it like this:

    > New Message
    > Old Message1
    > Old Message2
    > ...

    ReplyDelete
  25. it's nice ...
    and i have another way to "load page" or "load DIV" in PAGE after reqeuest or Change..:

    $('#div').load('index.php?view=3 #div','');

    good luck
    [email protected]

    ReplyDelete
  26. Nice post dude
    Thanx for sharing

    ReplyDelete
  27. I confirm.

    Not working under IE 8

    ReplyDelete
  28. Any luck with making this work with IE would be much appreciated

    ReplyDelete
  29. nice code.can you help me about showing remainin seconds ? how can i display this.

    ReplyDelete
  30. Any examples in .aspx instead of .php? :$ Yes, I'm a Microsoft geek... :$

    ReplyDelete
  31. well,but i can't run it perfectly pls demonstrate me .....

    ReplyDelete
  32. i cant seem to get example 1 working,i have done exactly what it says any suggestions?

    ReplyDelete
  33. jasondavis :

    here's my example... use this instead..


    $(document).ready(function(){ $('#load_tweets').load("count.php").mouseover(function(){
    var auto_refresh = setInterval(
    function(){
    $('#load_tweets').fadeOut('slow').load('count.php').fadeIn("slow");}, 3000);
    return false;
    });
    });

    ReplyDelete
  34. hi, I have some problems. I had to run three scripts sequentially.
    1. I use the toggle() to display the menu.
    2. after I choose one of the menu, will show new windows (popup: dhtmlxWindows) in new windows which contains a form.
    3. I submit the form (in a popup: dhtmlxWindows) which then perform the function $.ajax(). if the function $.ajax() successful, will reload the new div.

    here is the problem, after the $.ajax() runs successfully, and reload the new div, I can not call functions JQuery / Javascript others. eg I can not call toggle() again to select the menu. Can you help me?

    thanks

    ReplyDelete
  35. Hi
    Firstly thank you for all your great tutorials. One problem I've encountered is the use of .load() in IE8. When on a page that has several AJAX calls, .load() can sometimes throw back a 'Bad Request' error.

    Does anyone know of a good way of fixing this? Right now I have just $.post to solve the problem and it is working fine.

    ReplyDelete
  36. IE problem resolved:

    ReplyDelete
  37. this script will have problem if combine with
    http://www.9lessons.info/2009/11/facebook-style-application-with-jquery.html
    am i rite? is there any way to integrate both code..

    ReplyDelete
  38. This does work, but appears to cause constant memory growth for IE and Firefox. Is there a way to force garbage collection or clear out the DOM to keep this from happening?

    ReplyDelete
  39. 2 FULLY FUNCTIONAL EXAMPLES

    //ONCLICK
    $(document).ready(
    function(){$('#refresh1').click(
    function(){$('#responsecontainer1').fadeOut('slow').load('test.php?randval='+ Math.random()).fadeIn("slow",function(){
    alert('complete updated');
    });
    //return false;
    });
    });
    **********************************************

    //TIMER
    $(document).ready(function() {
    $("#responsecontainer2").load("test.php");
    var refreshId = setInterval(function() {
    $("#responsecontainer2").load('test.php?randval='+ Math.random());
    }, 1000);
    });

    ReplyDelete
  40. //ONCLICK
    $(document).ready(
    function(){$('#refresh1').click(
    function(){$('#responsecontainer1').fadeOut('slow').load('test.php?randval='+ Math.random()).fadeIn("slow",function(){
    alert('complete updated');
    });
    //return false;
    });
    });

    //TIMER
    $(document).ready(function() {
    $("#responsecontainer2").load("test.php");
    var refreshId = setInterval(function() {
    $("#responsecontainer2").load('test.php?randval='+ Math.random());
    }, 1000);
    });

    ReplyDelete
  41. Great! Keep post Thank you ! :)

    ReplyDelete
  42. Very good. Now i have a question. How can i create a javascript code with this so that if my visitors put the code
    script language=javascript src=mypage.php

    in their page, they will see each time there is update on my website ?

    ReplyDelete
  43. can anyone make it work in social engine 3?

    ReplyDelete
  44. how to combine mouseover event in thats script..

    please...

    ReplyDelete
  45. This what I'm looking for, thanks

    ReplyDelete
  46. nice tutorial, that i'm looking for, thanks you :D

    ReplyDelete
  47. very nice, me also looking for this type of code...thanks..:)

    ReplyDelete
  48. is it possible to put a thickbox inside this code???

    ReplyDelete
  49. nice, thanks for the article, I save this page.

    ReplyDelete
  50. hi..just wanna know do i need to change the (load_tweets)? div?..cuz right now i have fillup form when i type on the editbox and when it refresh the the stuff i typed it dissapaired..

    thanks

    ReplyDelete
  51. phemon!
    using this as a jquery hook just made my life so much easier.

    ReplyDelete
  52. You have to take out body to /body out of /script tag then after it works only

    ReplyDelete
  53. @jasondavis you can call function first something like this ;

    $(function(){
    $('#load_tweets').fadeOut("slow").load('record_countphp').fadeIn("slow")
    })
    $.ajaxSetup({ cache: false });
    var load = function() {
    $('#load_tweets').fadeOut("slow").load('record_count.php').fadeIn("slow");
    };
    var auto_refresh = setInterval(load, 60000);
    load();

    ReplyDelete
  54. First of all, thank you very much for the example codes.

    I have tried the example 1 successfully.

    In the PHP code I call with the $('#div').load function I generate links to other PHP files in my server.

    I need to load these new files in a DIV from the main page, but I don't know how to access elements from the main page from the loaded PHP code.
    Any suggestions?

    ReplyDelete
  55. With memcached work better)

    ReplyDelete
  56. hi,its not working in IE AND FIREFOX..

    ReplyDelete
  57. Brilliantly simple.

    ReplyDelete
  58. what program did u use to do the circles, and arrows in this post image, did u use a wacom pen? o some software, please answer me.

    ReplyDelete
  59. very good, i like it !

    ReplyDelete
  60. hmm this site is really awesome and informative to me, i am also gonna share this site to my friends.

    ReplyDelete
  61. For those of you experiencing the IE memory growth problem, you can add the following code before using any jQuery:

    var myAjax = function(settings) {
    var newSettings = $.extend({}, settings, {
    complete: function (xhr, status) {
    if (settings.complete) {
    settings.complete(xhr, status);
    }
    // Avoid IE memory leak
    xhr.onreadystatechange = null;
    xhr.abort = null;
    }
    });
    $.ajax(newSettings);

    ReplyDelete
  62. Will it work with jsp??

    ReplyDelete
  63. is it possible to load only the contents of div instead calling for .load('another page')
    ex:
    Div1 = #contents (no refresh required)

    Div2 = #contents2 (no loading of another page require refresh every xx seconds)

    ReplyDelete
  64. IE working fix do all of these:

    Add your top of php;

    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Content-Type:text/javascript;charset=utf-8");

    also start script in your page like this:


    var auto_refresh = setInterval(
    function()
    {
    $.ajaxSetup({ cache: false });

    ---your codes here
    ---your codes here
    ---your codes here

    ReplyDelete
  65. with .click function it loads every time new contents, it makes a chain of contents.how can we stop this behavor? can any body help ............

    ReplyDelete
  66. Superb article, this is what am looking for. Thanks lotzz.

    ReplyDelete
  67. What happens if the PHP script takes more than 10 seconds to return the data ?

    ReplyDelete
  68. Yes boi u a star it helped : but ivans helped me very well //TIMER
    $(document).ready(function() {
    $("#responsecontainer2").load("test.php");
    var refreshId = setInterval(function() {
    $("#responsecontainer2").load('test.php?randval='+ Math.random());
    }, 1000);
    });

    ReplyDelete
  69. its to many used resouces memory in server.

    ReplyDelete
  70. I have a php file with a div inside. I want to have another script in same file that autorefreshes the div without reloading a whole page when I include this file in another file.

    Example: banners.php included on home.php
    reload banners.php without reloading home.php

    Help?

    ReplyDelete
  71. Very helpful tutorial .. thank youuu >_<

    ReplyDelete
  72. all these people who have problems use firefox its better than ie or use chrome if you want faster performance and compatibility!

    there is a fix above to force it to work with ie but ie is no good anymore jnetscripts.com all feel free to sign up

    ReplyDelete
  73. Fantastic. I'm wondering if it possible to update more than one div on the same page using this method?

    ReplyDelete
  74. good tutorial, but how to load page from background?

    ReplyDelete
  75. Just was looking something like this...before this was trying Timer and all...so complicated..thanks.

    ReplyDelete
  76. That's awesome! But I got a problem with the code in chrome, It Just shows me an empty page.

    ReplyDelete
  77. need counter always increase value not stop even refresh the site

    ReplyDelete
  78. Hi
    If am insert new row ,row only refresh not for a page refresh in php

    please give guideline please

    ReplyDelete
  79. how about if I using
    $search_word=abs((int)$_GET['q']);
    is that more secure.

    ReplyDelete
  80. WOW.. it's wonderfull... tx bro.. I'm from indonesian...

    Terima Kasih...

    ReplyDelete
  81. Hey, is it possible to get a variable from the record_count.php. In my record_count.php is a echo "$technic_count'; but i can't use this variable on the mainsite to do some php.

    ReplyDelete
  82. Thank you so much for this tutorial...

    ReplyDelete
  83. i like and i helpfull this code but i need for JSP page

    ReplyDelete
  84. This comment has been removed by a blog administrator.

    ReplyDelete
  85. How I can use this in blogger DIV tag to refresh

    ReplyDelete
  86. $('#load_ques').load('search.php?q=').fadeIn("slow"); i am trying to load search.php but tht is page not trigeered search.php
    $ss=$_REQUEST['q'];
    $sql = "select * from ques where ssid = '$ss'";
    $sel= mysql_query($sql);
    //$sel1= mysql_fetch_array($sel);
    while($sel1= mysql_fetch_array($sel))
    {
    echo $sel1['question']."
    "."by".$sel1['user']."
    ";

    }

    ReplyDelete
  87. I'm a newbie to html code & this auto refresh code is of intrest to me but wasn't able to get it working for my situation. I'd pay someone to show me how to apply this to my radio stations recently played songs widget. My url is posted here to look at the page source. I wasn't allowed to post the html code here so going to my site would be the only way to see the JS code being used.

    I don't have access to anything but plain html editing with my template so the code I need would have to be good for plain html text editing if that makes any sense. Hope to get some help on this, thx

    ReplyDelete
  88. Can you Make a Simple Pageview Counter which updates every second with counter animation....

    ReplyDelete
  89. Thanks Dear Its Nice Script....

    ReplyDelete
  90. Awesome tutorial srinivas. time to implement in my website. Thanks buddy

    ReplyDelete
  91. Hi how to create Auto Load and Refresh like and unlike button in codeigniter..

    ReplyDelete
  92. i want just on time Auto Load and Refresh data not every 10 second.

    ReplyDelete
  93. This is more better way for writing a code.

    ReplyDelete
  94. Good Job. it is very beneficial.

    ReplyDelete
  95. Your every post is good and makes me understand in a better way.
    I appreciate the way you present the demo and code.
    Thank you.

    ReplyDelete

mailxengine Youtueb channel
Make in India
X