Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Maureen O'Gara, Nancy Y. Nee, Tad Anderson, Daniel Kaar

Related Topics: ColdFusion, Adobe Flex, AJAX & REA

ColdFusion: Article

ColdFusion and AJAX

All this is done without any screen refreshes. You have to admit that the interface is pretty sweet

One of the most annoying things about the Web page paradigm is that you have to reload the page whenever you want to do something on the server side. If you want to do a site search, it's sprinkled across two pages.

On the first page, the user will enter a search term, then clicks a submit button to get to the second page where the search results are returned. If the user wants to filter or sort the search results it's usually refreshed again and each result is redisplayed in its filtered state.

Lately there's been a movement to help improve the Web by eliminating these constant page refreshes. Macromedia's Rich Internet Application (RIA) push with Flash and Flex has been at the forefront of this effort, however Flex' entry price has made it prohibitive for many ColdFusion Developers. That's where AJAX comes in. It's an alternate way to create a RIA and relies on technologies built into most browsers, making it completely free.

Dissecting AJAX
AJAX stands for Asynchronous JavaScript and XML. It's not a single technology, but rather a combination of different technologies that are used to create a Rich Internet Application feel. You've probably seen examples of this kind of application. Google uses AJAX a lot on such services as maps.google.com. After bringing up a location, you can click and drag the map, zoom in or out, or even bring up directions to and from the location. All this is done without any screen refreshes. You have to admit that the interface is pretty sweet. (Note: Yahoo has a similar mapping application, built entirely in Flex at http://maps.yahoo.com/beta.)

Since AJAX is a combination of technologies you're going to want to know what you're getting into before going any farther, right? I thought so. Here's the list:

  • XHTML: To start with you need a display language. Most resources on AJAX say you have to use XHTML, but regular HTML will work too.
  • XMLHttpRequest: The XMLHttpRequest object lets you retrieve data from the server without refreshing the page. It's a JavaScript object implemented in most major browsers. As the XMLHttpRequest object is being called, the user can do other things on the page. This is where the "asynchronous" part of the acronym comes in.
  • iFrames: iFrames are in-line frames and are sometimes used as an alternative to the XMLHttpRequest object. A regular frame will divide the browser window into multiple separate pages, but an in-line frame embeds one page inside another. I won't get into any iFrames details in this article.
  • XML: You all know what XML is, right? As a refresher, it's a way to describe data. If you need more details, read the article in this column from August 05 at http://coldfusion.sys-con.com/read/117667.htm.
  • Document Object Model: The document object model defines your HTML page through a programmer API.
  • JavaScript: I'm sure you all know what JavaScript is too. It's the most common language used for providing client-side functionality to HTML pages.
How do all these different technologies work together using AJAX? Well, it generally works something like this:
  1. First, the user comes to your page and the page loads. Something (depending on what your page does) is loaded and displayed to the user.
  2. The user does something such as clicking a link. Instead of reloading the page (as would happen in a normal Web app), that link fires off a JavaScript function.
  3. The JavaScript function uses XMLHttpRequest object to retrieve XML data from the server.
  4. Then the JavaScript parses the XML Data and through the Document Object Model will change the page without a refresh.
So the user gets to see more data quicker without the annoying page refreshes. That's fantastic, right? Why isn't everyone using this? Well, as with all things, AJAX isn't perfect. There are drawbacks:
  • Development Time: Working with AJAX will bring you back to the old days of Web development, especially if you want any kind of cross-compatibility. There are different syntaxes for creating the XMLHttpRequest object in IE vs Netscape/Firefox, which can lead to extended development times.
  • User Experience: When used properly, an AJAX can enhance the user experience. However, when used improperly it can make it horrendous. Since the page isn't reloading, what happens when the user hits the back button? He'll leave the application altogether. I bet he expected to go to the app's "previous state." What happens when the user bookmarks a page? He'll go the "initial" state of the app. There are workarounds, of course, but they're not trivial to implement.
  • Searches: The single-page nature of the app makes indexing by search engines a tetchy proposition at best.
  • Response Times: The very thing that works for you (no page reloads) can also work against you. What happens if you're retrieving a lot of data from the server? And the user is given no indication that something is happening.
  • JavaScript: JavaScript must be enabled for an AJAX app to work. If JavaScript is disabled, your user isn't going to have a lot of fun with an AJAX app.
  • Accessibility: AJAX is, most likely, not going to meet accessibility guidelines. If this is a goal of your project you're going to have to provide a fallback option. That means developing two paths to the same goal.
There are a few real simple examples of AJAX that you've probably used or seen that existed long before the term AJAX was conceived. Have you ever rolled your mouse over a graphic navigation button only to have that graphic change? JavaScript rollovers can be considered a precursor to AJAX. They do use JavaScript and they do change the state of the page. Have you turned on or off a DHTML layer on a page based on some selection by the user? This is another example of AJAX. If an application has a select box with an "other" option in it I'll often use DHTML to display an input text box if "other" is selected. If other isn't selected the input box is hidden. Both of these are simple examples of changing the page without a screen refresh. They don't go out to the server to get data, but they still fit the RIA paradigm.

Putting This All Together
Let me show you how this all comes together, so you can actually do something useful. The first step in the process is to initialize the XMLHttpRequest object. Unfortunately, there's not consistent way to do this across browsers:

<script language="javascript" type="text/javascript">
var request = false;
try {
    request = new XMLHttpRequest();
}
catch (trymicrosoft) {
   try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
   }
   catch (othermicrosoft) {
   try {
    request = new ActiveXObject("Microsoft.XMLHTTP");
   }
   catch (failed) {
    request = false;
    }
   }
}
</script>

