Digital Edition

SYS-CON.TV
Rob Gonda's Two-Part AJAX Special: Now In One Part
By Popular Demand, We Bring You This Resource Article In One URL

It's become very popular lately, even though it's not exactly new. It's been possible to use the concept behind AJAX since browsers introduced the XMLHttpRequest function in 1999.

AJAX isn't a technology, or a language, and there's no recipe to implement it; it's just a combination of various components to achieve something you otherwise couldn't: asynchronous http requests. However, since early 2005, when Google and Flickr popularized the concept, its use has grown rapidly.

The name AJAX is short for Asynchronous JavaScript and XML. It uses the JavaScript XMLHttpRequest function to create a tunnel from the client's browser to the server and transmit information back and forth without having to refresh the page. The data travels in XML format because it transmits complex data types over clear text.

AJAX uses XHTML for the data presentation of the view layer, DOM, short for Document Object Model, which dynamically manipulates the presentation, XML for data exchange, and XMLHttpRequest as the exchange engine that ties everything together.

Because of these requirements, AJAX works on I.E. 5.0+, Mozilla 1.0+, Firefox 1.0+, Netscape 7.0+, and Apple added it to Safari 1.2+.

Traditional HTML sends a request to the server, which processes it and either returns a static HTML page or dispatches the request to some scripting language such as ColdFusion, which creates and returns an HTML page for the browser to render. When this method has to retrieve new data from the server it has to repost and reload another HTML file. In many cases perhaps only a small portion of the returned HTML code varies and the shell itself remains the same resulting in huge overhead because the data has to be downloaded every time.

Some classic examples of applications that would benefit from AJAX are searching for information and displaying it back in a table, related select dropdowns, or checking if a user exists before submitting an entire form.

As we can see, AJAX offers many advantages over traditional HTML applications, but we shouldn't overestimate it. Because the data is JavaScript-driven, one of the main drawbacks is that search engines won't index any of the dynamically generated content. It's definitely not SEO-friendly.

People familiar with MVC will have a better grasp of the concept. Though details of MVC are outside of the scope of this article, the three defined components are Model, View, and Controller. The controller mediates between the data model and the view. It responds to events, which are usually actions by users, and changes the view or model as appropriate. The view consists of the HTML. JavaScript reacts to events triggered by the user and alters the existing rendered content with DOM. ColdFusion will be our model layer and can consist of one or more files.

Building an AJAX platform or engine from scratch can be a difficult and lengthy procedure. There are many AJAX engines available for download and you're welcome to use any of them. The only difference between implementations will be the data encoding, transmission, and decoding methods. The views and models of the MVC will be the same. My examples will be based on CFAJAX, a community-driven Open Source project. One of the problems with CFAJAX is its poor documentation. There is no manual or even a complete FAQ. So I will explain how to set it up step-by-step and work around its downside.

To use AJAX you'll need to really know JavaScript and DOM. But by the end of this article you'll be able to set up AJAX, a ColdFusion model, make basic calls, and exchange simple data. As the applications grow and become more complex, the AJAX engine will remain the same, and the CF model will have more functions, but your JavaScript will have to manipulate more and more objects and that's where it's really at.

Enough chatter, let me show you how it works.

First, go to www.indiankey.com/cfajax/project.asp and download cfajax.1.2.zip. This file contains the core engine, some utilities, and some examples. Let's set up a folder in your Web root or whatever accessible folder you like called 'ajax.' Put the 'core' folder located in the cfajax zip file inside your 'ajax' folder. There are only two important files in this folder: 'engine.js' and 'cfajax.cfm.'

The engine.js contains the whole AJAX object that we'll use as our tunnel and cfajax.cfm has some basic functions that your ColdFusion model will have to include to decode the AJAX packet. Other files, not so core anymore, are 'util.js.' which contains a series of DOM functions to facilitate HTML manipulation when the server response is received, 'rico.js,' used for a built-in accordion example, and 'settings.js,' which aren't really settings, only the location of your ColdFusion model and an error-handler function. The only reason why this file exists is to hide the location of your ColdFusion file should someone open and view the source of your HTML file, which in my opinion is counter-productive because you have to edit this file and add a location variable every time you want to use AJAX with different models. The security should be built into the ColdFusion file.

Some people will claim that they can provide you with AJAX functionality without writing a single line of JavaScript; I disagree. Although you could use ColdFusion libraries to generate JavaScript, the results will be limited to the functionality provided. AJAX means asynchronous JavaScript and XML, not ColdFusion. So if you want to use AJAX effectively and provide solutions to new problems, you should learn JavaScript.

Now that we have our CFAJAX in place, let's create an index.cfm file and a model.cfm file in your ajax folder. For larger applications I would store the views in a 'views' folder and models in a 'models' folder, but I digress. Shall we concentrate on the basic example?

Open index.cfm and include the 'core/engine.js' file. Then create a 'getGreetings' and 'getGreetings_result' function. We'll call getGreetings onLoad for now, and the results function will just alert the response.

The 'engine.js' file creates an object called DWREngine; it means Direct Web Remoting. We will mainly be using a method called '_execute.' Execute takes four or more arguments. The first argument is the ColdFusion model location, then a queryString, a methodName, and a callback function, which is the JavaScript function that will be called when we get a response from the server. Execute also takes some optional arguments. It's not documented, but Execute will take any number of arguments, which will be parameters to be passed to the called method, and they have to be put between the third and fourth argument. I'll show you an example later.

