Welcome!

AJAX & REA Authors: Rajesh Lain, Sebastian Kruk, RealWire News Distribution, Harald Zeitlhofer

Related Topics: AJAX & REA, ColdFusion

AJAX & REA: Article

Building a Drag-and-Drop Shopping Cart with AJAX

Creating an interactive shopping experience

Keeping up with the latest Web technologies is tough nowadays. Every week it seems new sites are launched that push the envelope further and further in terms of what can be accomplished using just a Web browser.

The rise of AJAX over the past several months has taken over the development world and breathed new life into the Web. Although these techniques have been possible for many years now, the maturity of Web standards like XHTML and CSS now make it a viable alternative that will be viewable by all but the oldest browsers.

It's also been possible to accomplish many of the same things using Flex or Flash, but the development cycle with those applications is typically more involved and the overhead often not justified.

We're going to harness the power of the Scipt.aculo.us JavaScript library to provide our interaction. As their Web site states, this library "provides you with easy-to-use, compatible and, ultimately, totally cool JavaScript libraries to make your web sites and web applications fly, Web 2.0 style." We're also going to utilize the <CF_SRS> library to handle the actual AJAX data piping to our application. Both of these libraries are free for all to use, and they're easier to integrate than you would think.

For this article, we'll create an interactive shopping experience allowing us to add items to our shopping basket by dragging and dropping them onto an icon of a shopping cart. We'll add AJAX functionality, allowing us to update our shopping cart without redrawing the entire screen. To save the trouble of setting up a product database, we'll use Amazon Web Services to search for DVDs and use those to shop from.

Start with a blank index.cfm in your root directory. You'll need to visit http://script.aculo.us/downloads to download the latest distribution (they're nearing a final release for version 1.5 as of this writing). Copy the "lib" and "src" directories into your empty directory. You'll need all of the .js files so just copy over the entire directory in each case. Next, type the following lines into the <head></head> section of your page:

<script src="./lib/prototype.js" type="text/javascript"></script>
<script src="./src/scriptaculous.js" type="text/javascript"></script>

We'll need a search box to submit our query to Amazon:

<form action="index.cfm" method="post">
Search: <input type="text" name="keywords" size="20" />
<input type="submit" name="search" value="Go" />
</form>

The page will look for a form.search variable and run an Amazon search when it is defined. Each item returned will be placed in its own styled div that will be able to be picked up and dragged.

The Scriptaculous library makes it easy to create "draggables" (the only required argument is the ID of the object that you want draggable). Listing 1 contains the code to search Amazon and return the results as draggable divs.

At this point, all of the items returned from the search will be in their own box and should be draggable around the screen. When we created each draggable, we set "revert=true", which will snap each object back to its original location if not placed directly on a drop zone.

Next, we'll add a graphic of a shopping cart to our page, which will become a drop target on which to drag items. The Scriptaculous library also makes it easy to create these "droppables". The syntax is simply:

Droppables.add('id_of_element',[options]);

The code below creates a droppable zone of id "cart1" and also runs a function onDrop() that pops up an alert box letting the user know an item has being added. We then hide the element from view, which allows the other divs to slide over and adjust accordingly.

<img src="shopcart.jpg" id="cart1" style="float:left;">
<script language="javascript" type="text/javascript">
Droppables.add('cart1', { onDrop:function(element) {
alert('Added UPC ' + element.id + ' to your shopping cart.');
Element.hide(element.id);}})
</script>

The items should now be disappearing when dropped onto the shopping cart, but there's nothing going on behind the scenes yet. Now it's time to add some AJAX to process our shopping cart.

Although there are several AJAX libraries to choose from, we're going to use the ColdFusion Simple Remote Scripting <CF_SRS> library made available free of charge by Matthew Walker of ESWsoftware in New Zealand. <CF_SRS> uses an IFRAME for communication and encapsulates all of the dirty work for you. This library was chosen for its ability to handle HTML tables well and for its ability to interact directly with the browser's Document Object Model (DOM) to output our shopping cart rows.

We'll start with an empty cart by including the following code:

<fieldset style="width:400px;">
<legend>Your shopping cart</legend>
<table border="0" cellspacing="0" cellpadding="5" id="tableCart">
<thead></thead><tbody></tbody></table>
<button onclick="emptyCartButton_onClick()" id="emptyCartButton">
Clear Shopping Cart</button>
</fieldset>

(Don't worry about the fact that our table body (<tbody></tbody>) is empty right now - we'll be populating it in just a second through AJAX.)

