Recent Posts
Categories
Archives
Tags
Home >> Blogs >> Web Development >> Load Content Dynamically with Ajax
AJAX (wiki) is a great way of performing tasks which would usually require you to reload the web page. For instance, in an estate agent website I developed, logged in users could do a search for properties. If they found a property that they liked, they could click on the “Save to Favourites” link. This would redirect the page to another page which would save this property ID in the client’s favourites list, then redirect back to the search results page. When it reached the search results page now, this property obviously did not have a “Save to Favourites” link anymore…
Enter Ajax. By applying ajax to this page, I could have the user click the link, and save the property and remove the link without needing to reload the page. This saves bandwidth (no reloading pages), saves time (don’t have to run the search query again), and it just looks slick and professional.
Ajax basically works (in layman terms, read the wiki above for a more detailed explanation) by calling a web page from a javascript, and making the result of that page available to use in the script.
So, lets say I had a form on my page which asked the user to enter the name of a city. When they click on the submit button, it should look up the current temperature of that city and display it. Usually, we would submit the form and redirect between pages to display the result. Using ajax, the javascript can call a page that does the lookup, and it can then display the information on our page using the innerHTML property of the document….
Here is an example:
<html>
<head><script type=”text/javascript”>
xmlhttp = null;
count = 0;var d = new Date();
function ClearFile(StartTimer)
{
xmlhttp = null;
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}RndString = d.getFullYear() + “” + d.getMonth() + “” + d.getDate() + “” + d.getHours() + “” + d.getMinutes() + “” + d.getSeconds() + “” + count++;
xmlhttp.open(“GET”,’http://localhost:81/test/DeleteFile.php?C=’ + RndString,false);
xmlhttp.send(null);if(StartTimer == 1)
{
setTimeout(‘DoXMLPart()’, 2000);
}}
function DoXMLPart()
{InnerHTMLText = “”;
setTimeout(‘DoXMLPart()’, 5000);
xmlhttp = null;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}RndString = d.getFullYear() + “” + d.getMonth() + “” + d.getDate() + “” + d.getHours() + “” + d.getMinutes() + “” + d.getSeconds() + “” + count++;
xmlhttp.open(“GET”,’http://localhost:81/test/tags.txt?C=’ + RndString,false);
xmlhttp.send(null);if(xmlhttp.responseText != “”)
{
InnerHTMLText = document.getElementById(“File”).innerHTML + xmlhttp.responseText;
document.getElementById(“File”).innerHTML = InnerHTMLText;ClearFile(0);
}}
</script></head>
<body onload=”ClearFile(1);” onunload=”ClearFile(0);”>
<div id=”File” name=”File”></div>
</body>
</html>
When the page is loaded, the onload event in the body tag calls a function ClearFile(1). In clear file we set up our XMLHttpRequest object and load a page called DeleteFile.php. Delete file simply opens a text file on our server called tags.txt and makes it blank.
It then sets a timer to 2 seconds (2000 milliseconds). When the time times out after 2 seconds, it will call a function called DoXMLPart().
The first thing we do in this function is set a timer to call this function again after 5 seconds. We do this because we want to continually check the server for data in this file. Obviously you could use ajax without timers, for instance you could respond to the onclick event of a button.
Next, we set up our XMLHttpRequest object again and then call a page called tags.txt.
The property xmlhttp.responseText will contain any data from that call. In otherwords, it will contain the complete text of that file.
The line if(xmlhttp.responseText != “”) checks to see if there is anything in the file. If there is, we add it to the contents of the div called File. We then delete the contents of the file tags.txt
Using this method, we can add content to tags.txt and as we do it gets displayed to the user. Of course, we could call a php page as we did with DeleteFile.php.
A very important point is that IE 7 does not handle ajax terribly well. Internet explorer 7 (I haven’t tested the other versions) uses some extreme caching. The first time the ajax script is called it works fine, but thereafter it just keeps calling the ajax script that you called first. So, in our timed script above it would usually just repeat the first action over and over. It does not display new content, and even if the file is made blank, it keeps displaying what was in the file the first time. Its a real nuisance.
There is a work around though. We do two things.
1) You will notice that I have made the variable that holds the ajax xml request (xmlhttp = null;) a global variable.
2) By passing a unique query to the page you are querying, IE7 does not use the cached version.
That is the reason for this line of code:
RndString = d.getFullYear() + “” + d.getMonth() + “” + d.getDate() + “” + d.getHours() + “” + d.getMinutes() + “” + d.getSeconds() + “” + count++;
We create a random string which is made up of the current date and time, and an extra portion which is count. Count is a numeric value that starts at 0 and is incremented each time it is used. Note that it is not good enough to just use the count portion without the date and time portion. If the user presses refresh, the count starts at 0, but there are already cached versions of 0, 1, 2, etc, so the user will start to see actions which occured in the past repeating themselves… very confusing.
We then use this random string in our request:
xmlhttp.open(“GET”,’http://localhost:81/test/DeleteFile.php?C=’ + RndString,false);
This solves the problem with ajax (XMLHttpRequest) and IE7 perfectly. This problem does not occur in firefox.
If you have any comments or questions about this topic, please feel free to ask….
Sample code 1
This sample code has two html files, index1.html and index.html. index1.html does not use the work around as described here, so will not work with all IE’s. index.html does have the work around, so should work. This sample requires a properly running web server. You need to place the code onto a working server and run from there. Change the content in the tags file and they will be displayed in the page.
Sample code 2
This sample is much simpler. It only has 2 files and does NOT need to run in a web server, so you can run it straight from your desktop. Open index.htm and then open test.txt. Change the content of test.txt to see the changes in the server.