Right now the file looks like this:

Our model.cfm will be extremely simple. All we need to do is include the 'core/cfajax.cfm' file and a getGreetings function:

model.cfm
<cfinclude template="core/cfajax.cfm">
<cffunction name="getGreetings" returntype="string">
  <cfreturn "Today is " & DateFormat(now(),'MMMM DD') & ", Greetings." />
</cffunction>

Well, that was easy; we just finished our first AJAX application.

Now let's create a small application that could actually benefit you. How many times have you created a registration form that can validate almost everything client-side by using JavaScript, but the username has to be validated upon submission, and if it already exists, you either have to abort and use JavaScript for the alert and send the client back, or cflocate and populate all the form fields by using the session. Wouldn't it be great if we could avoid all that and simple check the username as another JavaScript call? And not even think of creating an existing username array and have it local in the registration form?

It 's not that much different from the file we have. Let's modify the index.cfm file a little. We'll create a basic user registration form with a single fieldname called user and we'll pass that value to the AJAX call. The tricky part here is that AJAX is asynchronous, which means that the function won't return the value you need. Instead the callback function will get called on a different thread. Not to worry, I'll demonstrate how this can be done.

model.cfm
<cfinclude template="core/cfajax.cfm">
<cffunction name="userExists" returntype="boolean">
   <cfargument name="event">
   <cfset var return = false />
   <cfif ListFindNoCase('rob,john,paul',event)><cfset return = true /></cfif>
   <cfreturn return />
</cffunction>

Index.cfm now contains a user registration form. On submit, we'll call checkUser(). Note that we must actually call it with a return parameter or we'll always return false! No matter what happens, the form won't get submitted the traditional way. Note that I included 'utils.js' only to call the 'useLoadingMessage' function, which imitates the Gmail loading message while AJAX makes its round trip. 'Execute' sets a callback function, which checks for the ColdFusion return. If true, we'll display an error message, and if the user doesn't exist, we'll manually submit the form by using the JavaScript submit() function. The only difference in the execute call is that we pass the form value to the ColdFusion model. The CFM page is straightforward: all we're doing is a dummy check against a hard-coded list. This is the place where you would put your queries or invoke your components.

You should now be able to set up an AJAX engine, a simple HTML view, make a call, listen, process, and respond using ColdFusion, and process the response in your callback function. In the next part of this article, I'll explain how to pass complex objects by using WDDX serialization, populate tables, use innerHTML properties for advanced JavaScript view manipulations, and provide a full internal rotating banners application that tracks impressions and clicks. I will also cover cross-browser compatibility and offer some little tricks to make your AJAX application as widely compatible as possible.

About Rob Gonda
Rob Gonda is an industry visionary and thought leader, speaks on emerging technologies conferences nationwide, and combines unique approaches to technology and marketing strategies. As a head of Creative Technologies at Sapient, Gonda is an interactive technical “guru,” who provides the knowledge and experience required to run high-level, multi-channel interactive campaigns that reach millions of consumers. Gonda has more than 15 years of experience in web development and 360 marketing campaigns for clients such as Coca-Cola, Adobe, Guinness, Toyota, Taco Bell, NBC, and others. His areas of specialty include emerging technologies, marketing strategy, social media, digital out-of-home, mobile, behavioral targeting, and multi-channel synergy. Before joining the strategy and technology leadership teams at Sapient, Gonda was co-founder and chief technical officer at iChameleon, a Hollywood FL-based agency renown for its emerging experiences and creative technology. In addition to his agency work, Gonda the chair for the digital media council at the Advertising Research Foundation, is the former editor-in-chief of the AJAX Developer’s Journal, co-author of “Real-World AJAX: Secrets of the Masters”, a passionate blogger who authors www.takemetoyourleader.com, and contributors to various publications such as Ad Age and Ad Week. He is a frequent figure on the speaker circuit, having presented at conferences from the senate’s CIO emerging technology to SXSW and Omma. Rob’s mission is to develop forward-thinking expertise that will ensure clients are always on par with rapidly changing technologies and maintain its ethos of evolving. You can reach him at rob[at]robgonda[dot]com and read his blog is at http://takemetoyourleader.com

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1



ADS BY GOOGLE
Subscribe to the World's Most Powerful Newsletters

ADS BY GOOGLE

SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 1...
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018,...
Dynatrace is an application performance management software company with products for the informatio...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, ...
Today, we have more data to manage than ever. We also have better algorithms that help us access our...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: D...
A valuable conference experience generates new contacts, sales leads, potential strategic partners a...
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by Fi...
SYS-CON Events announced today that IoT Global Network has been named “Media Sponsor” of SYS-CON's @...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news an...
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held Novemb...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing w...
Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear...
Enterprises are striving to become digital businesses for differentiated innovation and customer-cen...
DXWorldEXPO LLC announced today that Telecom Reseller has been named "Media Sponsor" of CloudEXPO | ...
Consumer-driven contracts are an essential part of a mature microservice testing portfolio enabling ...
"Calligo is a cloud service provider with data privacy at the heart of what we do. We are a typical ...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As au...
DXWorldEXPO LLC announced today that "IoT Now" was named media sponsor of CloudEXPO | DXWorldEXPO 20...