Next, you'll need to download the <CF_SRS> package from www.eswsoftware.com/products/download/. Copy the srs.cfm file into your Webroot (or you can add it to your CustomTags directory if you plan to do more AJAXing). You'll also need to create a subdirectory to hold the gateway pages that handle our AJAX data passing. Name the directory "SRS" and copy the Application.cfm and OnRequestEnd.cfm files into there from the "serverpages" directory in the zip file. You can use either regular CFM files or CFCs for these gateway pages (the download provides examples of each). The main thing to remember is that these pages should always return their results to "request.response".

Simply adding a <cf_srs> call to your page will handle the creation of the hidden IFRAME for you. Another great feature of the CF_SRS library is the ability to view an inline debugging window right inside the page you are working on. This allows you to see all of the data being passed back and forth through the gateway. You can enable this debugging by calling the tag as <cf_srs trace>. This line can be placed anywhere but we'll add it at the very end of the file.

Next, we'll need to create some JavaScript functions to handle the AJAX interactions. Add an onLoad function to your body tag as such: <body onload="body_onLoad()">. This will execute body_onLoad() when the page loads and we'll use this function to set up our gateway. The function should read as follows:

function body_onLoad() {
// create an SRS gateway to the cart.cfm page
objGateway = new gateway("srs/cart.cfm?");
// update cart in case of return visit
// code for this function is below
updateCart();
}

Once you have created your gateway, you can invoke the methods below to send requests to the server:

  • objGateway.setListener( str ): Use this method to specify the name of the function in your Web page that will handle the server's response. str is a string representing the function's name. The listener defaults to "alert", which will pop up a JavaScript alert() box containing the server's response. Note that while ColdFusion is a case-insensitive language, JavaScript is case-sensitive. If you return a structure to your listener function, all the structure keys will be rendered in JavaScript as lowercase.
  • objGateway.setArguments( obj ): Set the arguments and values to pass to the server. obj is an object literal, which is basically just a set of one or more attribute/value pairs wrapped in curly braces. Here's an example: { name:'Joe', age:30, country:'US' }. You can see that string values need to be wrapped in quotation marks, and colons (:) are used in place of equals signs (=).
  • objGateway.resetArguments(): Remove all the arguments previously set.
  • objGateway.request(): Send the request to the server.

More Stories By Joe Danziger

Joe Danziger is a senior web applications developer with Multimax, Inc., a provider of Enterprise IT Services and Solutions supporting the critical missions of the Air Force, Army, Navy, and other Department of Defense components. He is certified as an Advanced Macromedia ColdFusion MX Developer, and also maintains the Building Blocks site (www.ajaxcf.com) dedicated to AJAX and ColdFusion, as well as DJ Central (www.djcentral.com), a Website serving DJs and the electronic dance music industry.

Comments (22) 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
King 05/21/08 03:33:54 PM EDT

Soon everything will be Ajax, just look how the major websites are adapting to use it.

A 05/07/08 01:02:58 PM EDT

I think your right when you say that Ajax is the way of the future, although its is difficult to program, you can see yahoos and googles implementation of it.

Scott 08/02/07 12:04:03 PM EDT

Hello N,

I had the same problem. Try changing:

to:
<cfif StructKeyExists(xnSearch.Items.Item, "MediumImage")>

N 07/14/07 10:19:57 AM EDT

I'm following this tutorial to the letter as well and I also get this error in the code that retrieves the info from Amazon...

Element ITEMS.TOTALRESULTS.XMLTEXT is undefined in XNSEARCH

Is there a fix available or anything to get this to work. It looks good though.

N

asdf 07/10/07 01:17:36 AM EDT

asdfsafs asdfasf asdfasf

abcd 07/10/07 01:14:52 AM EDT

heloow asdf asdfs asdfasf biuiouer asdfaf boihoi awerew asdf

Wally Kolcz 01/22/07 09:27:35 AM EST

I loved your tutorial on how to make a drag and drop web cart, but I couldn't quite follow on how to put the code into the page to make it work. Do you have any finished files available for download to see how it is constructed?

Thanks

BUses 12/26/06 08:45:23 PM EST

Awesome content: L'augmentation d'AJAX pendant plusieurs mois passés a repris du monde de développement et a donné un second souffle au Web.
Merry Christmas of Poland!

Simone from Italy 12/20/06 10:54:21 AM EST

Hi, please add a link to index.cfm full compliled because It's very hard to have a union of all fragments introduced in your article. Thanks

Danny 10/31/06 04:09:38 AM EST

I'm following this tutorial to the letter and I get this error in the code that retrieves the info from Amazon...

Element ITEMS.TOTALRESULTS.XMLTEXT is undefined in XNSEARCH

Any ideas? Thanks for this tutorial!

j j 09/21/06 02:01:43 PM EDT

Keeping up with the latest Web technologies is tough nowadays. Every week it seems new sites are launched that push the envelope further and further in terms of what can be accomplished using just a Web browser.

