Sammu’s Weblog

Auto-refreshing dynamic content using AJAX

Posted by: sammu on: August 20, 2008

Using AJAX, it is possible to regularly auto-refresh a section of a webpage containing dynamic content without reloading the whole page.

Auto-refreshing dynamic content using AJAX

The script uses an XMLHTTPRequest to retrieve a dynamic page which is then inserted into the output page.
This content is then refreshed automatically using the Javascript setTimeout() function.

First of all you need a dynamic content page.
I’ve used a simple ASP date & time script as an example and named the page 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">
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.

1 Response to "Auto-refreshing dynamic content using AJAX"

..] Thank you for reading this post. You can now Leave A Comment (0) or Leave A ..]

Leave a Reply