9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
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
$search_word=$_GET['q'];
$sql = mysql_query("Select id form Messages where message
LIKE '%$search_word%'");
$record_count=mysql_num_rows($sql);
//Display count.........
echo $record_count;
?>
Comments
{ 107 comments }
kal said...

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

Yoosuf said...

cool, but this time no hosted sample

Yoosuf
http://eyoosuf.blogspot.com/

Srinivas Tamada said...

Thanks Kalyan..

EVula said...

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.

Srinivas Tamada said...

@Evula

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

Chris Heilmann said...

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!

jasondavis said...

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.

javier said...

Hola me párese un excelente blog con una muy buena y atractiva temática, saludos y hasta siempre.

Firma: http://lomascodiciadodelplaneta.blogspot.com

Ian Reynolds said...

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

Anton Ca$h said...

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

paulrajj said...

very nice information. thanks!

Selva Comments said...

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

superb work!

Srinivas Tamada said...

@Selva

Thank You

Gary said...

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?

Anonymous said...

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.

Anonymous said...

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.

Anonymous said...

Just wondering what the point is of setting the var for setInterval

chizzle said...

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

Srinivas Tamada said...

@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;
?>

chizzle said...

Thank you

Harsha M V said...

Awesome post srinivas.

Automotive Recruitment said...

Very nice plugin, will come in very handy.

dark said...

sorry for my bad english.

Although data updates are added?

Example: monitter.com

like this how can we do?

Anonymous said...

ERROR WHEN CODE IS INSIDE A FILES.

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

Anonymous said...

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

1mr3yn said...

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

Anonymous said...

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

Dmitriy said...

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 dposte07@aol.fr
Thanks.

Anonymous said...

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

Is any solution for this?

Thanks.

Anonymous said...

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

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

Anonymous said...

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
mk1364it@gmail.com

Anonymous said...

Nice post dude
Thanx for sharing

Anonymous said...

I confirm.

Not working under IE 8

Andrew said...

Any luck with making this work with IE would be much appreciated

Anonymous said...

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

Anonymous said...

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

shishir said...

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

mac said...

nicely done

Anonymous said...

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

Anonymous said...

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;
});
});

gundholmu said...

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

David said...

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.

Anonymous said...

IE problem resolved:

NeophyteHeaven said...

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

pulsa telephone murah said...

its amazing i will test it now... :)

Anonymous said...

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?

Ivan said...

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);
});

Ivan said...

//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);
});

Srinivas Tamada said...

@Ivan

Thank you

Muhammad Sarfraz said...

Great! Keep post Thank you ! :)

KRESSLY MAX said...

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 ?

KRESSLY MAX said...

Oh, can someone help me ?

Anonymous said...

can anyone make it work in social engine 3?

rio said...

how to combine mouseover event in thats script..

please...

Anonymous said...

loop replay

nassim rehali said...

thnkx brother Tamada
its usefull

omarxp said...

This what I'm looking for, thanks

tien tran said...

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

Mani said...

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

Anonymous said...

is it possible to put a thickbox inside this code???

Domain Murah said...

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

zotek said...

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

Maks said...

thanks man

Anonymous said...

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

Anonymous said...

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

hacker cup 2012 said...

@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();

Carlos J. said...

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?

Anonymous said...

With memcached work better)

Pramod Gorityala said...

hi,its not working in IE AND FIREFOX..

Anonymous said...

Brilliantly simple.

Alex Daniel Cabello León said...

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.

Anonymous said...

very good, i like it !

Facebook Application Developer said...

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

Jeremy Rollison said...

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);

Sathish Kumar Pandy said...

Nice demo with useful codings...

Anonymous said...

Will it work with jsp??

Anonymous said...

thanks

Logo EPS said...

Good Tutorial
Tks Srinivas

yuda prawira said...

thanks ...

cheekycroak said...

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)

Anonymous said...

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

Anonymous said...

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

pradeep said...

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

scalaberch said...

now i know how... thanks dude! :)

Anonymous said...

Ho its really nice

Lokesh said...

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

Anonymous said...

just what i needed

Luis Alberto said...

That's perfect! Thanks!

King Musa said...

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);
});

Anonymous said...

nice

Zeihan Aulia said...

its to many used resouces memory in server.

Anonymous said...

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?

Fanio Cute said...

Very helpful tutorial .. thank youuu >_<

Anonymous said...

Cool, thank you

Alex Jon said...

This is very nice........:)

Jay Mee said...

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

Anonymous said...

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

Obat Hiv Aids said...

good tutorial, but how to load page from background?

Shahid said...

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

Ahmed said...

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

Anonymous said...

need counter always increase value not stop even refresh the site

Anonymous said...

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

please give guideline please

Husni said...

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

Dede Irvan Setiawan said...

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

Terima Kasih...

Dennis Sauer said...

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.

bala krishna said...

Thank you so much for this tutorial...

Patel Ankit said...

i like and i helpfull this code but i need for JSP page

Post a Comment