N341  AJAX

Modified
Use IE5 to view and run tutorials on XML.

Overview

AJAX (Asynchronous Javascript And Xml) is a development technique for creating the user interface by changing the current page versus loading a entire new page.

One benefit is that the user sees only a small change when the interface changes (e.g. when new data is displayed). Other benefits include lighter load on the server.

The basic idea is the browser requests data from a server and when received, the browser modifies parts of the HTML being rendered. For example, changing the source of an image changes the image displayed.

Although XML is part of the AJAX name, any type of data can be used; because XML is automatically parsed into a tree structure, it is easier to manipulate using JavaScript.

One key to AJAX is retrieving data from a server. As we have seen before, the browser can request data from the server using a method=GET in a form.

Text data example

The example below illustrates several key points:

  1. Microsoft.XMLHTTP - is the Microsoft object used on IE to request data from the server. Other browsers use a different object, one should determine which browser is used.
     
  2. req.onreadystatechange = handleResponse - defines a function that will handle state changes. The function is not executed until the ready state changes. When the state changes in our example, we check values for 4 that the server has responded and 200 that the server replied OK to the data request.
     
  3. req.responseText - is the text returned by the server. The text box of the form is assigned the text returned.
     
  4. req.open("GET", "data.txt", true) - Requests that the server return the contents of data.txt; note that it is inside the function submitForm() and executed when the Submit button is clicked.
     
  5. Note that getText.htm must be loaded from a server in order for req.open("GET", "data.txt", true); to load from the server.

getText.htm

<script language="JavaScript">
  var req = new ActiveXObject("Microsoft.XMLHTTP");

  function submitForm() {
    req.onreadystatechange = handleResponse;
    req.open("GET", "data.txt", true);
    req.send(null);
  }

  function handleResponse()
     if(req.readyState == 4)
      if(req.status == 200) 
           document.ajaxGet.dynamic.value = "Received:" + req.responseText;
      else
          document.ajaxGet.dynamic.value="Error: " + req.status + " " + req.statusText;
    }
</script>

<FORM method="GET" name="ajaxGet" action="">
           <INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
           <INPUT type="text" name="dynamic" value="">
</FORM>

data.txt

Hello world!

Clicking Submit produces the following:

 

Exercise 1
  1. Copy and paste the above to getText.htm and data.txt files on W:\N341.
  2. Load into IE by: www.ius.edu/username/N341/getText.htm
  3. Clicking the submit button should change the contents of the text box to that of data.txt file.

 

User interfacing benefits

One use for AJAX is user interfaces that change details on the current page rather than loading a new page.

The following uses the innerHTML attribute to change the text displayed in the id=resultText from Hi to the Hello World! of the text file.

Note that getInnerHTML.htm must be loaded from a server in order for req.open("GET", "data.txt", true); to work.

getInnerHTML.htm

<script language="JavaScript">
  var req = new ActiveXObject("Microsoft.XMLHTTP");

  function submitForm() {
    req.onreadystatechange = handleResponse;
    req.open("GET", "data.txt", true);
    req.send(null);
  }

  function handleResponse() {
     if(req.readyState == 4)
      if(req.status == 200) 
          document.getElementById("resultText").innerHTML = req.responseText;
    }
</script>

<FORM method="GET" name="ajaxGet" action="">
           <INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
</FORM>
<div id="resultText">Hi</div>

Hi

 

Exercise 2
  1. Copy and paste the above to getInnerHTML.htm and data.txt files on W:\N341.
  2. Load into IE by: www.ius.edu/username/N341/getInnerHTML.htm
  3. Clicking the submit button should change the text from Hi to that of data.txt file.

 

XML data example

The example below illustrates one main difference between receiving text and XML.

req.responseText is replaced by: req.responseXML

Recall that XML, when loaded by the browser, is represented as a tree structure. The instructions to access the data in the tree formed by the XML of the data.xml  file are:

Retrieve the root of the XML document tree.

var doc = req.responseXML;

Retrieve the Greeting element

var element = doc.getElementsByTagName('Greeting').item(0);

Retrieve the data of the element and assign to the form text box.

document.ajaxGet.dynamic.value= element.firstChild.data;

 

getXML.htm

<script language="JavaScript">
  var req = new ActiveXObject("Microsoft.XMLHTTP");

  function submitForm() {
    req.onreadystatechange = handleResponse;
    req.open("GET", "data.xml", true);
    req.send(null);
  }

  function handleResponse() { 
    if(req.readyState == 4)
      if(req.status == 200) {
           var doc = req.responseXML;                             // process XML document
           var element = doc.getElementsByTagName('Greeting').item(0);
           document.ajaxGet.dynamic.value = "Received:" + element.firstChild.data;
      }
      else
          document.ajaxGet.dynamic.value="Error: " + req.status +
                                                             " " + req.statusText;
    }
</script>

<FORM method="GET" name="ajaxGet" action="">
           <INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
           <INPUT type="text" name="dynamic" value="">
</FORM>

data.xml

<Greeting>
   Hello world!
</Greeting>

Clicking Submit produces the following:

Exercise 3
  1. Copy and paste the above to getXML.htm and data.xml files on W:\N341.
  2. Load into IE by: www.ius.edu/username/N341/getXML.htm
  3. Clicking the submit button should change the contents of the text box to that of data.xml file.

 

XML generated from Access database example

The source of the XML can be a static file or dynamically generated be a server. The following example illustrates how an ASP program returning the XML from an Access database can serve as a data source.

The main difference is that the XML DOM tree must be accessed differently due to the organization of the XML generated on the server.

req.responseText is replaced by: req.responseXML

Recall that XML, when loaded by the browser, is represented as a tree structure. The instructions to access the data in the tree formed by the XML of the Portfolio.xml  file are:

Retrieve the root of the XML document tree.

var doc = req.responseXML;

Retrieve the z:row element.

var element = doc.getElementsByTagName('xml/rs:data/z:row').item(0);

Retrieve the attributes of the z:row element indexed at 2.

var att=element[2].attributes;

And assign the value of the ID attribute to the form text box.

document.ajaxGet.dynamic.value=att.getNamedItem("ID").value;

 

getAccessXML.htm

<script language="JavaScript">
  var req = new ActiveXObject("Microsoft.XMLHTTP"); // For IE only;

  function submitForm() {
    req.onreadystatechange = handleResponse; // called on state change
    req.open("GET", "Portfolio.xml", true);
    req.send(null);
  }

  function handleResponse() {
    if(req.readyState == 4)
      if(req.status == 200) {
        var doc = req.responseXML;
        var element = doc.getElementsByTagName('xml/rs:data/z:row');
        var att=element[2].attributes;
        document.ajaxGet.dynamic.value=att.getNamedItem("ID").value;
     }
     else
        document.ajaxGet.dynamic.value="Error: " + req.status +
                                                           " " + req.statusText;
  }
</script>

<FORM method="GET" name="ajaxGet" action="">
  <INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
  <INPUT type="text" name="dynamic" value="">
</FORM>

Portfolio.xml

<xml
  xmlns:rs="urn:schemas-microsoft-com:rowset"
  xmlns:z="#RowsetSchema">
  <rs:data>
    <z:row ID="Ray"
               SYMBOL="IBM"
               SHARES="10"/>
    <z:row ID="Jason"
                SYMBOL="MSFT"
                SHARES="100"/>
    <z:row ID="Harold"
                SYMBOL="FORD"
                SHARES="15"/>
    <z:row ID="Alex"
                SYMBOL="UAL"
                SHARES="230"/>
    <z:row ID="Robin"
                SYMBOL="FORD"
                SHARES="100"/>
    <z:row ID="Carol"
                SYMBOL="GMC"
                SHARES="20"/>
  </rs:data>
</xml>
 

Clicking Submit produces the following:

Exercise 4
  1. Copy and paste the above to getAccessXML.htm and Portfolio.xml files on W:\N341.
  2. Load into IE by: www.ius.edu/username/N341/getAccess.htm
  3. Clicking the submit button should change the contents of the text box to that of ID element in the 3rd row of Portfolio.xml file (e.g. Harold).

 

Dynamic server data

All of the above examples used a static file as a data source. However, dynamic data generated by a server program can also be the data source.

To dynamically generate the XML from the server program below change:

req.open("GET", "Portfolio.xml", true);

to:

req.open("GET", "Portfolio.asp", true);

Portfolio.asp
<%@ Language=JScript%>
<%
   conn = Server.CreateObject("ADODB.Connection");
   conn.Mode = 3;
   conn.Open ("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" +
                      Server.MapPath("Project.mdb"));
   rs = conn.Execute("SELECT * FROM PORTFOLIO");

   var xmlDoc = Server.CreateObject("Msxml2.DOMDocument");
   xmlDoc.async = false;
   rs.Save (xmlDoc, 1) ;                  // Convert rs recordset to xmlDoc as XML tree
   xmlDoc.Save (Response, 1);        // Output XML as Response
   conn.Close();
%>

 

Exercise 5

This exercise requires that the Portfolio.asp program run in the same directory as the Project.mdb data file.

  1. Copy and paste the above to Portfolio.asp file on W:\N341\Project.
  2. In getAccessXML.htm change:

    req.open("GET", "Portfolio.xml", true);

    to

    req.open("GET", "Project/Portfolio.asp", true);

  3. Load into IE by: www.ius.edu/username/N341/Project/getAccessXML.htm
  4. Clicking the submit button should change the contents of the text box to that of ID element in the 3rd row of Portfolio.xml file.