Using the Ajax Utility Library


Take a look at Figure 5.1, which shows a page that uses the Ajax Utility Library. To download text using the Ajax Utility Library, you just have to click a button.

image from book
Figure 5.1: Using the Ajax Utility Library

When you do click a button, the Ajax Utility Library springs into action, downloading text, as you see in Figure 5.2.

image from book
Figure 5.2: Downloading text using the Ajax Utility Library

That’s the first Ajax framework covered in this book, and it will be developed in this chapter. How easy is it to use this Ajax framework? Just include the JavaScript file ajaxutility.js in your Web page, like this:

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

Note 

This assumes that ajaxutility.js is in the same directory on the server as the Web page you’re including it in; otherwise, be sure to give the full URL to “ajaxutility.js” or your browser won’t be able to find it.

Now you’re free to use ajaxutility.js functions like getText to get text from the server using Ajax techniques. To call getText, you just supply the URL of the data to get (which can be a relative URL), and the name of a callback function. The Ajax Utility functions call that callback function with your downloaded data.

For example, in the page you see in Figure 5.1, the buttons are tied to the Ajax Utility getText function to download data.txt or data1.txt, with the callback functions callbackMessage1 and callbackMessage2:

 <H1>Getting text with the Ajax Utility Library</H1> <form>   <input type = "button" value = "Display text 1"     onclick = "getText('data.txt', callbackMessage1)">   <input type = "button" value = "Display text 2"     onclick = "getText('data2.txt', callbackMessage2)"> </form>

Then you only have to create the callback functions. For example, in callbackMessage1, which is passed the downloaded text when data.txt is downloaded, you can display that text in a <div> element named targetDiv:

 <script language = "javascript">   function callbackMessage1(text)   {     document.getElementById("targetDiv").innerHTML = text;   }         .         .         . </script>

And you add the targetDiv element to the <body> element:

 <body>   <H1>Getting text with the Ajax Utility Library</H1>   <form>     <input type = "button" value = "Display text 1"       onclick = "getText('data.txt', callbackMessage1)">     <input type = "button" value = "Display text 2"       onclick = "getText('data2.txt', callbackMessage2)">   </form>    <div >     <p>The fetched data will go here.</p>   </div> </body>

Similarly, you can set up the callbackMessage2 function, which is passed the text downloaded from data2.txt:

 <script language = "javascript">   function callbackMessage1(text)   {     document.getElementById("targetDiv").innerHTML = text;   }   function callbackMessage2(text)   {     document.getElementById("targetDiv").innerHTML = text;   } </script>

Now you’re using an Ajax framework and you don’t have to write any Ajax code. You just include ajaxutility.js in your Web page and then call the Ajax Utility functions.

What functions does ajaxutility.js support? There are four functions in ajaxutility.js, two for getting text and XML using the GET method, and two for getting text and XML using POST to send data to the server. Here are those functions:

  • getText(urlToCall, functionToCallBack): Uses the GET method to get text from the server.

  • getXml(urlToCall, functionToCallBack): Uses the GET method to get XML from the server.

  • postDataGetText(urlToCall, dataToSend, functionToCallBack): Uses the POST method to send dataToSend to the server, gets text back. Pass the data to send in parameter/value pairs like this: value=100.

  • postDataGetXml(urlToCall, dataToSend, functionToCallBack): Uses the POST method to send dataToSend to the server, gets XML back. Pass the data to send in parameter/value pairs like this: value=100.

How do these functions work in ajaxutility.js? The details are coming up next.

Cross-Ref 

For more information on passing data to the server with the GET method, see Chapter 3.

Get text from the server with getText

The first function in the Ajax Utility Library is getText function, which simply downloads text from the server. To use this function, you pass the URL you want to access, and the name of the callback function you want called with the downloaded text when the download is complete. This function uses the GET method to communicate with the server.