The first line initializes the request variable, giving it a Boolean value of false. You can check against this later to make sure that your request object was properly initialized. The next code creates an instance of the XMLHttpRequest object using 'new XMLHttpRequest.' This works fine for most non-Microsoft browsers, but won't work in IE. If it doesn't initialize, then an error is thrown, which is where the first catch statement comes into play. It attempts to re-initialize using the method available in the current version of Internet Explorer: new ActiveXObject("Msxml2.XMLHTTP").

If that fails, it tries the version from older versions of Internet Explorer new ActiveXObject("Microsoft.XMLHTTP"). That's kind of complicated right? I borrowed this initialization code from the article www-128.ibm.com/developerworks/Web/library/wa-ajaxintro2/?ca=dgr-lnxw07AJAX-Request (which you should all read because it goes into a lot more details about error checking that are outside the scope of this article).

So, now the code has created the object, but what can you do with it? As you can probably see, it doesn't do much yet. You want to assign it a URL, load the data, and then process the data in some way. This function will do that:

function getRSS() {
    var url = "/htdocs/jeffhousercom/wwwroot/rss.cfm";
    request.open("GET", url, true);
    request.onreadystatechange = updatePage;
    request.send(null);
}

This is function to grab an RSS feed. The first line defines the URL. This is standard JavaScript for defining a variable. You should bear in mind that you can only request URLs from the current Web site. In this case, I'm grabbing a RSS feed from a local copy of my blog. The next line calls a method on the request object entitled open. Open prepares the request to be sent, but doesn't actual send it. There are five arguments to the open function (although we only use three in this example):

  • Request-type: This specifies the request type, either get or post, for the URL that you want to send.
  • url: The URL specifies the URL that you're getting (or posting) to.
  • Asynchronous: The async value is a Boolean value that specifies whether this request is asynchronous or not. For AJAX use, you'll want to specify true. If set to false, the application will hold until this request is finished, which defeats the purpose of an RIA in the first place.
  • username: The username specifies the username required for accessing the URL, if applicable.
  • password: The username specifies the username required for accessing the URL, if applicable.
Okay, you've set up the request to be ready to send. The next line specifies the onreadystatechange property. This property specifies what function to call once the request is complete. If you don't specify a method to be called then nothing will happen once the request is complete. The final line calls the send method. The send method is the one that will execute the request. Its parameter is the data that you need to send along with the request. In our example, we aren't sending parameters, so we pass a null value.

Once the request complete, the updatePage function will execute, so lets look at that next:

function updatePage() {
   if (request.readyState == 4){
     Form1.XMLValues.value = request.responseText;
   }
}

This function first checks the readyState of the XMLHttpRequest object. Exploring that is beyond the scope of this article, but there are a lot more details in some of the references provided at the end. For now, all you need to know is that if the readyState is 4, then the request is complete. This takes the resulting value from the server response and assigns it to a form textbox. The form is below:

<form name="Form1">
    <textarea name="XMLValues" rows="20" cols="50"></textarea>
</form>

The text box will contain the XML from the RSS feed. There's another property associated with the XMLHttpRequest object called responseXML. This will contain the results as an XML Document object, which JavaScript can access natively. Unfortunately specific details are beyond the scope of this article, but I found this good resource to get you started on that: http://www.peachpit.com/articles/article.asp?p=29307&seqNum=4&rl=1 .

