Auto-refreshing dynamic content using Asynchronous JavaScript And XML (AJAX)

In this example I've used a simple ASP date & time script to show how dynamic content can be regularly updated on a webpage without it having to be re-loaded.

First of all you need a dynamic content page.
I've used the following code as an example and saved the page as time.asp:

<% Response.CacheControl = "no-cache" %>
<%= Date %> @ <%= Time %>

You need to include the line: <% Response.CacheControl = "no-cache" %> as Internet Explorer will cache this page otherwise, and the content will not be updated on the output page.

Next, place the following script in the head of the output page:

<script type="text/javascript">
// Set the variable for the dynamic content page below
var page = "time.asp";
function ajax(url,target)
{
// native XMLHttpRequest object
document.getElementById(target).innerHTML = 'sending...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = function() {ajaxDone(target);};
req.open("GET", url, true);
req.send(null);
// IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = function() {ajaxDone(target);};
req.open("GET", url, true);
req.send();
}
}
setTimeout("ajax(page,'scriptoutput')", 10000);
}
function ajaxDone(target) {
// only if req is "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200 || req.status == 304) {
results = req.responseText;
document.getElementById(target).innerHTML = results;
} else {
document.getElementById(target).innerHTML="ajax error:\n" +
req.statusText;
}
}
}
</script>

Set the variable for your dynamic content page at the top of the script:

var page = "time.asp";

Adjust the content reload time (currently set at 10000 milli-seconds or 10 seconds):

setTimeout("ajax(page,'scriptoutput')", 10000);

Add an onload event to the page's body tag to call the script:

<body onload="ajax(page,'scriptoutput')">

Define an area for the content - in this case is just a span within a paragraph:

<p>Current Server date & time (updated every 10 seconds):<br />
<span id="scriptoutput"></span></p>

Finally, save the page and upload it along with time.asp to the same folder in your webspace.

If we put all of this together, the output is as follows:

Current Server date & time (updated every 10 seconds):

If you want to use the example above but don't have access to the dynamic content page to add the CacheControl line ( <% Response.CacheControl = "no-cache" %>) you can still avoid Internet Explorer caching the content by adding a random querystring to the called page in the script.

To do this, replace the two instances of the line:

req.open("GET", url, true);

in the script with:

req.open("GET", url+"?sid="+Math.random(), true);