Using AJAX with ColdFusion Part I

 
Mar 20, 2006
by James Holmes

Asynchronous JavaScript and XML (AJAX) is a name for the technique in which the JavaScript XMLHTTPRequest Object is used to exchange data asynchronously with a server. In a standard web application, each time data is to be sent to or retrieved from the server, a get (e.g. clicking a URL link) or post (e.g. submitting a form) is necessary, resulting in a complete page refresh. In an AJAX application, no refresh occurs; a JavaScript event triggers an XMLHTTPRequest call and the returning function performs further actions when the data comes back. This can lead to a far more functional user interface in the client browser.

Various uses of AJAX can be made, from simply parsing and presenting an RSS feed, to full interaction with the server on which the web application is situated. The latter employment of the technique is featured in popular web applications such as Google's GMail. In GMail, the entire user interface is based on retrieving information (such as a list of messages in a thread or the full text of a single message) from the Google servers with a single click on a text link, without a page refresh slowing down the operation. The user interface is greatly enhanced in comparison to any that could be achieved with a standard form submission model.

Thus, for a ColdFusion developer, the most important use of AJAX in a web application is to call ColdFusion code on the web application's own server and get a result that can be used in the browser. AJAX allows the result of any ColdFusion function (or method) to be employed client side without refreshing the page.

Basic Client/Server Requirements for AJAX Applications, Regardless of Implementation:

All AJAX apps need:

Server:
  • A server platform that can handle the parsing of data into and out of the data exchange format used (ColdFusion fits the bill);

Client
  • Javascript enabled;
  • The XMLHTTPRequest Object in some form (actually there are techniques that enable similar, albeit limited, functionality without this object).

XML and Other Transports

While the name implies that XML must be used, this really isn't the case. Other data interchange formats such as JSON, native JavaScript and even raw HTML can be used where appropriate.

XML formats:
  • SOAP -- JavaScript can be used to consume SOAP-based webservices, thus leveraging existing CFCs
  • WDDX -- An XML format built into ColdFusion
  • YODEL -- A new XML format, for which ColdFusion and JavaScript parsers are available
  • XML-RPC -- An XML format

Other
  • JSON (JavaScript Object Notation) - A format that evaluates directly into JavaScript that can be used for any data exchange operations
  • JavaScript - Raw JavaScript can be used to exchange data, usually from the server to the client

Available Implementations and Libraries

A number of libraries and frameworks are available that will prevent the ColdFusion developer from reinventing the wheel:

Data Exchange Parsers:

A CFAJAX Example

A common requirement of web applications is the dependency of form select inputs on other form select inputs. For this example, let's assume the selections are in a database and therefore a CF query is going to populate them one way or another.

Before AJAX, there were a couple of options:

  1. Show a multi-screen form, where each menu selection is submitted and a new menu is shown based on that result. While only small amounts of information are transmitted and received at one time, the process is tedious for the user and requires multiple form handlers at the server end.
  2. Use JavaScript to load all the possible menus with the page, swapping out the second menu selections based on the first ones. While the server now only has to deal with one final form submission, the user's browser has to download multiple select menus as part of the JavaScript code, and many of these will not be needed.

AJAX allows us to modify the second choice so that only the selected menu is downloaded, giving us the benefits of both choices (low bandwidth and only a single form submission at the end of the process).

The code to achieve this in CFAJAX would look something like this (omitting the links to the include files that come with CFAJAX, as they depend on the developer's configuration):

Listing 1: The CF code
<cffunction name="GetMenu" output="false" returntype="query" hint="Returns a query of the submenu items based on the parent menu ID">
<cfargument name="ParentID" required="yes" type="numeric" hint="The parent ID of the items to return">
<cfset var QGetMenu="">
<cfquery datasource="SomeDSN" name="QGetMenu">
SELECT optiontext, optionvalue
FROM MenuOptions
WHERE parentid =<cfqueryparam cfsqltype="cf_sql_numeric" value="#ARGUMENTS.ParentID#">
</cfquery>
<cfreturn QGetMenu>
</cffunction>

Listing 2: The client code:
<script language="javascript" type="text/javascript">
function getOptions(parentId){
/*
This executes the CF function GetMenu(parentId)
and executes the JS function showNewOptions(result) when it returns.
It'a Asynchronous, so getOptions() doesn't wait for anything.
*/
DWREngine._execute(_cfscriptLocation_Assignments, null, 'GetMenu', parentId, showNewOptions);
}

function showNewOptions(result){
/*
result is the CFAJAX return from the query.
In this case we get a CF query that's been
turned into a JS Array of Objects.
*/
//first, clear out the existing options
var mySelect = document.getElementById('someSelectInput');
mySelect.options.length = 0;
//now populate the new options
for (var i=0; i < result.length; i++ ) {
mySelect.options[i] = new Option(result[i].OPTIONTEXT,result[i].OPTIONVALUE);
}
}
}

?.. form, etc ?.


<!--- this is the primary select, which controls the other one --->
<select name="mainSelect" id="mainSelect" onchange="getOptions(this.value);">
<option value="1">Option One</option>
<option value="2">Option two</option>
</select>

<!--- this is the secondary select, which is changed by the AJAX code --->
<select name="someSelectInput" id="someSelectInput">
</select>

CFAJAX, in fact, has utilities that simplify filling in a select list, but seeing the full workings of the JavaScript is of benefit when more complicated actions need to be performed.

Online Examples

A number of ColdFusion applications are now employing AJAX to great effect. For example:

Looking at these applications and others on the Web will undoubtedly give you ideas regarding the user interface in some of your existing applications. If you have ever looked at the screen and thought, "It would be great if it just did this," then now is the time to see if AJAX can provide that functionality.

In Part II of this article, I will take the AJAX example I've provided in this part and examine it more closely.
James Holmes is the lead web applications developer for one Division of an Australian University, working with ColdFusion and Oracle on Solaris. He has been employing CFAJAX to speed the workflow and enhance the user interface of their web apps. He maintains a blog at http://jr-holmes.coldfusionjournal.com/, and contributes to the CFAJAX wiki (www.indiankey.com/cfajax/wiki).

Privacy | FAQ | Site Map | About | Guidelines | Contact | Advertising | What is ColdFusion?
House of Fusion | ColdFusion Jobs | Blog of Fusion | AHP Hosting