Here’s how the code starts: by creating the getText function, complete with the parameters you pass to it (the URL to call, and the function to call back with the downloaded text):

 function getText(urlToCall, functionToCallBack) {     .     .     . }

The next step is to create the XMLHttpRequest object that this function uses to communicate with the server behind the scenes:

 function getText(urlToCall, functionToCallBack) {   var XMLHttpRequestObject = false;     .     .     . }

Note 

The XMLHttpRequest creation process is inside the getText function itself, which means you can call getText or any other function in the Ajax Utility Library as many times as you want, in whatever succession you want, and each function will still use its own XMLHttpRequest object, even if it’s called multiple times.

First, getText attempts to create an XMLHttpRequest object for the Internet Explorer 7/ Netscape/Firefox brand of browsers:

 function getText(urlToCall, functionToCallBack) {   var XMLHttpRequestObject = false;   if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   }     .     .     . }

And if that doesn’t work, getText attempts to create an XMLHttpRequest object in Microsoft Internet Explorer:

 function getText(urlToCall, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }     .     .     . }

The rest of the code in the getText function is surrounded by an if statement to make sure that an XMLHttpRequest object was created before it attempts to do anything further:

 function getText(urlToCall, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {         .         .         .   } }

If an XMLHttpRequest object exists, the getText function opens the XMLHttpRequest object, configuring it with the GET method and the URL to call, like this:

 function getText(urlToCall, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("GET", urlToCall);          .         .         .   } }

Next, the code connects the XMLHttpRequest object’s onreadystatechange property to an anonymous inner function:

 function getText(urlToCall, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("GET", urlToCall);      XMLHttpRequestObject.onreadystatechange = function()      {          .         .         .     }    } }

In this function, you wait until the XMLHttpRequest object’s readyState property holds 4 and its status property holds 200 to make sure the data has been downloaded correctly:

 function getText(urlToCall, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("GET", urlToCall);      XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {          .         .         .       }      }    } }

Here’s the crux of this function: when the text data has been downloaded, it calls the callback function with that text data:

 function getText(urlToCall, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("GET", urlToCall);      XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {            functionToCallBack(XMLHttpRequestObject.responseText);          .         .         .       }      }    } }

To make sure that the XMLHttpRequest object doesn’t hang around after it’s not needed anymore, the code deletes it this way:

 function getText(urlToCall, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("GET", urlToCall);      XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {            functionToCallBack(XMLHttpRequestObject.responseText);            delete XMLHttpRequestObject;           XMLHttpRequestObject = null;       }      }    } }

Finally, you send a value of null to the server, as you always do when using the GET method:

 function getText(urlToCall, functionToCallBack) {    var XMLHttpRequestObject = false;          .         .         .     XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {            functionToCallBack(XMLHttpRequestObject.responseText);            delete XMLHttpRequestObject;           XMLHttpRequestObject = null;       }      }      XMLHttpRequestObject.send(null);    } }

You’ve already seen how to put the getText function to work in the document testGetText.html (shown earlier in Figure 5.1). It’s easy: you simply call that function with the URL to fetch from the server and the callback function:

 <form>   <input type = "button" value = "Display text 1"      onclick = "getText('data.   <input type = "button" value = "Display text 2"      onclick = "getText('data2. </form> 

The callback function is passed the downloaded text, and you can put that text to work any way you want it, such as displaying it in your Web page:

 <script language = "javascript">   function callbackMessage1(text)   {     document.getElementById("targetDiv").innerHTML = text;   }   function callbackMessage2(text)   {     document.getElementById("targetDiv").innerHTML = text;   } </script> 

That handles the simplest case: getting text from the server. How about getting some XML? That’s what the Ajax Utility Library getXML function is for.

Get XML from the server with getXml

The Ajax Utility Library getXML function lets you use the GET method to download XML from the server. Like getText, all you have to pass it is the URL of the source for the XML, and a callback function to call with the downloaded XML.

Here’s how this function starts in ajaxutility.js:

 function getXml(urlToCall, functionToCallBack) {      .     .     . } 

As you might expect, this function works similarly to getText, with a few differences because it handles XML, not straight text.

In particular, it uses the responseXML property of the XMLHttpRequest object to read the downloaded XML:

 function getXml(urlToCall, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("GET", urlToCall);      XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {            functionToCallBack(XMLHttpRequestObject.responseXML);            delete XMLHttpRequestObject;           XMLHttpRequestObject = null;       }      }      XMLHttpRequestObject.send(null);    } } 

