Welcome!

AJAX & REA Authors: John Funnell, Bob Little, Kevin Hoffman, Maureen O'Gara, Onkar Singh

Related Topics: AJAX & REA, ColdFusion

AJAX & REA: Article

AJAX: Making the HTML User Experience Almost As Pleasant as Flash

The main advantage of Flash, in spite of its vector animations, is that you never reload the page

Trick 2
Observe that when you pass back HTML content to JavaScript, you have to URL-Encode the content (see Listing 7). If you try to pass back the HTML tags without encoding it, the AJAX calls will break without notice or error messages. In the receiving counterpart, you need to decode the HTML and this is achieved by using the unescape function as shown in Listing 6.

The drawback of this method is that it completely kills search engine friendliness. Search engines will not execute JavaScript calls and will not index your content. As a rule of thumb, I try to keep all front-end related content as SEO friendly as possible. You can use these examples for back-end related purposes. For example, gmail was written completely in AJAX. Notice that you can read and write e-mails and the site will never refresh and the speed is different over hotmail or any other Web mail application.

Table Example
Next, I'll cover looping over an AJAX record set and populating tables. Although you could generate the table and send the rendered HTML by using my previous content example, by using this technique, you'll delegate the load to the client browser instead of keeping it in the server.

I will introduce now a few DOM functions: createElement, createTextNode, setAttribute, appendChild, and removeChild. The concept here is to receive a recordset from a ColdFusion function and create the HTML by using DOM functions instead of the HTML tags.

In this example, I'll only demonstrate the JavaScript part that builds the table. If you look at Listing 8, you'll see an empty table with an ID in the "tbody" tag. This "tbody" tag is extremely useful when you have additional elements such as column headers in the "thead" tag. The "tbody" allows us to reference that section directly when adding and deleting elements.

The logical process that I follow in my pages is showing a "please wait" DIV when the user submits the request. At this point I make the AJAX call, send the request parameters, and wait for the response. The response will trigger the callback function, which immediately executes the "clear_table" function. This function loops over each row in the "tbody" and calls the DOM "removeChild" function. This will clear the results from the previous call. After I finished emptying the table, we proceed to populate it with the new recordset. If you look at the "showTable" function, you'll find two nested loops: one for each row and one for each column. Looping over each column is optional and up to you. Traditional ColdFusion programmers may prefer to loop over each row and manually code each column to their needs. Personally, I like to avoid having to write the same code over and over if I can help it. In my example, I created an array called "r" that contains the columns that I want to display. After you finish populating the table with the new recordset, you may remove the "please wait" message and the process is over.

Populating the table is actually rather simple: first I loop over each row from the recordset and create a "TR" element by using createElement('tr'); then in the nested loop I create the "TD" element for each column by using createElement('td'). The text is then evaluated in the following line "currenttext=document.createTextNode(eval('o.' + r[i] + '[j]'));". Here the "eval" function is resolving the recordset, then the column name, and then the position. For instance, the first row, first column, will read "o.uname[0]".

Creating the links is not as simple as typing "<a>". You will need to create an "A" element by using createElement('a'), and then use the setAttribute to add the href attribute.

After all is said and done, all that's left to do is to append each element to its parent. First you append the text node to the "a" element, then the "a" to the "td", then the "td" to the "tr", and finally the "tr" to the "tbody".

CFAJAX includes some utilities that facilitate this process but, the truth is, you will need to learn DOM JS if you really want to take control. For example, the example in Listing 8 only adds a link to the first column, and all the rest are just text.

Related Options Example
My last example will explain a useful built-in function with CFAJAX: related options (see Listing 9). How many times have you had to load enormous arrays of options to your HTML template to achieve this? Wouldn't it be great if you could load the dependent options only after the main option has been selected? CFAJAX includes two handy functions: "removeAllOptions" and "addOptions". These two functions will drive the JavaScript work to achieve related options to zero.

I hope the community doesn't mind, but I'll use the example from their site to demonstrate how this is achieved.

First, we'll have a brand dropdown that will call a JavaScript function called "getBrand" on its "onChange" trigger. All this function does is send ColdFusion the value of the current selected brand, and ColdFusion will return an array of values.

The array actually contains value pairs, which are the key, and the value separated by commas. It's important to pay attention to the hint value of the ColdFusion function; in this example, it's hint="type='keyvalue' jsreturn='array'", which is actually used in the callback function to set the expected value types. You can tell JavaScript the complex type of the return, set it to receive value pairs, and optionally set the delimited of the pairs. By default, it is expecting a comma for the delimiter.

The callback function cannot get any simpler. "getBrandResults" performs only two functions: DWRUtil.removeAllOptions("model"), which removes all current options from the model select component, and DWRUtil.addOptions("model", modelArray, "KEY", "VALUE"), which add the returned array to the model select component.

Conclusion
I hope you learned how AJAX could create a better user experience on your site. I covered passing complex objects, using innerHTML to modify the view layer after it has been rendered, drawing dynamic content, manipulating tables, and using related select options. AJAX is extremely fast, secure, and allows for advanced functionality that synchronous HTML does not.

