-
Refreshing DIV content with AJAX
Posted on February 11th, 2009 37 comments
AJAX (Asynchronous JavaScript And XML) is a keystone of Web 2.0 and is very useful in many aspects, because it offers the possibility to change the structure of the page (DOM). For instance, it makes possible refreshing a part of a website instead of having to use the classic page reload, which requests again the whole page from the server even when the updated parts are minimal (much slower and of course consumes more bandwidth; therefore making the visitor experience worse).If you know what a HTML <div> tag is and how to use it, with the help of AJAX refreshing a section of your website is possible. The section which will be refreshed is within a DIV; the rest of the HTML outside the DIV will not be refreshed.
To show you how to do so, I prepared an example with the code required for this purpose. But if you’re new to AJAX and would like to know how the code works, I recommend you to take a look at first at w3schools AJAX tutorial.
In the example, there are three files (in the same folder):
- ajax.js
- index.html
- boo.php
ajax.js contains the XMLHttpRequest object and the javascript code which we need for refreshing the DIV, index.php simply contains the HTML layout of the page and especially the position of the DIV element the content of which we want to refresh, and finally boo.php contains any code which we want to refresh and display in the DIV (in the example, a PHP function).
Let’s see what code is in each file:
ajax.js
// Customise those settings var seconds = 5; var divid = "timediv"; var url = "boo.php"; //////////////////////////////// // // Refreshing the DIV // //////////////////////////////// function refreshdiv(){ // The XMLHttpRequest object var xmlHttp; try{ xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari } catch (e){ try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ alert("Your browser does not support AJAX."); return false; } } } // Timestamp for preventing IE caching the GET request fetch_unix_timestamp = function() { return parseInt(new Date().getTime().toString().substring(0, 10)) } var timestamp = fetch_unix_timestamp(); var nocacheurl = url+"?t="+timestamp; // The code... xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4){ document.getElementById(divid).innerHTML=xmlHttp.responseText; setTimeout('refreshdiv()',seconds*1000); } } xmlHttp.open("GET",nocacheurl,true); xmlHttp.send(null); } // Start the refreshing process var seconds; window.onload = function startrefresh(){ setTimeout('refreshdiv()',seconds*1000); }Lines 3, 4 and 5 allow you to customise how will the DIV refresh: seconds to refresh, divid is the ID of the DIV we want to refresh in index.php and url is the location of the file containing the code which will be put in the DIV (namely, the code we want to automatically refresh).
Lines 38 and following contain some code to fix cache issues with IE. I noticed that while in Firefox 3 the DIV refreshed correctly, in IE it did not (because it cached the external URL being requested, boo.php). So what these lines of codes do is generate a UNIX timestamp and append it to the external URL as a variable (t). The variable is not used at all in the code of the external php file, but it is useful just because every time it partially changes the URL, so to prevent IE caching it. As new UNIX timestamps are always different, the URL will always be unique.
index.html
<script src="ajax.js"></script> <strong>This is the current date and time (updates every 5 seconds):</strong> <script type="text/javascript"><!-- refreshdiv(); // --></script> <div id="timediv"></div>
Not really much to say here (quite obvious, isn’t it?); notice however that in line 6 we include the external JavaScript (ajax.js) and that in line 13 we call the function to initialise the refreshing of the DIV content.
The DIV is empty. Its contents are in the third file…
boo.php
// Format time output $str = "It is %a on %b %d, %Y, %X - Time zone: %Z"; // Echo results echo(gmstrftime($str,time())); ?>
Although the content of this file could have been any, I decided it to be a PHP function (gmstrftime) which requests the current time and formats it. Every time the DIV is refreshed, the function returns the current time formatted; therefore you can clearly see that the example works, as the time will keep refreshing every 5 seconds.
The result, once you completed the example, should look like this:
You can change the code of boo.php to whatever you wish to try new things…
If you’re looking for an example of how to apply this script to a MySQL query to retrieve data automatically from a MySQL database, there’s a post featuring an example of it; you will find it here.
There’s also a post explaining how to refresh the content of multiple DIVs also with AJAX. Read it here.
Happy coding!
Related posts:
AJAX, Computers & programming, HTML, JavaScript, PHP ajax, asynchronous, code, div, html, javascript, php, refresh, reload, section, update, web 2.0, xml37 responses to “Refreshing DIV content with AJAX”
-
Its not working in IE.Please suggest
-
Thanks for the feedback…
Try the new code now, I updated the ajax.js and index.html code and tested it successfully both in Firefox 3 and IE 7.
I noticed that IE would always retrieve the same time (because it cached the GET request), so I added the code at ajax.js lines 38 and following to fix that.
I’ve put a demo of the example here.
-
Thanks for updating the code. Any idea about using the div refresh to fetch data from database for a chat process using php.
-
If you want to do this using a PHP database query, I’d give a try putting the code to do so in the external page to load in the div (namely boo.php in the example). Then you can echo the fetched data also in the external page.
Every time the DIV refreshes, the code in the external file is executed; therefore a query would be made every X seconds.
-
thanks
-
I wrote an extension answering your question, for future reference.
-
Thanks for posting the code.Can a page have more than one div refresh in it. I have tried working this but there seems to be some problem.
-
Thanks for your interest.
Yes it is possible. I’ve just written how to in the following post:
http://www.aleixcortadellas.com/main/?p=397There’s a working demo here:
http://www.aleixcortadellas.com/demos/ajaxdivrefresh2/index.htmlRegards
-
Thanks for posting the code. Does the header location work in the div refresh tag.I tested it but the page opens in the div tag instead of a new page.
-
May I ask what exactly you want to do?
- If you want to retrieve another website within the DIV, then you can do it with the PHP header redirect, or directly fetching the external site in the AJAX refresh function, as innerHtml of the DIV.
- If you want AJAX to refresh (actually redirect) the whole page where the DIV is placed in, then you would do it with JavaScript instead of PHP by using the following line of code:
window.location = “http://www.google.com/”;
- Other action…
Remember you can control the actions AJAX does and when, in the following piece of the code:
if(xmlHttp.readyState==4){
// Actions to perform when Ready
}
But actually, if what you want is the 2nd option then you don’t really need AJAX, I think. So if you give some more details perhaps I can help further…
Regards and have a nice weekend
-
I have got some php code in a div that refreshes using ajax.
In the php code I want to check some conditions and accordingly redirect the page.eg :
if (condition)stmt…
else
header:location to some url
While doing this the redirected page is displayed in the div tag.Can you suggest how I can get the redirected page to be displayed as a parent page instead of getting it displayed in the div tag.
Thanks
-
Okay this is an idea. I’ve tested it and I got it to work, this will do what you want.
Open AJAX.JS and right under the line
if(xmlHttp.readyState==4){add:
if(xmlHttp.responseText.match(”00aa”) != null){
window.location = “http://www.google.com/”;
}Then, open boo.php and add:
$x = 1;if($x == 1){
echo “00aa”;
}This is just an example. You have to change it to get it to work with your script. I tell you a bit what it does: note that boo.php has a conditional echo; when the condition is met, then the string “00aa” is echoed (you can change this). Then, what the ajax.js script piece of code I wrote above does is look if there’s any piece of content in boo.php matching the value specified (”00aa”), using the JS match() method. It will only detect the word or string if it has been echoed, not when it merely is in the PHP code (therefore, make it echo conditionally). So the rule is simple: if AJAX finds a specific word or string in the PHP file, it will do A (redirect). If it does not find it, it will do B (keep refreshing, for instance, until A is met).
Give it a try, it is easier than it sounds like. I hope this solves your problem, if you have further doubts let me know.
Regards
-
Marcio February 28th, 2009 at 19:07
Very Nice Article. I’m learning and this is very useful. Thanks and keep on the good work.
Regards.
-
Thanks for the feedback, Marcio
glad you learned from it… -
Olivia March 16th, 2009 at 15:53
Thank you…..this is the code i’m looking for………THANK……..
-
Suki, alternatively to what I mentioned above, perhaps you could achieve the same effect by using iframes and javascript.
-
I’m a total AJAX newbie, good with php and mysql but not with javascript. I’m trying to tweak your code to do a simple php search and on Submit return the results as a link.
I just can’t get it to work. Any thoughts…
here’s the codeindex.html
ajaxfunction();
ajax.js
var divid = “searchresult”;
var url = “sssearch_ajax.php”;////////////////////////////////
//
// Refreshing the DIV
//
////////////////////////////////function ajaxfunction(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject(”Msxml2.XMLHTTP”); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
catch (e){
alert(”Your browser does not support AJAX.”);
return false;
}
}
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open(”GET”,nocacheurl,true);
xmlHttp.send(null);
}the php
<?php
import_request_variables(”Pg”);
if ($dir = @opendir(”/mnt/shane/CADVANCE99/All Finished Study Sets”)) {
/*if ($dir = @opendir(”/mnt/heidi/CADVANCE99/All Finished Study Sets”)) {*/
while (($file = readdir($dir)) !== false) {
$pos = strpos($file, $nom);
if ($pos !== false) {echo “Click on the link to print all pages of the study set”;
echo ““;
echo $file;
echo ““;
$gotit = true;
break;
}
else {$gotit = false;
}
}
closedir($dir);
if ($gotit == false) {
echo “Sorry, no study sets found”;
}
}
?> -
Hello,
I see you neglected the snippet of code with the function to append timestamp to the end of the url being retrieved. This could be causing the problem…
Notice the line of your code:
xmlHttp.open(”GET”,nocacheurl,true);And the var you configured in the beginning:
var url = “sssearch_ajax.php”;So either you include the code for appending the timestamp, or if you don’t, you should change the first line I mentioned to:
xmlHttp.open(”GET”,url,true);In other words, the code you posted is trying to open the url stored in variable “nocacheurl”, but the url you sprecified is in variable “url”. “nocacheurl” value is url+timestamp…
Try if this is the problem and let me know if it works now. If it still doesn’t, I recommend you try at first the PHP separately to completely discard the problem is there.
Regards
-
I doing a realtime monitoring project. It need to continuously retrieve data from MySQL. Its work fine with the code you post, but i don’t like the 5 second lagging.
Error occur when i change this “var second=5″ to “var second=null”. Is there any way to solve this problem ?
-
Tested it locally and it works to me with null. I’ve noticed you wrote “var second=null”, but the variable name is in fact seconds, so check if your code is “var seconds=null.
Regards
-
Ok. I inserted the time stamp code which seems to have improved the function but I still have a problem. As soon as I open the page in a browser it executes the php code and searches my database, however, it does this before I have enter anything within the text field of my form so of course it searches the database and returns “No files found”. How do I adjust the code so that it does not execute the query until I have entered something in the text field and clicked Submit?
-
Here’s the form I’m working with:
ajaxfunction();
-
Hello,
That’s an easy one, very straightforward:
Sample index.html
< #body>
< #input type="text" id="searchquery" size="30">
< #input type="button" name="Submit" value="Search" onclick="refreshdiv();">
< #div name="timediv" id="timediv">< #/div>
< #/body>NOTE: Remove the # from the code above. I had to put them, or the blog converts the code into elements of the page. Sorry for inconvenience.
This code places a text field and a submit button; refresh function will be called when user clicks on search button (triggers the function with an onclick event) and not when page is loaded. You can retrieve the content submitted in the text box for use in the JavaScript part, by making reference to the text field ID. Example:
var query = document.getElementById("searchquery").value;Regards
-
Ok. I actually have the same form already coded in my html page.
I didn’t however have the variable. I popped it into the javascript but still doesn’t work. Maybe it’s my unusual php code. I’m not actually querying a db, I’m searching a networked drive for a file that matches the file name entered into the form and returning a link to the file in the query results.
Or maybe I put the variable in the wrong place in the javascript?// The code…
var query = document.getElementById(”nom”).value;
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open(”GET”,nocacheurl,true);
xmlHttp.send(null);
}Seems like this should be so simple but I’m on day 4 of this. Arghhh!
Any last thoughts? -
Hehe, happens to me now and then too while coding, that I get stuck…
Now to the point: it looks to me like you don’t use the variable. Ok, you assign the value to variable ‘query’, but do you then use this variable at all? Not in the code above at least.
I assume ’sssearch_ajax.php’ is the script you call periodically with the AJAX script, and that it contains all the PHP code which performs the search of the files you talk about.
You could pass the variable to that PHP script so that the PHP script knows what was written by the user in the text field and return the according results.
To do so, the code above should look like:
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
}
}
var query = document.getElementById(”nom”).value;
xmlHttp.open(”GET”,nocacheurl+’&query=’+query,true);
xmlHttp.send(null);
}About the nocacheurl+’&query=’+query
What this does is append to the url a GET variable which is passed to the PHP script. The GET variable is obviously named ‘query’ and its value will be whatever was written in the text field.
To retrieve the value of the passed GET variable in the PHP script, just use $_GET['query']
Hopefully this helps
-
Thanks for this nice code, Now i am facing some trouble but its not related to your code or that is what i think, I have a chat room in the HTML i want to put who is chatting box, for that i must use info.php , so i have just edited the ajax.js and writted in the
var url = “info.php”;
It works fine in firefox but in IE7 the html code gets nutz, and the whois box doesnt show but some other parts of the page (screwed) can you help me with this, i dont know much of html, i must be doing something wrong or missing some html code to make work properly in danmed IE.. .thanks -
Hello,
This could be a CSS problem. If you’re using CSS to style the chatbox, make sure your CSS is cross-browser compatible.
This tool can be useful in order to validate your CSS and can help you track problems if this is the issue.
http://jigsaw.w3.org/css-validator/Also make sure you’ve set a DOCTYPE
http://www.w3.org/QA/Tips/Doctype
(I know it’s a basic, but I’ve often had similar issues with IE just because of missing DOCTYPE)Let’s see if that’s it…
PS. If you require advanced programming expert help and advice, I strongly recommend you take a look at http://www.experts-exchange.com; I’m a contributor there too.
-
well the doc type i am using
CSS validator validate fine my chat page as css level 2.1, you can check my page to check of what i am talking about, try ie 7 and firefox and ill see that firefox works great…
http://vcomputadoras.com/chat/katrachada2.phpi will really appreciate if you help me out..
-
Hello,
I have found the issue, it wasnt any css related stuff, it was in fact a script i was using to have people to put the website in their favorites, once i took it out your script worked like champ in IE7….thank you.
-
So the script here is conflicting with the favorites script? I wonder what the exact issue is, just curiosity…
Glad anyway you found a quick fix.
-
This is the sript that was conflicting with your code, as i stated before i just took it out of the html and you code worked fine, no issues at all..
= 4)) {
var url="http://vcomputadoras.com/chat/katrachada.php";
var title="Agrega Katrachada el chat 100% a tus favoritos!";
document.write('Agrega Katrachada el chat 100% a tus favoritos!');
}
else {
var msg = "No te olvides de agregar Katrachada a tus favoritos! preciona las techas";
if(navigator.appName == "Netscape") msg += "(CTRL-D)";
document.write(msg);
}
// End --> -
should show the whole script
= 4)) {
var url=”http://vcomputadoras.com/chat/katrachada.php”;
var title=”Agrega Katrachada el chat 100% a tus favoritos!”;
document.write(’Agrega Katrachada el chat 100% a tus favoritos!‘);
}
else {
var msg = “No te olvides de agregar Katrachada a tus favoritos! preciona las techas”;
if(navigator.appName == “Netscape”) msg += “(CTRL-D)”;
document.write(msg);
}
// End –> -
Thanks. Not sure what the issue could be, apart that I have the feeling the variable “url” is potentially conflictive. Note that in my script there’s a variable with the same name, which is not local to a specific function but at the same level as in the second script. I would suggest you try again the two scripts together renaming one of the “url” variables to something unique, so that the value of one of them does not override the other.
Regards
-
Tony Bryant June 11th, 2009 at 19:32
Great Code! I have not read all the comments so someone may have stumbled upon this but just in case. You can update multiple divs with this code by making a couple of simple changes.
First remove vars on lines 4 and 5. Then change line 13 to this:
function refreshdiv(divid, url){
Then change lines 51 and 61 to this:
setTimeout(function(){refreshdiv(divid, url)},seconds*1000);
Then when you call the refreshdiv function from your html page, pass the div id and page you wish to load:
refreshdiv(’timediv’, ‘boo.php’);
If you have more then one div then just call the function twice replacing the div id and page you wish to call.
refreshdiv(’timediv’, ‘boo1.php’);
refreshdiv(’datediv’, ‘boo2.php’);This will make the function generic and universal so that you can call it from a .js file and use it on multiple pages without the need to recreate it for each div.
-
hye aleix,
i love all your ajax tutorials
(just giving you huge pat on your back, because im learning a lot from you
) -
Thanks Daria! Glad you find the information here useful! Whenever I learn more AJAX tips and tricks in the future, be sure I’ll share them here
Kind regards
-
Im searching for sites related to this. Glad I found you. Thanks
Leave a reply