And that’s it! That completes the getXml function.

How about putting this function to work? For example, you might modify the Chapter 3 page lunch.html that downloaded two XML documents, menu1.xml and menu2.xml, and displayed the menu items in those documents in a drop-down list control.

To start this new page, textGetXml.html, you include ajaxutility.js:

 <html>   <head>     <title>Getting XML with the Ajax Utility Library</title>     <script type = "text/javascript" src =        "ajaxutility.js"></script>         .         .         .

Next, you add the controls you’ll need: a <select> control to display the menu items, two buttons that allow the user to select between menus, and a <div> element in which to display the item the user selects for their lunch:

 <form>   <select size="1"       onchange="setmenu()">     <option>Select a menu item</option>   </select>   <br>   <br>   <input type = "button" value = "Select menu 1"      onclick = "getXml('menu1.xml', getmenu1)">    <input type = "button" value = "Select menu 2"      onclick = "getXml('menu2.xml', getmenu2)">  </form> <div  width =100 height=100>Your lunch   selection will appear here.</div> 

Note 

Each button is tied to the getXml function, directing that function to download menu1.xml or menu2.xml, and using getmenu1 or getmenu2 as the callback function.

The getmenu1 and getmenu2 callback functions are passed the XML downloaded from the server, in JavaScript XML document form. They decode that XML and pass it on to a function named listmenu, which displays the menu selections in the <select> control:

 <html>   <head>     <title>Getting XML with the Ajax Utility Library</title>     <script type = "text/javascript" src =        "ajaxutility.js"></script>     <script language = "javascript">       var menu;       function getmenu1(xmlDocument)       {         menu = xmlDocument.getElementsByTagName("menuitem");         listmenu();       }       function getmenu2(xmlDocument)       {         menu = xmlDocument.getElementsByTagName("menuitem");         listmenu();       }       function listmenu ()       {         var loopIndex;         var selectControl = document.getElementById('menuList');         for (loopIndex = 0; loopIndex < menu.length; loopIndex++ )         {             selectControl.options[loopIndex] = new                 Option(menu[loopIndex].firstChild.data);         }     }         .         .         .

Finally, all that’s left is the setmenu function, which the <select> control calls when the user has made a menu choice and it needs to display that choice in the Web page:

 <html>   <head>     <title>Getting XML with the Ajax Utility Library</title>     <script type = "text/javascript" src =        "ajaxutility.js"></script>     <script language = "javascript">       var menu;       function getmenu1(xmlDocument)       {         menu = xmlDocument.getElementsByTagName("menuitem");         listmenu();       }       function getmenu2(xmlDocument)       {         menu = xmlDocument.getElementsByTagName("menuitem");         listmenu();       }       function listmenu ()       {         var loopIndex;         var selectControl = document.         for (loopIndex = 0; loopIndex < menu.length; loopIndex++ )         {             selectControl.options[loopIndex] = new                 Option(menu[loopIndex].firstChild.data);         }     }     function setmenu()     {       document.getElementById('targetDiv').innerHTML =          "You selected " + menu[document.getElementById            ('menuList').selectedIndex].firstChild.data;     } 

What do the two menus look like? The menu1.xml document contains the items ham, turkey, and beef:

 <?xml version = "1.0" ?> <menu>   <menuitem>Ham</menuitem>   <menuitem>Turkey</menuitem>   <menuitem>Beef</menuitem> </menu>

