25
Wed, Dec
0 New Articles

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.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • 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.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • 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

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • 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: