In the previous TechTip, you learned that the key to AJAX is an XMLHttpRequest object. To connect to a remote document using the XMLHttpRequest object, you need to follow a simple series of steps. The first step is to define the XMLHttpRequest object itself. Since Internet Explorer uses a different method of defining this object than other browsers do, your script needs to prepare for this. The statements below show how:
if (!ActiveXObject) {
xmlHttp = new XMLHttpRequest;
}
else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
In this example, you check for the existence of the ActiveXObject object. If that object does not exist, the document is being displayed on a browser other than Internet Explorer. In that case, the object is defined using the XMLHttpRequest object. Otherwise, it's defined using the ActiveXObject("Microsoft.XMLHTTP") object.
Now that the object has been defined, you need to identify how to use this object to connect to your target document. The code below illustrates how to accomplish this:
xmlHttp.open("GET","http://some.webservice.site/document.xml",
true);
xmlHttp.send();
As this example shows, you use the open() method to define how to connect to the Web server; this example uses "GET" along with the URL of the document to be read and the final value indicating that this connection should be made asynchronously, which means that once the send() method is executed, execution of the script will continue without waiting for data to be returned. Then, the send() method sends the request defined on the open() method.
Once the connection has been made, you need to associate a JavaScript function with the onreadystatechange event. This function can be either an embedded function or a user-defined function name. The example below illustrates both methods.
xmlHttp.onreadystatechange = stateHandler(xmlHttp);
// Defining event handler using an internal function definition
xmlHttp.onreadystatechange = function(xmlHttp) {
alert(xmlHttp.readyState);
}
The first example is fairly cut-and-dried. It simply assigns the onreadystatechange event to the function named stateHandler(). The second example uses a technique whereby the function itself is embedded into the assignment statement. Note that the xmlHttp object is passed as a parameter to each function. Since the onreadystatechange() function is called each time the ready state changes, the application needs to ensure that the code to be performed is executed only if and when the proper state is reached. You can do this by conditioning the code to be executed as shown below:
if (xmlHttp.status == 200) {
// Code to be executed once an XML document is opened.
}
}
This example compares the readyState to 4, which indicates the connection has been made. It also compares the returned status value to 200, indicating that the connection was made successfully.
Once you have a successful connection, you need a way to get the data returned. The first step in this process is to assign a variable to the responseXML property on the XMLHttpRequest object, as shown here:
Once that association has been built, the variable xmldoc automatically becomes a type XMLDocument. This type allows us to traverse the entire structure of the returned document.
Next, you gain access to individual elements within the returned document based on their tag names. This is accomplished using the getElementsByTagName() method. This method returns a collection of elements. You can read through this collection using the item() collection. To read the actual data stored in the element, use the firstChild.data property. Below is an example of reading through each element of the collection and writing out the results.
for (var x = 0; x < myData.length; x++) {
document.write(myData.item(x).firstChild.data);
}
In this example, you assign the variable myData to the collection associated with the XML tag named "data." The length property is used to determine the upper boundary for a for loop to read through all of the items in this collection. You then use the firstChild.data property to display the values out to the browser. You can also traverse the tree structure using the childNodes() collection. This simple process gives you all the tools you need to access XML data via AJAX.
Now that you understand the concept, let's look at a working example of using AJAX.
Using AJAX to Read Currency Exchange Rates
A discussion of AJAX wouldn't be complete without a working example that helps to fully illustrate the usefulness of this functionality. Figure 1 contains the source for an HTML page that utilizes AJAX to retrieve the noontime currency exchange rate for a given currency code from the Federal Reserve Bank of New York Web service.
|
Figure 1: This sample consumes the Federal Reserve Bank exchange rate information.
This simple yet powerful example uses a text input box to accept the three-character currency code based on the ISO 4217 currency code list. Figure 2 shows the Web page presented to a user.
Figure 2: This Web page allows a user to obtain exchange rate data. (Click images to enlarge.)
When a user clicks on the Get Conversion Rate button, the page launches the getConversionRate() user-defined JavaScript function. This function passes the value of the currency code input text box to the foreign exchange rates Web service via the Microsoft.XMLHTTP ActiveX object. The resulting XML data contains the actual exchange rate along with a text string containing a description of the currency code provided. The resulting data is returned to the browser via the alert() JavaScript method. Figure 3 illustrates the resulting pop-up box.
Figure 3: XML data returned by the Web service is passed back to the user.
This example simply displays the value to the user; however, you could easily use the exchange rate returned to convert values within a shopping-cart application to/from a desired currency. The key to remember is that all of this is done "client side" prior to sending any data back to the Web server.
AJAX: It's Not Just for Cleaning Anymore
As I hope I've helped to illustrate in this TechTip, when you combine AJAX with XML Web services, you can create truly powerful applications simply using JavaScript. For more information on utilizing JavaScript for business applications, check out the book JavaScript for the Business Developer, new from MC Press.
LATEST COMMENTS
MC Press Online