and the menu2.xml document contains tomato, cucumber, and rice:

 <?xml version = "1.0" ?> <menu>   <menuitem>Tomato</menuitem>   <menuitem>Cucumber</menuitem>   <menuitem>Rice</menuitem> </menu>

You can see this new page, testGetXml.html, at work in a browser in Figure 5.3.

image from book
Figure 5.3: Downloading XML using the Ajax Utility Library

When the user clicks the Select menu 1 button, menu 1-ham, turkey, and beef-appears in the drop-down list, as you can see in Figure 5.4.

image from book
Figure 5.4: Downloading menu 1

And when the user clicks the Select menu 2 button, the second menu-tomato, cucumber, and rice-appears in the drop-down list, as shown as Figure 5.5.

image from book
Figure 5.5: Downloading menu 2

As you can see, the Ajax Utility Library can download XML from the server, and pass that XML on to your own code. Of course, you have to know how to handle that XML yourself because it’ll be in JavaScript XML document object form.

One way to make the fetched XML easier to work with is to add auxiliary convenience functions to the Ajax Utility Library. For example, you could add a function named getElements, which would unpack the XML document object, returning an array of the elements you’re looking for. You could pass the name of the elements you’re searching for to the getElements function:

 function getElements(elementName) {     .     .     . }

And that function would use the XML document object’s getElementsByTagName method to search that object and return an array of the requested elements, or null if no such elements were found, like this:

 function getElements(elementName) {   return xmlDocument.getElementsByTagName(elementName); }

You’ve seen how to get text and XML from the server, using the getText and getXml functions. How about posting some data to the server and getting text back?

Post data to the server and get text back

As you know, Ajax applications usually send some data to the server and then get data back. The Ajax Utility Library supports this process with two functions: postDataGetText and postDataGetXml. First, the postDataGetText function: this function lets you post data to the server and get text data back.

Tip 

You don’t need to send data using the POST method. You can also use the Ajax Utility Library’s getText and getXML functions to pass data to the server. You just have to URL-encode that data and append it to the end of the URL used with GET like this: scripter. php?data=Now+is+the_time.

You pass the postDataGetText function the URL you want to access, the data to send to that URL, and the function to call back:

 function postDataGetText(urlToCall, dataToSend, functionToCallBack) {     .     .     . }

As with the other functions in the Ajax Utility Library, postDataGetText starts by creating an XMLHttpRequest object:

 function postDataGetText(urlToCall, dataToSend, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }     .     .     . } 

And the code checks to make sure that the XMLHttpRequest creation process was successful:

 function postDataGetText(urlToCall, dataToSend, functionToCallBack) {   var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     .     .     .   } }

Connecting to the server starts with the XMLHttpRequest object’s open method, where you indicate you’re using the POST method, and configuring the XMLHttpRequest object to connect to the URL passed to the postDataGetText function:

 function postDataGetText(urlToCall, dataToSend, functionToCallBack) {   var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("POST", urlToCall);        .       .       . } 

When you’re using the POST method with Ajax, you also set the Content-Type request header to application/x-www-form-urlencoded, like this:

 function postDataGetText(urlToCall, dataToSend, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("POST", urlToCall);      XMLHttpRequestObject.setRequestHeader('Content-Type',        'application/x-www-form-urlencoded');          .         .         .   } }

Now you’re ready to connect an anonymous inner function to the XMLHttpRequest object’s onreadystatechange property, and wait for the download to occur:

 function postDataGetText(urlToCall, dataToSend, functionToCallBack) {   var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("POST", urlToCall);      XMLHttpRequestObject.setRequestHeader('Content-Type',       'application/x-www-form-urlencoded');     XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {         .         .         .       }      } }