Where to Go from Here
If you want to learn more about AJAX, there are some great resources you can read. The article by Jesse James Garrett that started it all is at www.adaptivepath.com/publications/essays/archives/000385.php. Garrett is credited with coining the term AJAX. You can follow an AJAX blog at www.ajax-powered.net, which talks about all things AJAX. Finally, there are a few people who are working on ways to integrate ColdFusion and AJAX together. One is the CFAJAX project www.indiankey.com/cfajax. Another is the AJAXCFC project at www.robgonda.com/blog/projects/ajaxcfc.

More Stories By Jeffry Houser

Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.

Comments (5) View Comments

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.


Most Recent Comments
walweb 10/30/06 02:37:09 AM EST

Nice example of a web2.0 application using Googlemaps API is PICSFROMSPACE, LOOKUP YOUR PLACE BY ADDRESS. Showing satellitepictures at streetlevel by address or zipcode.
Check out http://www.walweb.nl/picsfromspace

SEO/SEM Journal News Desk 10/29/06 02:12:13 PM EST

AJAX stands for Asynchronous JavaScript and XML. It's not a single technology, but rather a combination of different technologies that are used to create a Rich Internet Application feel. You've probably seen examples of this kind of application. Google uses AJAX a lot on such services as maps.google.com. After bringing up a location, you can click and drag the map, zoom in or out, or even bring up directions to and from the location. All this is done without any screen refreshes. You have to admit that the interface is pretty sweet. (Note: Yahoo has a similar mapping application, built entirely in Flex at http://maps.yahoo.com/beta.)

CFDJ News Desk 10/29/06 01:58:22 PM EST

AJAX stands for Asynchronous JavaScript and XML. It's not a single technology, but rather a combination of different technologies that are used to create a Rich Internet Application feel. You've probably seen examples of this kind of application. Google uses AJAX a lot on such services as maps.google.com. After bringing up a location, you can click and drag the map, zoom in or out, or even bring up directions to and from the location. All this is done without any screen refreshes. You have to admit that the interface is pretty sweet. (Note: Yahoo has a similar mapping application, built entirely in Flex at http://maps.yahoo.com/beta.)

CFDJ News Desk 10/29/06 01:15:39 PM EST

AJAX stands for Asynchronous JavaScript and XML. It's not a single technology, but rather a combination of different technologies that are used to create a Rich Internet Application feel. You've probably seen examples of this kind of application. Google uses AJAX a lot on such services as maps.google.com. After bringing up a location, you can click and drag the map, zoom in or out, or even bring up directions to and from the location. All this is done without any screen refreshes. You have to admit that the interface is pretty sweet. (Note: Yahoo has a similar mapping application, built entirely in Flex at http://maps.yahoo.com/beta.)

Dan Novik 10/17/06 07:46:05 AM EDT

a lot of Ajax components are part of Coldtags suite: http://www.servletsuite.com/jsp.htm#ajax

@ThingsExpo Stories
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nigeria has the largest economy in Africa, at more than US$500 billion, and ranks 23rd in the world. A recent re-evaluation of Nigeria's true economic size doubled the previous estimate, and brought it well ahead of South Africa, which is a member (unlike Nigeria) of the G20 club for political as well as economic reasons. Nigeria's economy can be said to be quite diverse from one point of view, but heavily dependent on oil and gas at the same time. Oil and natural gas account for about 15% of Nigera's overall economy, but traditionally represent more than 90% of the country's exports and as...
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
"At our booth we are showing how to provide trust in the Internet of Things. Trust is where everything starts to become secure and trustworthy. Now with the scaling of the Internet of Things it becomes an interesting question – I've heard numbers from 200 billion devices next year up to a trillion in the next 10 to 15 years," explained Johannes Lintzen, Vice President of Sales at Utimaco, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
"For over 25 years we have been working with a lot of enterprise customers and we have seen how companies create applications. And now that we have moved to cloud computing, mobile, social and the Internet of Things, we see that the market needs a new way of creating applications," stated Jesse Shiah, CEO, President and Co-Founder of AgilePoint Inc., in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
Code Halos - aka "digital fingerprints" - are the key organizing principle to understand a) how dumb things become smart and b) how to monetize this dynamic. In his session at @ThingsExpo, Robert Brown, AVP, Center for the Future of Work at Cognizant Technology Solutions, outlined research, analysis and recommendations from his recently published book on this phenomena on the way leading edge organizations like GE and Disney are unlocking the Internet of Things opportunity and what steps your organization should be taking to position itself for the next platform of digital competition.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at @ThingsExpo, Andrew Bolwell, Director of Innovation for HP's Printing and Personal Systems Group, discussed how key attributes of mobile technology – touch input, sensors, social, and ...