JQuery- Auto Refresh Div Every X Seconds

Image frame
JQuery- Auto Refresh Div Every X Seconds
Maruf
Feb 26th, 2009
Maruf scribbled this post.

I’ve recently been working on a e-commerce site (online store) for a client. One of the features required was to show the most recently viewed items on the homepage. For that to work, I need to write a script to query a DB every 10secs or so. Youtube actually has something similar, where on the homepage they display “videos that are being viewed now”. I don’t know how they do, but this is how I do it…

Obviously it’s an AJAX affect; as always, I’ll be using the JQuery library (my personal favourite).

Here’s the OUTDATED code (find updated code below this example)…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<head>
<!-- For ease i'm just using a JQuery version hosted by JQuery- you can download any version and link to it locally -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
 
<script>
var refreshId = setInterval(function()
{
     $('#responsecontainer').fadeOut("slow").load('response.php').fadeIn("slow");
}, 10000);
</script>
</head>
<body>
 
<div id="responsecontainer">
</div>
</body>

As you can see, the JS code in the header is calling a file called response.php. That’s the file which will refresh every 10 seconds. Just change the value to increase/decrease the refresh period. The #responsecontainer div is where the response.php will be displayed.

It’s as easy as that.

If anyone uses the code, let me know how you get on :)

UPDATE- Load content immediately on page load & I.E Fix

I’ve had a LOADS of people emailing us asking how to get the content in the data.php file to load immediately on pageload, and then start the refreshing process. Also, a lot of people had issues with this code in I.E. I believe I’ve managed to deal with both problems. Here’s the code for that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html>
<head>
<!-- For ease i'm just using a JQuery version hosted by JQuery- you can download any version and link to it locally -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
 $(document).ready(function() {
 	 $("#responsecontainer").load("response.php");
   var refreshId = setInterval(function() {
      $("#responsecontainer").load('response.php?randval='+ Math.random());
   }, 9000);
});
</script>
</head>
<body>
 
<div id="responsecontainer">
</div>
</body>

Click here for an example (page should start reloading after 5 secs or so- you’ll notice the number changing). You can download the working files here.

I hope that helps! If anyone tries this updated code, please let me know if it works ok. Thanks a lot :)


Filed away: Ajax

comments

Image frame
1

This doesn’t work in IE7 unless user has set his browser not to cache to page.

Burf
Mar 13th, 2009
Image frame
2

It will work in IE if you send some POST variable along the load().
IE disregards most header data not to cache the site, unless POST data is send along with the call :S

Burf
Mar 13th, 2009
Image frame
3

Hi,
I just want to say that it works for me.
thanks

maruf
Mar 17th, 2009
Image frame
4

Hey there! Your script is awesome! I am really planning to use it… still there is a problem.. looks like its not compatible with jquery tooltips. It’s like after the first refresh the tooltip won t work, and also if a tooltip was active DURING the refresh it gets stuck on the page and it won’t disappear. Do you know of any compatible tooltip with ur refresh script? Thanks a lot, ed

eddubeddu
Mar 17th, 2009
Image frame
5

careful there, if you have flash content on your page while running ie, every time that div refreshes, it causes flash player to hiccup. I was recently working on a feature similar for a flash game leaderboard (http://wizarddefense.com/play/) and ran into this problem. My only solution was to make the refresh user-consented, so I wouldn’t be the one to blame :-P . Otherwise, this is great!

Vincent
Mar 23rd, 2009
Image frame
6

Thanks for the code but I notice JQuery tends to load and change the content before the fadeOut. So I modified the code to put the content load and fadeIn in the callback of the fadeOut, hence:

var refreshId = setInterval(function() {
$(‘#responsecontainer’).fadeOut(“slow”, function () {
$(this).load(‘response.php’).fadeIn(“slow”);
});
}, 10000);

There is probably a more elegant way of doing this.

Lewis Walsh
Mar 24th, 2009
Image frame
7

