Welcome!

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
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
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.
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, 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...

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

An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
"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.
Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
The 3rd International @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 it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.