Student Organization Guy 08/05/06 04:28:22 AM EDT

How is user experience improved with dragging items into a shopping cart? ;) This is just developer feature candy. There are many other site components to focus your time on that will improve your application. Don't work so hard just to remove your 'add to cart' buttons.

CFDJ News Desk 08/04/06 04:20:22 PM EDT

Keeping up with the latest Web technologies is tough nowadays. Every week it seems new sites are launched that push the envelope further and further in terms of what can be accomplished using just a Web browser.

AJAXWorld News Desk 08/04/06 03:46:57 PM EDT

Keeping up with the latest Web technologies is tough nowadays. Every week it seems new sites are launched that push the envelope further and further in terms of what can be accomplished using just a Web browser.

AJAXWorld News Desk 08/04/06 03:46:48 PM EDT

Keeping up with the latest Web technologies is tough nowadays. Every week it seems new sites are launched that push the envelope further and further in terms of what can be accomplished using just a Web browser.

AJAXWorld News Desk 08/04/06 03:35:26 PM EDT

Keeping up with the latest Web technologies is tough nowadays. Every week it seems new sites are launched that push the envelope further and further in terms of what can be accomplished using just a Web browser.

AJAXWorld News Desk 08/01/06 04:10:49 PM EDT

Keeping up with the latest Web technologies is tough nowadays. Every week it seems new sites are launched that push the envelope further and further in terms of what can be accomplished using just a Web browser.

barb 08/01/06 03:52:54 PM EDT

I also have been struggling to get this example to work. It is not clear to me if I have to have a Coldfusion server running. Currently, I do not. I simply followed the instructions in the article. I'm getting the Javascript error "gateway not defined" from the line of code where I try to instantiate it: objGateway = new gateway("srs/cart.cfm?");. Can you please provide more information or a complete code listing?

Thank you!

bill 02/10/06 11:35:56 PM EST

The app is great but I'm also struggling to get it to work. I'm not giving up!
Hi Joe,
could you please post the full code file or send us by email.
Thanks,
b.

Kenny 02/08/06 07:10:32 PM EST

This is one of the most frustrating examples I've ever tried. I cannot figure out how to assemble this application. It is not well written at all in my opinion. Why is there not a clear list of all the code somewhere? I came to the website to download the code, so I could simply paste it and watch it work. But instead I've been stressing for the last 40 minutes just trying to figure out how to get it all together, and I simply cannot. I give up!

SYS-CON Brazil News Desk 01/27/06 02:28:32 PM EST

Keeping up with the latest Web technologies is tough nowadays. Every week it seems new sites are launched that push the envelope further and further in terms of what can be accomplished using just a Web browser.

Colm Brazel 01/24/06 08:54:51 AM EST

Hi,

I'm reading the online digital edition version
of this article, page 2 ends without giving the complete listings of the code given in the article, so, for example, I don't have the code to search amazon to test. Code listings are invaluable to check article contents with hopefully verified working version.

cheers

Colm