After downloading the data, the postDataGetText function passes it to the callback function you’ve specified, and then deletes the XMLHttpRequest object:

 function postDataGetText(urlToCall, dataToSend, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("POST", urlToCall);      XMLHttpRequestObject.setRequestHeader('Content       'application/x-www-form     XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {           functionToCallBack(XMLHttpRequestObject.responseText);            delete XMLHttpRequestObject;           XMLHttpRequestObject = null;       }      }         .         .         .   } }

Everything’s set up. All you need to do is pass the data to send to the server, and that looks like this:

 function postDataGetText(urlToCall, dataToSend, functionToCallBack) {    var XMLHttpRequestObject = false;          .         .         .     XMLHttpRequestObject.onreadystatechange = function()      {          if (XMLHttpRequestObject.readyState == 4 &&            XMLHttpRequestObject.status == 200) {             functionToCallBack(XMLHttpRequestObject.responseText);              delete XMLHttpRequestObject;             XMLHttpRequestObject = null;         }       }      XMLHttpRequestObject.send(dataToSend);      } }

That completes the postDataGetText function. How about putting it to work?

You can test the postDataGetText function with the testpostDataGetText.html file, which is included in the downloaded files for this chapter. This page simply posts text to a small PHP script, echoer.php, under the parameter message, and that script echoes the text back. Here’s what echoer.php looks like:

 <? echo ($_POST["message"]); ?>

So what does the test page, testpostDataGetText.html, look like? It starts by including the Ajax Utility Library, making the postDataGetText function available to its JavaScript:

 <html>   <head>     <title>Posting data and getting text with the Ajax        Utility library</title>     <script type = "text/javascript" src =        "ajaxutility.js"></script>         .         .         . 

Then it displays a “Get the text” button, connected to the postDataGetText function. The page passes the URL to post data to, echoer.php, as well as the data to send. Because you post data in the parameter=value format, this example posts the data message=Hello from Ajax Utility to echoer.php. And you also pass the name of the callback function that is passed the downloaded data, called display in this case:

 <body>   <h1>Posting data and getting text with the Ajax      Utility library</h1>   <form>     <input type = "button" value = "Get the text"      onclick = "postDataGetText('echoer.php',        'message=Hello from Ajax Utility.', display)">   </form>       .       .       . </body>

When the user clicks the button, the data message=Hello from Ajax Utility is passed to echoer.php, which echoes back Hello from Ajax Utility, and the postDataGetText function passes that text to the callback function display. The display function displays the downloaded text in a <div> element:

 <html>   <head>     <title>Posting data and getting text with the Ajax        Utility library</title>     <script type = "text/javascript" src =        "ajaxutility.js"></script>     <script language = "javascript">       function display(text)       {         document.       }     </script>   </head>

Here’s what it looks like in action. You can see the testpostDataGetText.html page at work in Figure 5.6.

image from book
Figure 5.6: Posting text and getting it back

There’s one more function to add to the Ajax Utility Library-postDataGetXml-which posts data to the server and gets XML back.

Post data to the server and get XML back

Sometimes you may want to post data to the server and get back XML, not text. The Ajax Utility Library is up to the task with the postDataGetXml function. You pass this function the URL to access, the data to post, and the function to call back, like this:

 function postDataGetXml(urlToCall, dataToSend, functionToCallBack) {     .     .     . }

As with the other functions, the code starts by creating an XMLHttpRequest object:

 function postDataGetXml(urlToCall, dataToSend, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }          .          .          . }

If the XMLHttpRequest object was created, the code opens the XMLHttpRequest object, setting the method to POST and configuring that object to connect to the URL passed to the postDataGetXml function:

 function postDataGetXml(urlToCall, dataToSend, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new      ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("POST", urlToCall);      XMLHttpRequestObject.setRequestHeader('Content-Type',        'application/x-www-form-urlencoded');         .         .         .   } } 

