The Largest Repository of ColdFusion Knowledge in The World for More Than 12 Years

ColdFusion on Ulitzer

Subscribe to ColdFusion on Ulitzer: eMailAlertsEmail Alerts newslettersWeekly Newsletters
Get ColdFusion on Ulitzer: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


CFDJ Authors: AppDynamics Blog, Michael Kopp, Tad Anderson, Bob Gourley, Jayaram Krishnaswamy

Related Topics: RIA Developer's Journal, ColdFusion on Ulitzer, Apache Web Server Journal, XML Magazine, AJAX World RIA Conference

RIA & Ajax: Article

Real-World AJAX Book Preview: The AJAX News and Feed Reader

Real-World AJAX Book Preview: The AJAX News and Feed Reader

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs for the special pre-order price, click here for more information. Aimed at everyone from enterprise developers to self-taught scripters, Real-World AJAX: Secrets of the Masters is the perfect book for anyone who wants to start developing AJAX applications.

The AJAX News and Feed Reader

The AJAX News and Feed reader is an application written in ColdFusion using ajaxCFC, a free open source ColdFusion/AJAX framework, and a Model-View-Controller design pattern. It contains the basic functionality of taking an unlimited number of RSS 2.0 feeds as input, parsing the XML data, listing the feeds in a left menu, and showing the news entries in the main area. You can add/delete feeds at any point as well as request a feed update. This example doesn't permanently store any feed, eliminating the need for a database or tedious install. All feeds are stored in the session of the user using the application and are deleted when the session expires.

The design is an XHTML table with three main elements: header, left column, and main content area. The header contains an input field to add new feeds; the left column lists all existing feeds; and the main content area shows all entries for one particular field.

DHTML elements have been kept to a minimum to illustrate clearly the difference between AJAX and DHTML. There are no fancy transitions, movements, or effects, just server connectivity and content update using easy-to-learn techniques, putting AJAX applications closer to everyone's reach.

First rule of thumb: this application uses no DOM! Document Object Model is a way of controlling the elements inside an HTML page with object nodes. Despite the fact that nodes behave differently in different browsers, the main reason not to use them is code reusability. To use DOM, the same code has to exist in HTML tags for the initial load, and in object notation for updates.

There are reasons why the Model-View-Controller pattern is so widely used and preferred by most advanced object-oriented developers. The first one is because it clearly distinguishes the presentation layer from the business logic, making it so changes in one will hardly affect the other. The second reason is code reusability: breaking down the distinct elements in the presentation layer lets them be included and reused as often as needed in HTML or AJAX applications.

The Architecture

The application has three main components: views, controllers, and models. Views represent the presentation layer, which consists mainly of HTML and JavaScript. The controller's main function is to accept requests from the views and process them using the models, and then decide which view to update. Finally, the models are the ones that contain the application's core functionality and business logic.

Pay special attention to the fact that RSS feeds are nothing but simple Web Services whose main purpose is to share data and content in raw format. Many developers attempt to use JavaScript to access these Web Services, leaving all functionality in the client's browser. Every browser has what is called a sandbox, which prevents cross-domain calls and makes it difficult for the XMLHttpRequest to find its way to third-party feeds. There's a reason why browsers don't allow these calls, and it makes no sense to try to get around it. Even if it wasn't so difficult to initiate cross-domain requests, client-side feed readers aren't a good idea. After getting the XML feed, JavaScript would have to apply some logic in parsing it, catching errors, and updating the view layer, meaning that now all the logic is sitting inside the client's browser. What does this mean? It means that all the business logic can be viewed, decoded, examined, analyzed, and modified by anyone. That's quite a big security hole that no commercial application can afford to have.

This application demonstrates how to keep only connectivity JavaScript functions on the client side and leave all the business logic on the server. It's wrong to assume that because AJAX stands for Asynchronous JavaScript and XML it means that JavaScript should predominate. Some Java Script knowledge is necessary to build AJAX applications successfully; nonetheless, as this example demonstrates, it's possible to build them without being a JavaScript guru.

The secret resides in two magical functions: innerHTML and eval. InnerHTML, which modifies the content of any element on the page without using DOM, thus reusing the same server-generated HTML views. The eval function dynamically executes any JavaScript string, making it possible to build instructions on-demand on the server side that the browser will blindly execute.

Don't confuse server-side evaluation with client-side evaluation. The server can never blindly evaluate AJAX requests because that would open it to JavaScript, XML, and SQL injections. The clientside JavaScript can evaluate server requests because the application maintains full control of the instructions. The worse thing that can happen is that the instruction is intercepted and the user finds a way to alter the presentation layer.

In reality, an AJAX request isn't different from any regular HTML request. In an MVC framework, it will follow exactly the same steps, passing through an event handler, controllers, models, back to the controllers, and views. The only difference is that a traditional request outputs HTML, while an AJAX request can output data either in string or XML format or instructions in JavaScript format. In this application, the AJAX response will always output JavaScript instructions.

Client-Side Code

The client-side components consist of HTML and JavaScript. Unlike some other AJAX applications rich in JavaScript, this one only has a connectivity library and manages the remote calls. Doing AJAX calls is possible with just a few lines of code as shown in Listing 14.1.

Listing 14.1

var req;

