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 19 | <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);
$.ajaxSetup({ cache: false });
});
</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
This blog post was written on 26 Feb 2009 by Maruf, and has 122 Comments so far
Learning & sharing
This is where we store some of our Web Development thoughts, tips and tricks for both our own uses and for others to learn from. Sharing is caring.
Please feel free to contrinute to our blog posts; perhaps even teach us a few tricks of your own. We'd love to hear your thoughts.
Social
Feel free to share this blog post and/or subscribe to our RSS feed :)
This doesn’t work in IE7 unless user has set his browser not to cache to page.
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
Hi,
I just want to say that it works for me.
thanks
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
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
. Otherwise, this is great!
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.
tx
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”.
All that i can say is its working for me..
thank you for document !
You could use jQuery’s built in event timer too:
.everyTime(5000,function(i){ });
Dude ,
Great ya . Thank a lot its working for me . i just look for this script
Worked great on a live stats system for me, thanks!
How would you pause or stop the refresh?
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.
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?
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?
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!
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
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)
Tnx Pal its really cool and works perfectly, a usful piece u know.
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.
hy, i just wanna said that it works. made life easier. big thanks.
Hi. Quick question: why are you setting a refreshId var and not going right into the setInverval()? Thanks!
Thanks, but still can´t find a clean solution to the ie7/8 problem
Hey Guys,
I’ve updated the code- it should work in I.E now!
Let me know how you guys get on.
Many thanks!
Thanks for the code man!
thank you!
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.
Will it not slow down the users computer
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…
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);
});
Thanks! It worked for me!!!
you are awesome…..!! great work…….!!
how do i use this with noconflict,
because its not workin on my site…
http://indiecore.net
The script is not displaying links i mean there are not clickable.. how can i make them clickable? thanks.. great script
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
Thanks dude.
Is there a way to make it refresh only once, or stop after the first refresh?
Nice work by the way, it works great!
Figured it out, changed setInterval to setTimeout.
Thanks for the code.
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!
nvm i got it workin, just forgot to post back!
makes my radio station a lil nicer
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.
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!
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!!
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
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.
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!
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 :-].
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
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
}
);
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.
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
Thanks for this script. It works perfect. I was straggling to great a chart, but with this script its working. Thank you again
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?
Superb! Very very nice work! Thank you for share!
Thanks for the code, it works great
But How ca I stop the refresh with a link?
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
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 **
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?
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?
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.
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?
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
Thanks for this script.
I don’t like the fade out / in effect, can it be removed and how?
Thanks in advance.
You rock man!!!
It really works. thanks alot
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
Hi, i modified this code and work very fine
i use it to reload div with online information 
Thanks!
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.
Excellent script, thank you, you have saved me some dev time!
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
Thanks a lot.
FANTASTIC Script! This was exactly what I was looking for. I was able to get it to work with IE and FF by passing the following variables:
$(\”#responsecontainer\”).load(‘gcc_display.php?randval=’+Math.random()+’&name=$ASSIGNEE&kookie=$KOOKIE’);
The ASSIGNEE & KOOKIE variables are custom ones I needed, and by adding the Math.random() it worked with IE. Otherwise it would not work with IE. You may want to put a comment indicating the 2nd stanza is required for IE. I am using this at a MAJOR Fortune 100 company for our worldwide call center application I developed, so I really appreciate your help. You should be proud of your work.
Awesome script.
Would it be possible to only load new content from the .php file? And fade in the new changes into the div?
If anyone can help me with this modification please get in contact. Happy to pay for your time.
AMAZING!!! ONE OF BEST BEST BEST J.S. I WAS EVER FOUND IN THE WEB!!!!!
becouse of this great script – From my next Adsense check, i wish to “buy you beer”…do you have paypal? – remaeis@gmail.com – Ivan -
Trying to use this script with JSP pages in a MVC application. For some reason it wont work. I have the jquery library imported. I can call my JSP pages which return data from a database lookup with an URL of the form ‘http://localhost:8080/realtime/data’ In the .jsp page i tried using the same URL in ‘load’ but it didn’t work. Tried to create URL using another standard tag library, which works everywhere but the ‘load’ here. please help.
all i can say is i love you LOL
maruf = \m/
Brill! Thanks for the simpler way of doing it, I originally did it the “Outdated” way you have shown, The jQuery version is amazingly quick! Top marks
Dude, you saved my life….
I tried to make de refresh by my self but it didn’t work…
Thx a lot!
This code crashes FF and eats a lot of memory. Any update?
Thnx
Amazing ,. awesome dude .. thanks for share .. love it :-bd
Superb! Thank you for a usefull script.
@ 67 Nice with $.ajaxSetup({ cache: false }); Fixes the IE cache problem. Great work!
if you want to add to load the same div than use this load(/yourfile.php #responsecontainer); cheers
is it possible to use purely php to make a chat room that does not refresh the entire page, no frames either
I trawled through a lot of help till i found yours.
Amazing work!
It works for me too
Just wanted to say thanks for this script. I got it working with the rantex script to create a rotating random testimonial/quote from a pre-determined list.
Cheers!
How to pause the auto refresh on mouseover? I have a div(#responsecontainer) with a news article and photo inside — if user mouses over article or image I’d like to pause the autorefresh so they can finish reading article. Seems like it should be simple but after searching two hours and trial and error no joy yet.
This code is what i want!
Thanks Author!
Thanks BrightCherry!
Amazing ,. awesome dude .. thanks for share ..
This is working great except for one thing. Memory continues to grow after each .load. So if the user leaves this page open for a while, the memory usage for the browser becomes very large, depending on the contents that are loading insided the div on each refresh. Is there a way to fix this problem?
Nice pretty looking script. lightweight and efficient. excellent man!
This script is beyond amazing!! I use it to show real time trucking loads that are available all across the united states =)
It works like a charm! Really thanks!
After a year i used this code again, thanks for it!
Is there any way to import a file from different domain ? how about the cross-domain things… is it possible ?
and hey i want to buy a beer to you, give me your paypal
Need help. Does anyone knows how to make the auto refresh/reload of the page when the input has no value, but if the input has a value, in will stop the refreshing/reloading. Thank you…
Works fine! Really thanks! Anyway JSON response as an use example could u replace wth that php rand
Works fine! Thanks alot!
Very Very nice script but had a prob. not updating in IE keep reading post and Gustavo 04/08/2010 fix the prob. with the post thanks all
Thanks two tons, man. I had a little trouble with an RSS parsing script until I realized that I’d have to have the actual parsing script itself in the response.php, not just the script that places the feed.
It works great now though, it’s exactly what I needed,
I got the script to work. My problem is in the php document I have to use <?php and not <?. Now when the script activates on my page it breaks the page and doesn't reload in the div tag? Here is my code :
/***********************************************
* PHP Photo Album script v2.0- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for this script and 100s more
***********************************************/
php page
$(document).ready(function() {
$(“#responsecontainer”).load(“response.php”);
var refreshId = setInterval(function() {
$(“#responsecontainer”).load(‘response.php?randval=’+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});
good one.. Its works for me
man,that code is awesome
but i have a problem with page which have paging content
i cant go to page 2,3,4,…
just stuck in page 1
anyone can help??
It might take some time to wrap your head around the theming system but it boils down to defining a stylesheet file for the theme and at least one PHP page template based on the master ‘look’ of your site. Add PHP code in strategic places to insert the title, posts, widgets, etc. and let WordPress do the heavy lifting. Look at other themes as examples, particularly the ones that claim to be simple and CSS-oriented, they should be easier to decipher.. . Everything you need to know is here:. http://codex.wordpress.org/Theme_Development
I agree with the other comments regarding memory – this code has a memory leak somewhere. I have reproduced the problem on multiple browsers. Firefox is particularly susceptible and crashes after a time.
I can’t seem to get it to work with WHILE loops… anyone having the same problem? The info is not displaying. Although the example files with the random numbers work for me.
this is great, really
but is there a way to avoid page scrolling up to the container div after loading the external page?
if you have a vertical layout and a short interval this could be very annoying
thanks buddy for the great script!! i was doing heat maps this turned out to be a life saver
thanks
This works fine. Is it technically possible in jquery to refresh .txt file only if it was modified or newer than the old one which loaded at the start.
Works perfectly! Thanks
Works great! Thanks, I’ve sent you beer money
Is there any way to rotate between 3 php files in the same div?
In other words, load file1.php into then after 20 seconds refresh with the contents of file2.php, then after 20 seconds refresh again with the contents of file3.php and then back to file1.php in a continual loop?
Hi!
thx for the script.
But i got a problem with it and multiple instances
I use script to alter some remote wsdl service which works perfectly updating it. But if another user (more then 1) opens webpage and alters same variable with different value then first user it will keep switching them both from value1 to value2 so it is in the loop :S Is there anyway to fix this?
Hi, i was so happy to find this code, im using to update a list of messages posted by my family on our site and i thought it was working perfect till i noticed that buttons were now missing, i display the messages from mysql and if the session member = message author there should be a delete button next to the message but it dissapears when the div updates, any ideas? i really want to get this working as its the best code i have tried so far.
Thanks
And if you whant to stop refreshing :
clearInterval(refreshId);
Hi. Very nice stuff.
But I want to print Loading… in div while loading ajax content
Any idea
Thanx in advance…
Lol note to self, do NOT implement a 5 second check if more than 20-30 users.. Apache will hate you afterwards..
I watched my server load go from 0.70 to 3.80 after implemenation and it only returned a single number (lol)
Thanks for the Script!
Works for me!
thanks
Hai guys. I want to know how to add fadeIn/fadeOut function together with the auto refresh function. Is it possible??
Love this. Best explanation yet!!!!! Thanks a lot man.
Does this only work with PHP pages? I need a solution that will work with html pages rather than PHP.
My div already shows the correct data. I just need it to reload that div. If I hit F5 it refreshes it correctly, but I want to be able to achieve this by just reloading the div.
@craig – Yes it works for php. Put your php content in response.php