Cloud Expo Latest Stories
With the explosion of the cloud, more businesses are transitioning to a recurring revenue model to generate reliable sales, grow profits, and open new markets. This opportunity requires businesses to get to market quickly with the pricing and packaging options customers want. In addition, you will want to take advantage of the ensuing tidal wave of data to more effectively upsell, cross-sell and manage your customers. All of this is possible, but only with the right approach. At 15th Cloud Expo, Brendan O'Brien, Co-founder at Aria Systems and the inventor of cloud billing panelists, will lead a panel discussion on what it takes to launch and manage a successful recurring revenue business. The panelists will offer their insights about what each department will need to consider, from financial management to line of business and IT. The panelists will also offer examples from their success in recurring revenue with companies such as Audi, Constant Contact, Experian, Pitney-Bowes, Teleko...
Planning scalable environments isn't terribly difficult, but it does require a change of perspective. In his session at 15th Cloud Expo, Phil Jackson, Development Community Advocate for SoftLayer, will broaden your views to think on an Internet scale by dissecting a video publishing application built with The SoftLayer Platform, Message Queuing, Object Storage, and Drupal. By examining a scalable modular application build that can handle unpredictable traffic, attendees will able to grow your development arsenal and pick up a few strategies to apply to your own projects.
Come learn about what you need to consider when moving your data to the cloud. In her session at 15th Cloud Expo, Skyla Loomis, a Program Director of Cloudant Development at Cloudant, will discuss the security, performance, and operational implications of keeping your data on premise, moving it to the cloud, or taking a hybrid approach. She will use real customer examples to illustrate the tradeoffs, key decision points, and how to be successful with a cloud or hybrid cloud solution.
The cloud provides an easy onramp to building and deploying Big Data solutions. Transitioning from initial deployment to large-scale, highly performant operations may not be as easy. In his session at 15th Cloud Expo, Harold Hannon, Sr. Software Architect at SoftLayer, will discuss the benefits, weaknesses, and performance characteristics of public and bare metal cloud deployments that can help you make the right decisions.
Over the last few years the healthcare ecosystem has revolved around innovations in Electronic Health Record (HER) based systems. This evolution has helped us achieve much desired interoperability. Now the focus is shifting to other equally important aspects – scalability and performance. While applying cloud computing environments to the EHR systems, a special consideration needs to be given to the cloud enablement of Veterans Health Information Systems and Technology Architecture (VistA), i.e., the largest single medical system in the United States.
Cloud and Big Data present unique dilemmas: embracing the benefits of these new technologies while maintaining the security of your organization’s assets. When an outside party owns, controls and manages your infrastructure and computational resources, how can you be assured that sensitive data remains private and secure? How do you best protect data in mixed use cloud and big data infrastructure sets? Can you still satisfy the full range of reporting, compliance and regulatory requirements? In his session at 15th Cloud Expo, Derek Tumulak, Vice President of Product Management at Vormetric, will discuss how to address data security in cloud and Big Data environments so that your organization isn’t next week’s data breach headline.
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
Is your organization struggling to deal with skyrocketing volumes of digital assets? The amount of data is growing exponentially and organizations are having a hard time managing this growth. In his session at 15th Cloud Expo, Amar Kapadia, Senior Director of Open Cloud Strategy at Seagate, will walk through the essential considerations when developing a cloud storage strategy. In this discussion, you will understand the challenges IT is facing, why companies need to move to cloud, and how the right cloud model can help your business economically overcome the data struggle.
If cloud computing benefits are so clear, why have so few enterprises migrated their mission-critical apps? The answer is often inertia and FUD. No one ever got fired for not moving to the cloud – not yet. In his session at 15th Cloud Expo, Michael Hoch, SVP, Cloud Advisory Service at Virtustream, will discuss the six key steps to justify and execute your MCA cloud migration.
The 16th International Cloud Expo announces that its Call for Papers is now open. 16th International Cloud Expo, to be held June 9–11, 2015, at the Javits Center in New York City brings together Cloud Computing, APM, APIs, Security, Big Data, Internet of Things, DevOps and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal today!
Most of today’s hardware manufacturers are building servers with at least one SATA Port, but not every systems engineer utilizes them. This is considered a loss in the game of maximizing potential storage space in a fixed unit. The SATADOM Series was created by Innodisk as a high-performance, small form factor boot drive with low power consumption to be plugged into the unused SATA port on your server board as an alternative to hard drive or USB boot-up. Built for 1U systems, this powerful device is smaller than a one dollar coin, and frees up otherwise dead space on your motherboard. To meet the requirements of tomorrow’s cloud hardware, Innodisk invested internal R&D resources to develop our SATA III series of products. The SATA III SATADOM boasts 500/180MBs R/W Speeds respectively, or double R/W Speed of SATA II products.
In today's application economy, enterprise organizations realize that it's their applications that are the heart and soul of their business. If their application users have a bad experience, their revenue and reputation are at stake. In his session at 15th Cloud Expo, Anand Akela, Senior Director of Product Marketing for Application Performance Management at CA Technologies, will discuss how a user-centric Application Performance Management solution can help inspire your users with every application transaction.
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridstore delivers vmOptimized™ Storage that self-optimizes to each application or VM across both virtual and physical environments. Leveraging a grid architecture, Gridstore delivers the first end-to-end storage QoS to ensure the most important App or VM performance is never compromised. The storage grid, that uses Gridstore’s performance optimized nodes or capacity optimized nodes, starts with as few a...
SYS-CON Events announced today that Cloudian, Inc., the leading provider of hybrid cloud storage solutions, has been named “Bronze Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Cloudian is a Foster City, Calif.-based software company specializing in cloud storage. Cloudian HyperStore® is an S3-compatible cloud object storage platform that enables service providers and enterprises to build reliable, affordable and scalable hybrid cloud storage solutions. Cloudian actively partners with leading cloud computing environments including Amazon Web Services, Citrix Cloud Platform, Apache CloudStack, OpenStack and the vast ecosystem of S3 compatible tools and applications. Cloudian's customers include Vodafone, Nextel, NTT, Nifty, and LunaCloud. The company has additional offices in China and Japan.
SYS-CON Events announced today that TechXtend (formerly Programmer’s Paradise), a leading value-added provider of server and storage virtualization, and r-evolution will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TechXtend (formerly Programmer’s Paradise) is a leading value-added provider of software, systems and solutions for corporations, government organizations, and academic institutions across the United States and Canada. TechXtend is the Exclusive Reseller in the United States for r-evolution