How to load XML data with JavaScript (AJAX tutorial)

by admin on July 24, 2009 · 0 comments

The latest technology (or grouping of technologies) sweeping the web is AJAX (Asynchronous JavaScript And XML). This technology, using the XMLHttpRequest() object to retrieve a piece of XML in the background, and load its contents into the web page dynamically, thus creating a constantly refreshed Dynamic HTML (DHTML) interface.

You can make very complication AJAX code, but this is the bare-bones code to simply grab a node from the XML (I'll use a total sales revenue number as the target), and dynamically modify the page contents to display it on the page in a DIV with the ID "salesTotal".

function getSalesTotal()

{
        url = "xml_sales_total.php";
        // AJAX code for Mozilla, Safari, Opera etc.
        if (window.XMLHttpRequest) {
                  xmlhttp = new XMLHttpRequest();
                  xmlhttp.onreadystatechange = xmlhttpChange;
                  xmlhttp.open("GET", url, true);
                  xmlhttp.send(null);
        }
        // AJAX code for IE
        else if (window.ActiveXObject)  {
                  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                        if (xmlhttp)
                        {
                                xmlhttp.onreadystatechange = xmlhttpChange;
                                xmlhttp.open("GET", url, true);
                                xmlhttp.send();
                        }
          }
}

function xmlhttpChange()
{
        //create XMLDOM object if xmlhttp shows "loaded"

        if (xmlhttp.readyState == 4) {
          // if "OK"
          if (xmlhttp.status == 200) {
                        var salesTotal = xmlhttp.responseXML.getElementsByTagName("salesTotal");
                        if (browser == "Internet Explorer") {
                                salesTotal = salesTotal[0].firstChild.data;
                        } else {
                                salesTotal= salesTotal[0].firstChild.data;
                        }       
                        document.getElementById("salesTotal").innerHTML= salesTotal;          
          } else {
                //alert("There was a problem retrieving the XML data");
          }
      }
}

timeout = setInterval("getSalesTotal()", 1000);

Previous post:

Next post: