Tullig.Net: Home arrow Web Construction arrow Using AJAX To Update Data On A Web Page
Using AJAX To Update Data On A Web Page PDF Print E-mail
Written by David Hollingworth   
Thursday, 19 July 2007

The Javascript

The javascript gets called when the HTML page is loaded using the onload event we saw earlier. The getData() function is a Javascript function that starts the chain of events to load and display the data. I'm not going to go into too much detail in the narrative about the script because it's fairly well commented, except to say that you'll need to put it into a script file, E.g. conditions.js, and save it somewhere sensible on your server. Then you include the script into your HTML page with a line in the head section of the document:

<script type="text/javascript" src="conditions.js"></script> 

Here the conditions.js file is in the same directory as our web page. 

OK, here's the Javascript in full. There's a couple of bits you'd have to change for your implementation at the top of the file. You'll have to change the url to point to your domain and location of the responder script. You can also update the interval to a sensible number of seconds depending on how often your XML file is ftped to your server. I ftp my file every 60 seconds so I've got the update interval set to 30 seconds to catch each update as soon as possible.

var response;
var request = false; // The object to handle the request for data
var reqType = "GET"; // Make the request type a GET as opposed to a POST
var url = "http://your-domain/your-responder-file.php";
var asynch = true; // Make this an asynchronous request
var interval = 1000 * 30;    // Update the page at 30 second intervals

function getData()
{
    //
    // Do the first request, then
    // 
    httpRequest();
    
    //
    // send the request at intervals
    //
    setInterval(httpRequest, interval);
}

/* Wrapper function for constructing a Request object.*/
function httpRequest()
{
    //
    // Only create the request object.
    //
    //Mozilla-based browsers
    if(window.XMLHttpRequest){
        request = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject)
    {
        // IE browsers
        request=new ActiveXObject("Msxml2.XMLHTTP");
        if (! request)
        {
            request=new ActiveXObject("Microsoft.XMLHTTP");
        }
     }

    //the request could still be null if neither ActiveXObject
    //initializations succeeded
    if(request)
    {
       initReq(reqType,url,asynch); // Initialize the request
    }  
    else 
    {
        alert("Your browser does not permit the use of all "+
        "of this application's features!");
    }
}

/* Initialize a Request object that is already constructed */
function initReq(reqType,url,bool){
    /* Specify the function that will handle the HTTP response */
    request.onreadystatechange = handleResponse;
    
    //
    // In order to prevent IE browsers from returning a cached version of
    // the XML file we append a unique value to the end of the URL. This is
    // ignored by the responder script; but ensures the page gets updated.
    //
    var urlToSend = url + "?key=ms" + new Date().getTime();
    request.open(reqType, urlToSend, bool);
  
    request.send();
}

//event handler for XMLHttpRequest
function handleResponse(){
     // alert("readyState = " + request.readyState + "status = " + 
        request.status);
    if(request.readyState == 4){
        if(request.status == 200){
            //
           // Get the XML document back from the request object
           // and display the results.
           //
           var doc = request.responseXML;     
           displayDocInfo(doc);
        } 
        else 
        {
           alert("A problem occurred with communicating between the "
           + "XMLHttpRequest object and the server program.");
           alert("request.status = " + request.status);
        }
    }//end outer if
}

//
// Loop throught the XML document using the element names to
// identify the ids of the span tags in the HTML document.
//
function displayDocInfo(doc)
{
    // Get the root of the XML document
    var root = doc.documentElement;
    var nds;
    var thisTag;
    // If the root has children, i.e. if there's data elements
    // under the root:
    if(root.hasChildNodes())  
    {
        nds=root.childNodes;
        // alert("Root node has " + nds.length + " children");        
        // For each of the child nodes
        for (var i = 0; i < nds.length; i++)
        {
            // Get the corresponding span tag from the HTML document, 
            // e.g. span id="curtemp" /span
            thisTag = document.getElementById(nds[i].nodeName);
            
            // If there's some data contained in this node then
            if (thisTag)
            {
                if(nds[i].hasChildNodes)
                {
                    // set the tyag value to the XML node value
                    thisTag.innerHTML = nds[i].firstChild.nodeValue;
                }
                else
                {
                    // Set the tag value to an empty space
                    thisTag.innerHTML = " ";
                }
            }
        }
        //
        // We need to use the current time elsewhere so just get this nodes value
        //
  var localtime = root.getElementsByTagName('curtime')[0].firstChild.nodeValue;
        thisTag = document.getElementById('localtime');
        thisTag.innerHTML = localtime;
    }
    return;
}
 

If all is well then:

  1. Your AWS software produces a new XML file every minute, having replaced the AWS tags with data, and ftps this to your web server.
  2. Every 30 seconds the Javascript makes a request of the responder script which sends up the latest XML file.
  3. The Javascript then uses the XML tag names to identify the span IDs and to set the span's innerHTML content to the XML data values.


 

 

 



Last Updated ( Thursday, 19 July 2007 )
 
Next >