function loadXMLDoc(url) {
   req = false;
     // branch for native XMLHttpRequest object
     if(window.XMLHttpRequest) {
       try {
         req = new XMLHttpRequest();
       } catch(e) {
       req = false;
       }
     // branch for IE/Windows ActiveX version
     } else if(window.ActiveXObject) {
       try {
       req = new ActiveXObject("Msxml2.XMLHTTP");
       } catch(e) {
       try {
         req = new ActiveXObject("Microsoft.XMLHTTP");
       } catch(e) {
         req = false;

       }
     }
   }
   if(req) {
     req.onreadystatechange = processReqChange;
     req.open("GET", url, true);
     req.send("");
   }
}

However, there's more to consider in spite of this simple remote request like security, concurrency, error handling, logging, and serialization, just to name a few. For this reason, this example is based on a ColdFusion/AJAX library called ajaxCFC. To set it up it takes only two lines, as outlined in Listing 14.2.

Listing 14.2

<script type='text/javascript'>_ajaxConfig = {'_cfscriptLocation':'index.cfm', '_
jsscriptFolder':'views/js/ajax'};</script>
<script type='text/javascript' src='views/js/ajax/ajax.js'></script>

The first line sets up a configuration object that tells the component where the event handler is and where the JavaScript library is; the second line simply includes one JavaScript file. It couldn't be simpler.

The location of the event handler can be overridden on a per-call basis, but nine out of 10 times all calls will be directed to the same event handler or façade.

Making a remote call is as simple as calling the ajax() function and passing two arguments: the method, function, or event to be called on the server side and the arguments to be passed. The arguments can behave differently depending on what is sent. The call can take named or unnamed arguments, one or many, invoke a specific callback function or use the generic. This example simplifies the process and always uses named arguments and the default callback handler. For example, the action to aggregate a new feed looks like the code in Listing 14.3.

Listing 14.3

ajax('addFeed', {feed:$('newFeed').value});

The first argument simply indicates that the "addFeed()" event will be called by the event handler; the second is a named arguments, with the name 'feed,' and the value of the "newFeed" text input. The $() function is nothing but a shortcut, a somewhat improved version of getElementById(). JavaScript libraries such as prototype.js or DWR commonly use it.

Note that every asynchronous call requires that a function be called once the server replies and no function is set here. The library's default behavior is to expect a string to be dynamically evaluated, eliminating the need for setting a new handler for every function.

The default callback is just a simple dynamic evaluation function per Listing 14.4.

Listing 14.4

// call back function
function evaluator (r) {
eval(r);
}

The function expects the server to respond with a string of JavaScript instructions that can be blindly evaluated. To modify any content, the server will send an innerHTML property along with the instructions.

Besides the remote request call, the only other client-side function is an activity indicator. It's always good practice to let the user know when something is happening in background. Traditionally, the Web user is used for constantly clicking/refreshing while waiting for new content to arrive. With AJAX, activity or progress indicators are needed every time the user depends on the response of some asynchronous call.

The ajaxCFC framework comes with two ways to do that: a generic red box located in the top right of the screen or a small animated gif that can replace the content area that's expecting to be updated. To replace an area with this animated gif, a loading call is triggered as shown in Listing 14.5.

Listing 14.5

function loading(target) {
    $(target).innerHTML = '<div align="right">
<img src="images/indicator_snake.gif"></div>';
}

To invoke this function, simply add if before the AJAX call. Optionally, it could also be incorporated as part of the ajax() function call. After the previous example, the loading function can be called immediately before adding a new feed to the list. The left column will show an animated sneak gif while waiting for the server to fetch the RSS information from the newsfeed and append its title at the end of the current feeds list as in Listing 14.6.

Listing 14.6

<input type="text" id="newFeed" size="50" value="" />
<input type="button" value="add" onclick="loading('leftCol');ajax('addFeed',
{feed:$('newFeed').value});" />

Server-Side Code

The server side consists of a Model-View-Controller framework. The controller handles all the incoming requests, communicates with the models, and uses the views to respond back to the AJAX request. This example uses three main components: an AJAX component, an aggregator, and an RSS object. The AJAX component parses all the incoming remote requests and their arguments, does security validations, and logs in various points of the process. The aggregator is a collection of individual RSS objects; every session is entitled to one aggregator. The RSS object contains all the information about one feed, including the name, description, dates, and all entries, as well as the functionality to parse the XML feed (see Figure 14.1).

The RSS object retrieves the XML feed using the cfhttp ColdFusion tag, which lets the server initiate an HTTP request and get all the content in a variable that can be parsed and processed. After downloading the XML, the XmlParse() function is invoked, which transforms the XML nodes into a ColdFusion structure followed by the XmlSearch(), which is a standard XPath function to query XML objects. The XPath function is used to find the blog title, description, link, and all the entries' information.

Where to Go from Here

You can download and use this code at will. It's licensed under the Apache 2.0 License.

Full working example:

  • http://www.robgonda.com/dev/rss/

    ajaxCFC Framework:

  • http://www.robgonda.com/blog/projects/ajaxcfc

    MVC Design Pattern at Wikipedia:

  • http://en.wikipedia.org/wiki/Model-view-controller

    Questions or suggestions?

  • rob [at] robgonda.com

    This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs, click here to order.

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

    Comments (0)

    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.