Next, you connect an anonymous inner function to the XMLHttpRequest object’s onreadystatechange property:

 function postDataGetXml(urlToCall, dataToSend, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("POST", urlToCall);      XMLHttpRequestObject.setRequestHeader('Content       'application/x-www-form     XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {         .         .         .       }      }   } }

When the XML has been downloaded, the code passes it to the callback function, and then deletes the XMLHttpRequest object:

 function postDataGetXml(urlToCall, dataToSend, functionToCallBack) {    var XMLHttpRequestObject = false;    if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("POST", urlToCall);      XMLHttpRequestObject.setRequestHeader('Content       'application/x-www-form     XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {           functionToCallBack(XMLHttpRequestObject.responseXML);            delete XMLHttpRequestObject;           XMLHttpRequestObject = null;       }      }   } }

All that’s left is to actually send the data to the server, and that looks like this:

 function postDataGetXml(urlToCall, dataToSend, functionToCallBack) {   var XMLHttpRequestObject = false;          .         .         .     XMLHttpRequestObject.onreadystatechange = function()      {        if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {           functionToCallBack(XMLHttpRequestObject.responseXML);            delete XMLHttpRequestObject;           XMLHttpRequestObject = null;       }      }     XMLHttpRequestObject.send(dataToSend);    } } 

This completes the postDataGetXml function. Time to put it to the test in a new page, testPostDataGetText.html, which is included in the downloaded files for this chapter. You might create a test script, menus.php, that you can pass data to and get back the XML you’ve already seen for the two menus. For example, if you pass a parameter named menu set to 1 to menus.php, you’ll get back the first menu:

 <? header("Content-type: text/xml"); if ($_POST["menu"] == "1")   $menuitems = array('Ham', 'Turkey', 'Beef');         .         .         . ?>

If you pass the menu parameter set to 2, you’ll get the second menu:

 <? header("Content-type: text/xml"); if ($_POST["menu"] == "1")   $menuitems = array('Ham', 'Turkey', 'Beef'); if ($_POST["menu"] == "2")   $menuitems = array('Tomato', 'Cucumber', 'Rice');          .          .          . ?>

And all that remains is to store the menu in XML form and pass it back to the browser:

 <? header("Content-type: text/xml"); if ($_POST["menu"] == "1")   $menuitems = array('Ham', 'Turkey', 'Beef'); if ($_POST["menu"] == "2")   $menuitems = array('Tomato', 'Cucumber', 'Rice'); echo '<?xml version="1.0" ?>'; echo '<menu>'; foreach ($menuitems as $value) {   echo '<menuitem>';   echo $value;   echo '</menuitem>'; } echo '</menu>'; ?>

So if you pass menu=1 to menus.php, you get menu 1 back; if you pass menu=2 to menus.php, you get menu 2 back.

All that’s left is to write the Web page, testPostDataGetXml.html, that puts menus.php and postDataGetXml to work. You might start by adding the HTML for the <select> control that displays the menus:

 <form>   <select size="1"      onchange="setmenu()">     <option>Select a menu item</option>   </select>     .     .     . </form>

And you can follow that up with the HTML for the two buttons that let the user select between the menus:

 <form>   <select size="1"      onchange="setmenu()">     <option>Select a menu item</option>   </select>   <br>   <br>   <input type = "button" value = "Select menu 1"     onclick = "postDataGetXml('menus.php', 'menu=1',       getmenu)">   <input type = "button" value = "Select menu 2"     onclick = "postDataGetXml('menus.php', 'menu=2',       getmenu)"> </form>

Note 

These buttons differ in the data you pass to postDataGetXml; one passes menu=1 and the other menu=2, making menus.php return the correct menu.

Finally, you need the <div> element to display the user’s selection from the displayed menu:

 <form>   <select size="1"      onchange="setmenu()">     <option>Select a menu item</option>   </select>   <br>   <br>   <input type = "button" value = "Select menu 1"     onclick = "postDataGetXml('menus.php', 'menu=1',       getmenu)">   <input type = "button" value = "Select menu 2"     onclick = "postDataGetXml('menus.php', 'menu=2',       getmenu)"> </form> <div  width =100 height=100>Your lunch   selection will appear here.</div> 

