TechTip: Access XML Web Services with JavaScript

Scripting
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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.

Mike Faust

Mike Faust is a senior consultant/analyst for Retail Technologies Corporation in Orlando, Florida. Mike is also the author of the books Active Server Pages Primer, The iSeries and AS/400 Programmer's Guide to Cool Things, JavaScript for the Business Developer, and SQL Built-in Functions and Stored Procedures. You can contact Mike at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Mike Faust available now on the MC Press Bookstore.

Active Server Pages Primer Active Server Pages Primer
Learn how to make the most of ASP while creating a fully functional ASP "shopping cart" application.
List Price $79.00

Now On Sale

JavaScript for the Business Developer JavaScript for the Business Developer
Learn how JavaScript can help you create dynamic business applications with Web browser interfaces.
List Price $44.95

Now On Sale

SQL Built-in Functions and Stored Procedures SQL Built-in Functions and Stored Procedures
Unleash the full power of SQL with these highly useful tools.
List Price $49.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  •  

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: