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

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.

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

Dynatrace is an application performance management software company with products for the informatio...
In his session at 21st Cloud Expo, Michael Burley, a Senior Business Development Executive in IT Ser...
Having been in the web hosting industry since 2002, dhosting has gained a great deal of experience w...
NanoVMs is the only production ready unikernel infrastructure solution on the market today. Unikerne...
All in Mobile is a mobile app agency that helps enterprise companies and next generation startups bu...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO Silicon Valley 2019 will cover all of these tools, with the m...
Yottabyte is a software-defined data center (SDDC) company headquartered in Bloomfield Township, Oak...
SUSE is a German-based, multinational, open-source software company that develops and sells Linux pr...
Your job is mostly boring. Many of the IT operations tasks you perform on a day-to-day basis are rep...
Serveless Architectures brings the ability to independently scale, deploy and heal based on workload...
Technological progress can be expressed as layers of abstraction - higher layers are built on top of...
When building large, cloud-based applications that operate at a high scale, it’s important to mainta...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it wil...
Big Switch's mission is to disrupt the status quo of networking with order of magnitude improvements...
Lori MacVittie is a subject matter expert on emerging technology responsible for outbound evangelism...
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the c...
"Calligo is a cloud service provider with data privacy at the heart of what we do. We are a typical ...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, disc...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (No...
Chris Matthieu is the President & CEO of Computes, inc. He brings 30 years of experience in developm...