More Stories By 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. He is the former Editor-in-Chief of the AJAX Developer’s Journal, an Advanced Certified Coldfusion Developer, member of the Adobe Community Experts, frequent contributor to the CFDJ and ADJ, co-author of Real-World AJAX: Secrets of the Masters, author of AjaxCFC, holds a BS in computer science and engineering and an MBA with a specialization in entrepreneurship. Rob recently joined Sapient from ichameleon/group/ where he was a founding partner and chief technical officer. He is part of the global technology leadership team, and brings with him over ten years of experience in web development and 360 marketing campaigns for clients such as Adobe, Coca-Cola, Guinness, Toyota, Taco Bell, NBC, and others. He specializes in emerging technologies, marketing strategy, social media, and he is currently fascinated with rich internet applications, service oriented architecture, mobile, agile methodology, automation, behavioral targeting, multi-channel synergy, and identifying new trends. 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://www.robgonda.com

Comments (17) 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
Dougal Mathers 02/13/08 12:19:23 PM EST

I cannot seem to get the table example to work and am wondering if you could help explain a bit more around it as with the other examples?

Great article to get people started. Many thanks,Dougal.

Thierry Nivelet 04/14/06 08:22:21 AM EDT

You may be interested in our catalog multi-criteria search engine
http://www.intuicat.com/IntuiCatAjaxDemo.asp

Interesting enough is that all presentation code lies on server, client merely executes change orders sent by server.

SYS-CON Belgium News Desk 04/11/06 11:15:58 AM EDT

AJAX can make the HTML user experience almost as pleasant as Flash. The main advantage of Flash, in spite of its vector animations, is that you never reload the page. Flash Remoting allows you to interface with the server in the background and AJAX does exactly the same for HTML pages.

SYS-CON India News Desk 04/11/06 10:07:45 AM EDT

AJAX can make the HTML user experience almost as pleasant as Flash. The main advantage of Flash, in spite of its vector animations, is that you never reload the page. Flash Remoting allows you to interface with the server in the background and AJAX does exactly the same for HTML pages.

Rob Gonda 12/09/05 12:34:11 AM EST

by the way, check out my latest alternative to cfajax. I developed an ajax CFC framework.

check it out at http://www.robgonda.com/blog/projects/ajaxcfc/

Jim @ The ZK Project 11/27/05 11:28:24 PM EST

>> First of all, I really disagree on rising cost of developing AJAX applications.

Adding an AJAX feature means an extra task, no matter how simple it is. It gets worse when we add more codes to the client. It means you might have to replicate business logic to clients. It also means you have to maintain two copies of codes.

>> It definitely helps with dhtml and look and feel, but it does not automate AJAX at all, it makes it actually
>> more difficult. It seems like that in order to make it work you need to add your Java server-side code
>> within your view. That will make maintenance really tedious.

Whether to embed codes in the view is up to developers, not the framework itself. It is designed to speed up prototyping and customization. If MVC or other design patterns are required, developers need only to provide a map between components to the real class they want.

On the other hand, traditional AJAX apps required developers to embed JavaScript into HTML pages.

AJAX has different meanings to different people. For us, it means a technology to enable a rich user interface that communicates with the backend server. What ZK does is to abstract the interaction and communication to Java level and make to the server side, not JavaScript or decorated HTML, not at the client that you are used to.

Rob 11/26/05 05:28:05 PM EST

BTW, for more info please visit my blog at http://www.robgonda.com/blog

Rob 11/25/05 11:36:26 AM EST

Jim,

First of all, I really disagree on rising cost of developing AJAX applications. Au contraire, they are going down as more and more developers get into it.

Although I usually do not check seeding or spam, I decided to check the ZK project.

It definitely helps with dhtml and look and feel, but it does not automate AJAX at all, it makes it actually more difficult. It seems like that in order to make it work you need to add your Java server-side code within your view. That will make maintenance really tedious.

Jim @ The ZK Project 11/25/05 03:42:40 AM EST

As AJAX gives Web applications a fresh look, the rising cost of developing AJAX applications is challenging its way to success.

That is the reason we founded the ZK project ( http://zk1.sourceforge.net ): make AJAX transparent to app developers.

ZK is an Open Source and Live Demo at http://www.potix.com/zkdemo/userguide.

ZK has the following characteristics.
* XUL-based Components.
* Event Driven Model.
* Server-Centric Processing.
* Script in Java and EL Expressions.

Rob 11/22/05 11:48:23 PM EST

Kevin, good call. I usually do, but with the rush of getting the article out it slipped... Thanks for pointing it out.

Rob 11/22/05 10:25:24 PM EST

By the way, can someone please fix this feedback tool?! I won't take 9 out of 10 posts I submit.

Rob 11/22/05 10:24:30 PM EST

Kevin, good call. I usually do, but with the rush of getting the article out it slipped.
Thanks for pointing it out.

Kevin Penny 11/22/05 06:49:12 PM EST

Excellent - you should scope your cfc vars however - makes it alittle easier to understand what vars come from where (arguments)

MissedOut? 11/17/05 07:40:22 AM EST

I've still yet to build my first AJAX request. Does that mean I'm too late to the party?

newbie 11/17/05 07:26:34 AM EST

So is AJAX a download or is it a technique? Pafrdon my ignorance...only now I am seeing AJAX, AJAX, AJAX everywhere but I don't really know what it *is* yet

newbie 11/17/05 07:26:32 AM EST

So is AJAX a download or is it a technique? Pafrdon my ignorance...only now I am seeing AJAX, AJAX, AJAX everywhere but I don't really know what it *is* yet

ByeBye HTML 11/17/05 06:43:27 AM EST

>> AJAX is extremely fast, secure, and allows
>> for advanced functionality that
>> synchronous HTML does not.

No wonder this is the hottest technology on earth right now. HTML is Dead!