Welcome!

Open Source Cloud Authors: Elizabeth White, Carmen Gonzalez, Liz McMillan, Zakia Bouachraoui, William Schmarzo

Related Topics: Open Source Cloud, Machine Learning

Open Source Cloud: Article

Cross-Browser Client-Side AJAX

Other than using the XMLHTTP request object, how does one go about writing an AJAX application?

I'd like to take a moment before continuing to point out the onreadystatechange property. It's there that we provide a handler for when the XMLHTTP request object's readystate changes. Or, in other words, the server did something. The possible server responses, along with their meanings are described in Table 2.

The onreadystatechange property and ready states are only used for asynchronous requests. Since we're busy people and this is supposed to be an article about AJAX we'll concentrate on the asynchronous request as opposed to a synchronous request. The required code is shown in Listing 1 with the results in Figure 1.

Just in case you were wondering, there are only two differences between an asynchronous request and a synchronous request. The first is that the true is false. And the second is that an onreadystatechange event handler isn't needed. The browser will wait for the server's response.

All right, for argument's sake let's say that the onreadystatechange event handler has the server's response and that that the ready state is complete. It doesn't mean that we're done, yes, the information is on the browser, but unless the user has some kind of weird mutant power enabling him to see the invisible, the information isn't in a very useful format. Sitting in an object hidden from view, yeah, that's helpful. Fortunately there are, however, a number of options available that can make the information a wee bit more user friendly.

However, before displaying anything on the browser it might be a good idea to make sure it's what we're expecting. After all, it's within the realm of possibility that we don't get a good response like this one:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
     <getItemsResponse xmlns="http://tempuri.org/">
       <getItemsResult>xml</getItemsResult>
     </getItemsResponse>
    </soap:Body>
   </soap:Envelope>

We could, in fact, get a SOAP fault like this:

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
     <soap:Fault>
       <faultcode>soap:MustUnderstand</faultcode>
       <faultstring>Mandatory Header error.</faultstring>
       <faultactor>http://localhost/AJAX4/chapter4.asmx</faultactor>
<detail>Web Service coffee break.</detail>
     </soap:Fault>
    </soap:Body>
   </soap:Envelope>

Again for argument's sake let's assume that the response was successful, because handling a SOAP fault actually depends on what we were attempting to accomplish in the first place. With AJAX it's kind of traditional when handling a successful response from the server to show something on the user's browser, so that's what we'll do. Which leads me to the question how?

Well, first it's necessary to extract the part of the XMLHTTP request object's response that we're interested it. While there are several ways to do this extraction ranging from applying a regular expression to the text response to selecting individual nodes from the XML response, I'll use the XML response. Hey, why not, the "X" in AJAX stands for XML, might as well use it, and leave the text response for debugging with alerts.

If you haven't noticed yet, when creating an AJAX application from scratch there always seems to be just one more thing to do. In this case it's display the results in the Web browser, which depending on the result can be done in several ways. For instance, the innerHTML property is a real good possibility. Basically it would look something like this:

document.getElementById('tagid').innerHTML = whatever;

Another possibility is to display the results using the HTML Document Object Model's appendChild method like this:

document.getElementById('tagid').appendChild(whatever);

Just in case you're wondering, whatever is in the examples above, it's essentially whatever you'd like it to be. It could be text, as in the value of a particular XML node, or it could be XHTML that was created on the server. I've even seen the XMLHTTP request object's responseText property used so that regular, not well formed, HTML could be used. While this might sound odd it's a good way to get a little extra mileage out of existing applications.

However, I'm personally fond of living dangerously. Yes, I'm one of those developers who's been accused of dabbling in the dark arts by some other developers; yes, I use XSLT on the client. Before running off to hide from the scary man, let me explain that if a Web browser supports the XML the odds are close to 100% that it also supports XSLT. Interested?

AJAX and the Dark Arts
Good, but I should warn you that certain things are easier in one browser than the other. For example, creating an XSLT processor is one step in Firefox, while it's multi-step in Internet Explorer; basically anything to do with XML is different from browser to browser. One of these differences is something called XML data islands, introduced in Internet Explorer 5.0, it's a way of embedding XML in the body of an HTML document. I've decided to use this technique as well as demonstrate that the XMLHTTP request object can be used without SOAP to 'GET' a file directly from the Web server. The end result of this endeavor is shown in Listing 2 and Figure 2, look it over and I'll be right here to explain some oddities.

I'd like to point out several things about Listing 2. First, the Cascading Style Sheet, whose sole purpose it to insure that the XML data island doesn't display in the browser. Another item is how the serialization and de-serialization of XML is handled by the individual Web browsers. Working around these differences is often enough to push one over the edge, but once the code exists it's merely a matter of cloning it as often as needed. Although, being a lazy, er, efficient type, I usually create JavaScript classes for this kind of thing. (see Figure 3)

Conclusion
What I've shown here is just a taste of some of the power and problems that one encounters when developing an AJAX application. And while developing the first application is often time-consuming, once these techniques have been mastered subsequent applications come a lot easier than the first. Yes, hard work is its own reward, although having a hot buzzword on the resume is good. Come to think of it the paycheck is nice too.

More Stories By Edmond Woychowsky

Edmond Woychowsky is the author of Prentice Hall's AJAX: Creating Web Pages with Asynchronous JavaScript and XML (to publish August 2006). A graduate of Middlesex Country College and Penn State, Edmond Woychowsky began his professional life at Bell Labs as a dinosaur writing recursive assembly language programs for use in their DOSS order entry system. Throughout his career Ed has worked in the banking, insurance, pharmaceutical and manufacturing industries slowly sprouting feathers and evolving into a web developer. Best known for his often unique articles on the TechRepublic web site as well as his ability to explain how Muenchian grouping works in small words. Currently he can be found working in New Jersey as a consultant, applying both AJAX and XSLT to problems in often bizarre ways and looking forward to his next meal.

Comments (10)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...