tx

toruan
Mar 25th, 2009
Image frame
8

Hi, I searched for a suitable solution for refreshing my Shoutcast “Now Playing” song. I tweaked this script and paired it with the “Now playing” script from my stream host provider. It works like a charm and has a professional look (I tuned off the fade effect). Just want to say “thanks”. :)

Marty
Apr 3rd, 2009
Image frame
9

All that i can say is its working for me..

tom
Apr 3rd, 2009
Image frame
10

thank you for document !

codeboot
Apr 26th, 2009
Image frame
11

You could use jQuery’s built in event timer too:

.everyTime(5000,function(i){ });

thomas
Apr 28th, 2009
Image frame
12

Dude ,
Great ya . Thank a lot its working for me . i just look for this script

Dipen
Apr 30th, 2009
Image frame
13

Worked great on a live stats system for me, thanks!

JamesB
May 8th, 2009
Image frame
14

How would you pause or stop the refresh?

linuxamp
May 20th, 2009
Image frame
15

Thanks for the code. Took me a long time to find what i needed. Finaly i can rest a bit.

Question. When the page loads for the fist time it takes the amount of seconds it was set to load.

How can i get it to load right as it loads the page and then start the script time to refresh.

The page is:
http://esp.irockfm.com/wp-content/players/popup-player.php

Thanks in advanced.

Jon
Jun 3rd, 2009
Image frame
16

Hi,
thx for this very nice & easy script!

But i´ve got a question.

What can i do load the div’s content also by loading the whole site the first time?

i only want to refresh the div´s content – not load another.

do you have any ideas?

sebstian
Jun 5th, 2009
Image frame
17

This works really well for me. But the php script takes about 15 seconds to load initially. (By contrast, if I direct link to it or use an include, it shows almost immediately.) Is there a way to improve the initial load speed?

bobby
Jun 16th, 2009
Image frame
18

First of all: great script!

Does anyone already has find a ‘clean’ solution for getting the script work in IE7/8? And the first loading ‘problem’?

Thanks in advance!

ffwd
Jul 6th, 2009
Image frame
19

Great script, so simple yet brilliant. I’ve changed it a little as I needed the divs to load immediately on page load, then refresh every 60 seconds. Here is my code:

var refreshId = setInterval(function()
{
$(‘#responsecontainer’).load(‘response.php’);
$(‘#responsecontainer2′).load(‘response2.php’);
}, 60000);

$(document).ready(function()
{
$(‘#responsecontainer’).fadeOut(“slow”).load(‘response.php’).fadeIn(“slow”);
$(‘#responsecontainer2′).fadeOut(“slow”).load(‘response2.php’).fadeIn(“slow”);
});

Thanks for the foundations, quality

Loo
Jul 8th, 2009
Image frame
20

Hi,

I worked on your code its very easy,simple,dynamic, i have added some more features to the code and
kept it in my client’s shopping cart.I’m very happy with this

I was googling for 4 days for my desired code

at last i found

Thanks
saideep
(PHP,CMS Developer)

saideep
Jul 15th, 2009
Image frame
21

Tnx Pal its really cool and works perfectly, a usful piece u know.

Derick
Jul 23rd, 2009
Image frame
22

I absolutely love this solution for Firefox, however I am stumped with IE. The refresh returns to cached data on the first refresh. Tried turning off caching in my browser but that failed. Tried (or thought I tried) to send a POST variable along with the load but that made the refresh completely stop in both browsers. Does anyone have any ideas out there what I could do next? Any ideas would be GREATLY appreciated.

midnight
Aug 10th, 2009
Image frame
23

hy, i just wanna said that it works. made life easier. big thanks. :)

ganis zulfa
Aug 12th, 2009
Image frame
24

Hi. Quick question: why are you setting a refreshId var and not going right into the setInverval()? Thanks!

mike
Aug 14th, 2009
Image frame
25

Thanks, but still can´t find a clean solution to the ie7/8 problem

Ray
Aug 19th, 2009
Image frame
26

Hey Guys,

I’ve updated the code- it should work in I.E now!

Let me know how you guys get on.

Many thanks!

Maruf
Sep 4th, 2009
Image frame
27

Thanks for the code man!

Uroš
Sep 5th, 2009
Image frame
28

thank you!

raz
Oct 9th, 2009
Image frame
29

Hello, This code could be exactly what I need although I am having problems trying to change it. I am new to Ajax.

What I am trying to do is to get this code to work from a database. For example, I want to place this code on my members page and then set up a database for messages. The code will show a box at the top of the page and when a message is inserted into the database it appears in this box.

Ive tried to get it to work but it just shows an empty window. Any help would be really really appreciated.

Justin
Oct 26th, 2009
Image frame
30

Will it not slow down the users computer

Tim Devloper network
Oct 26th, 2009
Image frame
31

Hi thank you so much for the code!

can anyone tell me that how can i add two divs on my page with this script ?

i have 2 different content for adding my page…

RIDVAN
Nov 9th, 2009
Image frame
32

Hi Ridvan,

you can easily add the script two times:

$(document).ready(function() {
$(“#div-one”).load(“link-to-ajax-file”);
var refreshId = setInterval(function() {
$(“#div-one”).load(‘link-to.ajax-file’);
}, 3000);
});

$(document).ready(function() {
$(“#div-two”).load(“link-to-ajax-file”);
var refreshId = setInterval(function() {
$(“#div-two”).load(‘link-to-ajax-file’);
}, 3000);
});

Sebastian
Nov 10th, 2009
Image frame
33

Thanks! It worked for me!!!

David
Nov 13th, 2009
Image frame
34

you are awesome…..!! great work…….!!

Shishta
Nov 19th, 2009
Image frame
35

how do i use this with noconflict,

because its not workin on my site…

http://indiecore.net

emoruffino
Dec 7th, 2009
Image frame
36

The script is not displaying links i mean there are not clickable.. how can i make them clickable? thanks.. great script

Samuel
Dec 9th, 2009
Image frame
37

The refresh button on IE returns to cached data on the first refresh. Tried turning off caching in my browser but that failed.

Firefox and safari works great

Martin
Dec 17th, 2009
Image frame
38

Thanks dude.

Mike Lama
Dec 18th, 2009
Image frame
39

Is there a way to make it refresh only once, or stop after the first refresh?

Nice work by the way, it works great!

douglas
Jan 1st, 2010
Image frame
40

Figured it out, changed setInterval to setTimeout.

Thanks for the code.

douglas
Jan 1st, 2010
Image frame
41

Thanks, this works for me! Any idea how I can call this function direct after adding something to the database instead of just waiting for the next refresh?

Thanks!

Erik
Jan 5th, 2010
Image frame
42

nvm i got it workin, just forgot to post back!

makes my radio station a lil nicer

emoruffino
Jan 9th, 2010
Image frame
43

The is still a bug with cache, when I manually refresh the page, first which is shown the value from enetring site. To avoid that I modified the code:
$(“#responsecontainer”).load(“response.php?v=”+ Math.random());
It works great.

kuba
Jan 10th, 2010
Image frame
44

Thanks for the great article. After searching in vain how could i reload data in my datagrid, with no hope i run through this one and BOOM! it solved my problem. A million thanks!

Quintin Canaya Jr
Jan 16th, 2010
Image frame
45

hi Maruf! Thanks for your great script: so easy, so quick… and so precious!

Is possible to use it for more instances? I mean: in the same page reload one div after 20 seconds, and another one after 5 seconds?
Or reload after the same period 2 different pages?

Thank you!!

edoluz
Jan 22nd, 2010
Image frame
46

Hi. I need to refresh the content from database instead of response.php. Any ideas how i can do so? And i need to display the on random

Irman
Jan 28th, 2010
Image frame
47

Very nice script!.. i’m not really good at this but i did this xD..

how would it be record by record, 1 by 1 tweeter style?

PS: sorry my english, i’m latinamerican.

COLT
Feb 1st, 2010
Image frame
48

Thanks a bunch Maruf! Your code really help me out (esp. with the nasty IE issue). Actually, seems I was still getting some weird flicker issues, but, after I modified the code, this managed to go away. Here’s my modified code of your function:

var refreshId = setInterval(function() {
$(“#page_refresh”).load(‘show-comments.php?v=’+ Math.random());
}, 500);

THANKS A LOT AGAIN! :-)

Kevin Pajak
Feb 2nd, 2010
Image frame
49

My modification is basically just kuba’s (aboe) mode to just the “v” (instead of “randval=”, along with the first part of your function taken out [$(document).ready(function() {
$("#responsecontainer").load("response.php");
]. Then, voila! Finally that horrible IE browser worked my app correctly :-].

Kevin Pajak
Feb 2nd, 2010
Image frame
50

Hi, this looks great. I’d like to use this to refresh a dynamically populated select list (values are kept in mysql table and using php to filter) without refreshing the page. Can I assume that if I replace the randomizer in response.php to the code I now use to populate the select list that the query will run at the interval? Also, can I trigger this via a jquery dialog, on close, for example?

Thanks,

Tony

Tony
Feb 4th, 2010
Image frame
51

I needed to load and refresh the page but only until I returned a value I was looking for. Then I needed to stop the page from refreshing. Here is how I did that:

// Global Variables
var refreshId;

$(document).ready(
function() {
// Initial page load
$(“#responsecontainer”).load(“/test/test.php”);

// Start refesh counter
refreshId = setInterval(
function() {
// This function works with $.get
function doSomethingWithData(data) {
if (data != “pending”) {
// Reload & Display
$(“#responsecontainer”).load(‘/test/test.php?randval=’+ Math.random());
} else {
// Display
document.getElementById(‘responsecontainer’).innerHTML = “Done”;

// Stop refresh counter
clearTimeout(refreshId);
}
}
// Second refresh
$.get(‘/test/test.php?randval=’+ Math.random(), doSomethingWithData);
}
, 10000); // Time between refeshes 1000 miliseconds = 1 second
}
);

Sammie S. Taunton
Feb 9th, 2010
Image frame
52

i usually never comment on codes that are useful but this is magic, i tried everything with prototype and jquery and i managed to find a solution but always crashed on IE. This works like a charm on IE.

rafs
Mar 14th, 2010
Image frame
53

Dude what a great code, I used to use the ajax code but it wouldn’t load until the amount of time for it to refresh is met… regards

utan
Mar 16th, 2010
Image frame
54

Thanks for this script. It works perfect. I was straggling to great a chart, but with this script its working. Thank you again

Molobela Walter
Mar 19th, 2010
Image frame
55

Great piece of code. I’m a noob to jquery. Could anyone show me how I could stop the code from loading the php page after a certain amount of time? Like 15 minutes?

Tarvi
Mar 29th, 2010
Image frame
56

Superb! Very very nice work! Thank you for share!

Marcos Fontana
Apr 15th, 2010
Image frame
57

Thanks for the code, it works great

But How ca I stop the refresh with a link?

tidave
May 15th, 2010
Image frame
58

Hi Sammie,

After checked your code, still don’t understand how to stop the auto refresh. Should I input any parameter to let program know the auto-refresh should be stopped? How to make use of the function “doSomethingWithData”? Thanks

Jacky
May 15th, 2010
Image frame
59

Didn’t try this on your code, I think it can be helpful…

and for MSIE 5.x the expires meta tag

Hopfuly the meta tags above will work for all browsers that use browser cache…

** meta tags can be used in the HEAD section of any page **

Willem Vyent
May 17th, 2010
Image frame
60

I just want to refresh a particular div
the codes goes like this

var refreshId = setInterval(function()
{
$(‘#responsecontainer’).fadeOut(“slow”).load(‘#responsecontainer’).fadeIn(“slow”);
}, 10000);

the div do refresh but the problem is my whole page get destroyed when it refresh.
how do i solve this problem?

Dox
May 21st, 2010
Image frame
61

IT works fine in google chrome. however in mozilla its stop displaying the div after a 3 times of show. how can i solve this problem?

DOX
May 22nd, 2010
Image frame
62

Wow, this script worked perfectly. I used it to refresh the number of users currently active on my game server. It was perfect, thankyou so much.

Lawrence
May 29th, 2010
Image frame
63

Anyone has the solution for IE8?

The content of the div doesn’t refresh.

I thought it was a cache problem, but it isn’t (i tried to clean the cache via PHP).

Any suggestions?

Stefano
Jun 23rd, 2010
Image frame
64

hi,, nice to grab your script

is working for my auto refresh div now, but i have a problem with some jquery marquee script to show running text on the same page but on the different file of this auto refresh div

the problem is running text get freeze a second when jquery do auto refrech in 3 second

now i want to customize your jquery auto refresh div that it only refresh when there is a new record in database

as simple is, if there a new record in database then do auto refresh

anyone can help me?

thnks for the help :)

stein
Jul 7th, 2010
Image frame
65

Thanks for this script.
I don’t like the fade out / in effect, can it be removed and how?

Thanks in advance.

Dev_Guy
Jul 16th, 2010
Image frame
66

You rock man!!!

It really works. thanks alot :)

Taimur Hassan
Aug 3rd, 2010
Image frame
67

I fix de problem for IE cache tha is the problem just add this code

$.ajaxSetup({ cache: false });

var refreshId = setInterval(function()
{
$(‘#responsecontainer’).fadeOut(“slow”).load(‘chi.php’).fadeIn(“slow”);
}, 1000);
$.ajaxSetup({ cache: false });

GOOOD script

Gustavo
Aug 4th, 2010
Image frame
68

Hi, i modified this code and work very fine :) i use it to reload div with online information :)
Thanks!

Aderek
Aug 6th, 2010
Image frame
69

Hey, thanks for the code. I used it as a base to do a basic image change. I’m new to AJAX so there may be a better way to do this but it is quite simple:

$(document).ready(function() {

document.getElementById(‘ID1′).innerHTML = “”;

document.getElementById(‘ID2′).innerHTML = “”;

});

var refreshId = setInterval(function() {

document.getElementById(‘ID1′).innerHTML = “”;

document.getElementById(‘ID2′).innerHTML = “”;

}, 5000);

Just use the etc. to show where you want them.

I’ve gone a bit more complex though. The .gif files are actually PHP files that are giving a image output. This allows you to do all sorts of fancy stuff behind the scenes. For example, I have a script that checks the database for various things and then presents a image stream depending on the results. In my case it is a simple green tick or red cross image from one of the many free vector packs online.
You can do something like this by using code along the lines of:

By using these two methods together you can make a dynamic real-time updating table. I used one from http://cssglobe.com/lab/tablecloth/ but there are plenty more about.

Now I have a nice table that changes it’s green ticks and red cross images depending on the conditions fed to the PHP page every few seconds, without needing to do a full page update – fantastic! :)

Hope that gives someone a few ideas and some further code to play with.

Agent
Aug 16th, 2010
Image frame
70

Excellent script, thank you, you have saved me some dev time!

Toby
Aug 18th, 2010
Image frame
71

I’m having trouble whit using redirect in response.php.
You see,I put if else condition in response.php.There is a condition that if its true the page will go to another page.
I ve used all redirect method that I know, but still it doest work.
Could you help me with that?
Thanks a lot

Tommy Bustomi
Aug 19th, 2010

feel free to leave a scribble

Name:
Email:
gravatar
Want an image next to your comments?
visit gravatar.com
Message:
Get a free quote