TechTip: Access XML Web Services with JavaScript PDF Print E-mail
Tips & Techniques - Scripting
Written by Mike Faust   
Thursday, 25 October 2007

Try this practical, working example to see how you can combine AJAX with XML Web services to create truly powerful applications using JavaScript.

In a previous TechTip, I introduced you to the JavaScript objects used to access XML Web services via Asynchronous JavaScript and XML (AJAX). This time, I'll expand on what I covered last time and show you a working sample of a Web page.

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.

// Defining event handler using a user-defined function
   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.readyState ==4) {
     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:

var xmldoc = xmlHttp.responseXML;

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.

var myData = xmldoc.getElementsByTagName("datatag");

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.

<html>
<head>
<title>AJAX Currency Conversion</title>
<script language="JavaScript">
   var xmlHttp, rateString

     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

function getConversionRate() {
   var currCode = document.all("currCode").value;

   xmlHttp.open("GET", 

"http://www.newyorkfed.org/markets/fxrates/WebService/v1_0/FXWS.cfc?

method=getLatestNoonRate&currency_code=" +
                     currCode, false);


   xmlHttp.send();

   var XMLDoc = new ActiveXObject("Microsoft.XMLDOM");
   XMLDoc.setProperty("SelectionLanguage", "XPath");
   XMLDoc.setProperty("SelectionNamespaces", 

"xmlns:frbny='http://www.newyorkfed.org/xml/schemas/FX/utility'");
   XMLDoc.loadXML(xmlHttp.responseText);

   if (!XMLDoc.documentElement) {
   return "Currency Code Entered Invalid or Not Supported.";
   }
   else {
   var xString = XMLDoc.documentElement.text;
   XMLDoc.loadXML(xString);

      var retRate = 

XMLDoc.documentElement.getElementsByTagName

("Name").item(0).firstChild.data + ' is ' + 

XMLDoc.documentElement.getElementsByTagName("frbny:OBS_VALUE").item(0).

firstChild.data;
      return retRate;
   }
}

</script>
</head>
<body><p align="CENTER">
<input type="text" name="currCode" maxlength=3 style="width:75px">
<input  type="button" value="Get Conversion Rate" 

onClick="alert(getConversionRate());">
<table><tr><td id="Rate"></td></tr></table>
</p>
</body>
</html> 

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.

http://www.mcpressonline.com/articles/images/2002/AJAXTechTip2V3--10260700.png

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.

http://www.mcpressonline.com/articles/images/2002/AJAXTechTip2V3--10260701.png

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.

 
Discuss (4 posts)
Guest.Visitor
TechTip: Access XML Web Services with JavaScript
Oct 30 2007 17:50:00
Mike. Good article. <p>Should you use a more recent version of the XML HTTP Request object? They are faster than older versions, probably have bugs worked out too. <p>Example: <a href="http://www.wrox.com/WileyCDA/Section/id-291289.html">http://www.wrox.com/WileyCDA/Section/id-291289.html</a> <p>And a browser might cache an AJAX request with the GET method (heck, POST might be cached too technically) so you might want to stick a unique query string onto the end of the URL every time like this: <p>var noCacheDate = new Date(); <br>
var url = "http://www.somewhere.com?time=" + noCacheDate.getTime(); <p>Chris
#115918
Guest.Visitor
TechTip: Access XML Web Services with JavaScript
Oct 30 2007 11:49:00
Good Catch. The odd part is that it doesn't cause an issue on IE6, which is why the example shown worked for generating the screenshots.
#115917
g11021
TechTip: Access XML Web Services with JavaScript
Oct 26 2007 06:10:00
There is missing a semicolon at the end of the first line in the script <BR>
- var xmlHttp, rateString <p>Regards Jørn
#115916
MC Press Web Site Staff
TechTip: Access XML Web Services with JavaScript
Oct 30 2007 17:52:00
This is a discussion about <B>TechTip: Access XML Web Services with JavaScript</b>.<p align='center'><a href=http://www.mcpressonline.com/mc?1@232.1KNKfHX1eQT.17@.6b50a898>Click here for the article</a>.</p>
#115915


Discuss...
User Rating: / 0
PoorBest 

Mike Faust
About the Author:
Mike Faust is the Manager, Systems Development for BrightHouse Networks in Maitland, Florida. Mike is also the author of the books The iSeries and AS/400 Programmer's Guide to Cool Things, Active Server Pages Primer, SQL Built-in Functions and Stored Procedures, and JavaScript for the Business Developer. You can contact Mike at This e-mail address is being protected from spam bots, you need JavaScript enabled to view it .
Read More >>
Related Articles
Next >
   MC-STORE.COM