Welcome!

AJAX & REA Authors: Scott Hirsch, David H Deans, Carmen Gonzalez, Pat Romanski, Aria Blog

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

@CloudExpo Stories
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: S...
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo, moderated by Ashar Baig, Research ...
In her General Session at 15th Cloud Expo, Anne Plese, Senior Consultant, Cloud Product Marketing, at Verizon Enterprise, will focus on finding the right mix of renting vs. buying Oracle capacity to scale to meet business demands, and offer validated Oracle database TCO models for Oracle development and testing environments. Anne Plese is a marketing and technology enthusiast/realist with over 19+ years in high tech. At Verizon Enterprise, she focuses on driving growth for the Verizon Cloud pla...
StackIQ offers a comprehensive software suite that automates the deployment, provisioning, and management of Big Infrastructure. With StackIQ’s software, you can spin up fully configured big data clusters, quickly and consistently — from bare-metal up to the applications layer — and manage them efficiently. Our software’s modular architecture allows customers to integrate nearly any application with the StackIQ software stack.
As Platform as a Service (PaaS) matures as a category, developers should have the ability to use the programming language of their choice to build applications and have access to a wide array of services. Bluemix is IBM's open cloud development platform that enables users to easily build cloud-based, creative mobile and web applications without having to spend large amounts of time and resources on configuring infrastructure and multiple software licenses. In this track, you will learn about the...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: ...
Compute virtualization has been transformational, yet security policy implementation and enforcement has lagged behind in agility and automation. There are a number of key considerations when implementing policy in private and hybrid clouds. In his session at 15th Cloud Expo, Holland Barry, VP of Technology at Catbird, will discuss the impact of this new paradigm and what organizations can do today to safely move to software-defined network and compute architectures, including: How normal ope...
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff hap...
SYS-CON Events announced today that SOA Software, an API management leader, 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. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accel...
SYS-CON Events announced today that Utimaco 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. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customiz...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
SYS-CON Events announced today that ElasticBox is holding a Hackathon at DevOps Summit, November 6 from 12 pm -4 pm at the Santa Clara Convention Center in Santa Clara, CA. You can enter as an individual or team of up to 10 developers. A New Star Is Born Every Month! All completed ElasticBoxes will then be sent to a judging panel - 12 winners will be featured on the ElasticBox website in 2015. All entrants will receive five full enterprise licenses for one year + ElasticBox headphones + Elasti...
Once the decision has been made to move part or all of a workload to the cloud, a methodology for selecting that workload needs to be established. How do you move to the cloud? What does the discovery, assessment and planning look like? What workloads make sense? Which cloud model makes sense for each workload? What are the considerations for how to select the right cloud model? And how does that fit in with the overall IT tranformation? In his session at 15th Cloud Expo, John Hatem, head of V...
Cloud services are the newest tool in the arsenal of IT products in the market today. These cloud services integrate process and tools. In order to use these products effectively, organizations must have a good understanding of themselves and their business requirements. In his session at 15th Cloud Expo, Brian Lewis, Principal Architect at Verizon Cloud, will outline key areas of organizational focus, and how to formalize an actionable plan when migrating applications and internal services to...
SAP is delivering break-through innovation combined with fantastic user experience powered by the market-leading in-memory technology, SAP HANA. In his General Session at 15th Cloud Expo, Thorsten Leiduck, VP ISVs & Digital Commerce, SAP, will discuss how SAP and partners provide cloud and hybrid cloud solutions as well as real-time Big Data offerings that help companies of all sizes and industries run better. SAP launched an application challenge to award the most innovative SAP HANA and SAP ...
Ixia develops amazing products so its customers can connect the world. Ixia helps its customers provide an always-on user experience through fast, secure delivery of dynamic connected technologies and services. Through actionable insights that accelerate and secure application and service delivery, Ixia's customers benefit from faster time to market, optimized application performance and higher-quality deployments.
SYS-CON Events announced today that Calm.io has been named “Bronze Sponsor” of DevOps Summit Silicon Valley, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Calm.io is a cloud orchestration platform for AWS, vCenter, OpenStack, or bare metal, that runs your CL tools puppet, Chef, shell, git, Jenkins, nagios, and will soon support New Relic and Docker. It can run hosted, or on premise and provides VM automation / expiry, self-service portals,...
SYS-CON Events announced today that Aria Systems, the recurring revenue expert, 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. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue bu...
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce t...
Blue Box has closed a $10 million Series B financing. The round was led by a strategic investor and included participation from prior investors including Voyager Capital and Founders Collective, as well as the Blue Box executive team. This round follows a $4.3 million Series A closed in December of 2012 and led by Voyager Capital. In May of this year, the company announced general availability of its private cloud as a service offering, Blue Box Cloud. Since that release, the company has dem...