That’s it for the HTML controls. The Ajax Utility function postDataGetXml does most of the work here, of course, passing the data to the server and getting the XML response; you just use the postDataGetXml function to include ajaxutility.js:

 <html>   <head>     <title>Posting data and getting XML with the Ajax       Utility Library</title>     <script type = "text/javascript" src =       "ajaxutility.js"></script>         .         .         .

The callback function, which is getmenu here, is passed a JavaScript XML document holding the XML from the server:

 <html>   <head>     <title>Posting data and getting XML with the Ajax       Utility Library</title>     <script type = "text/javascript" src =       "ajaxutility.js"></script>     <script language = "javascript">       function getmenu(xmlDocument)       {         .         .         .       }         .         .         .

In getmenu, you can recover the <menuitem> elements, store them in an array named menus, and then call a function named listmenu to handle the work of stocking the <select> control with the menu items:

 <html>   <head>     <title>Posting data and getting XML with the Ajax       Utility Library</title>     <script type = "text/javascript" src =       "ajaxutility.js"></script>     <script language = "javascript">       var menu;       function getmenu(xmlDocument)       {          menu = xmlDocument.getElementsByTagName("menuitem");          listmenu();       }         .         .         . 

The listmenu function stores the menu items in the <select> control this way:

 <html>   <head>     <title>Posting data and getting XML with the Ajax        Utility Library</title>     <script type = "text/javascript" src =        "ajaxutility.js"></script>     <script language = "javascript">       var menu;       function getmenu(xmlDocument)       {          menu = xmlDocument.getElementsByTagName("menuitem");          listmenu();       }       function listmenu ()       {         var loopIndex;         var selectControl = document.getElementById('menuList');         for (loopIndex = 0; loopIndex < menu.length; loopIndex++ )         {             selectControl.options[loopIndex] = new                 Option(menu[loopIndex].firstChild.data);         }     }         .         .         . 

When the user makes a menu selection, the <select> control calls a function named setmenu:

 <html>   <head>     <title>Posting data and getting XML with the Ajax        Utility Library</title>     <script type = "text/javascript" src =        "ajaxutility.js"></script>     <script language = "javascript">         .         .         .     function setmenu()     {       document.getElementById('targetDiv').innerHTML =          "You selected " + menu[document.getElementById            ('menuList').selectedIndex].firstChild.data;     }     </script>   </head> 

You can see testPostDataGetXml.html at work in Figure 5.7.

image from book
Figure 5.7: Posting data and getting XML back

You get menu 1 back from menus.php in XML format by clicking the first button, as shown in Figure 5.8. To get menu 2, click the second button, as shown in Figure 5.9.

image from book
Figure 5.8: Getting menu 1

image from book
Figure 5.9: Getting menu 2

Congratulations! You’ve got the postDataGetXml function working, and with it, the Ajax Utility Library.

As you can see, the Ajax Utility Library is a useful one for working with Ajax. All the Ajax programming is done for you; there’s no need to write it yourself. You’ve only got to select the function you want to use to connect to the server behind the scenes, and the Ajax Utility Library does the rest. Here are the functions to select from:

  • getText(urlToCall, functionToCallBack)

  • getXml(urlToCall, functionToCallBack)

  • postDataGetText(urlToCall, dataToSend, functionToCallBack)

  • postDataGetXml(urlToCall, dataToSend, functionToCallBack)

That’s the idea behind Ajax frameworks: the Ajax code is already written for you, and all you’ve got to do is make the calls to the frameworks’ functions. The Ajax Utility Library is an example of one Ajax framework, and next you’ll see others available for free which you might like better, starting with libXmlRequest.



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net