Ajax Workshop 3: Shopping Cart using Script.aculo.us
Filed Under (Lessons, Tutorials, Workshops) by admin on 19-02-2006
This workshop we will be building a shopping cart that’s Ajax powered. This will be a drag and drop shopping cart using the Script.aculo.us JavaScript library. We will also be using PHP on the back end to store the user’s shopping cart in sessions.
We will start this workshop off with the XHTML and CSS for the shopping cart and its products. Let’s take a look at the XHTML.
<div id="products"> <div style="float:left; font-weight:bold">Products</div> <div id="clearCart" onclick="clearCart();">Clear Cart</div> <div id="loading">Loading...</div> <br style="clear:both" /> <div class="box" id="product_1">1</div> <div class="box" id="product_2">2</div> <div class="box" id="product_3">3</div> <div class="box" id="product_4">4</div> <div class="box" id="product_5">5</div> <div class="box" id="product_6">6</div> </div> <div id="cart"> <div style="float:left; font-weight:bold">Shopping Cart</div> </div>
We start out with a product div; this div will hold all of our products. Inside the product div we have a new div for the product box label “Products”, a div to hold the clear cart button (which we attached an event to that will be discusses further in the workshop) and the loading status image. After we have a break tag with a clear:both this is needed because we floated the previous divs.
We then have the products with their class “box” and a unique id. The ID is what we will be passing to the server side to add the product to our shopping cart.
We then have the cart div. This is the actual shopping cart when you drag your products into to be saved server side.
Let’s take a look at the CSS now.
#cart { background-color:#FFFF66; border:dashed gray 1px; height:100px; width:500px; padding:5px; margin-top:10px; overflow: auto; } #products { background-color:#FFF; border:dashed gray 1px; height:100px; width:500px; padding:5px; } .box { background-color:#CCFF33; border:solid gray 1px; margin:10px; padding:4px; width:50px; height:50px; float:left; cursor:pointer; } #loading { display:none; float:right; } #clearCart { text-decoration:underline; cursor:pointer; float:right } #clearCart:hover { background-color:#CCFFCC; color:#000099; }
Nothing spectacular going on here for the most part, we are giving all of our divs some style, setting the height and width colors etc. Some things to point out are in the box class we are floating left so that the divs are horizontally aligned also we are setting display of the loading ID to none so that it’s not shown unless we are communicating with the server.
You should now have something that looks like this:

We now need to add the code for Script.aculo.us to create the drag and drop functionality. Add this code right before the closing of your body tag.
<script type="text/javascript"> var products = document.getElementsByClassName('box'); for (var i = 0; i < products.length; i++) { new Draggable(products[i].id, {ghosting:true, revert:true}) } Droppables.add('cart', {onDrop:addProduct}) </script>
The first thing we are doing is getting each product as an object so we can add the drag ability from Script.aculo.us. We do this by getting all elements with the class name of “box” in an array then looping through and creating a new Draggable with the ID of the element. There are also two parameters: ghosting:true and revert:true. Ghosting makes the element transparent while dragging and revert sends the element back to it’s starting position on mouse out.
We then make the cart div a droppable. What this does is allow us to catch the ID of which element was dropped and call a function. We set the onDrop parameter to onDrop:addProduct which means that when a draggable (product) is dropped on the droppable (cart) we call the function addProduct.
Let’s take a look at the JavaScript now that contains all of our functions.
function addProduct(element, dropon, event) { sendData(element.id); } function sendData (prod) { var url = 'cart.php'; var rand = Math.random(9999); var pars = 'product_id=' + prod + '&rand=' + rand; var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); } function clearCart () { var url = 'cart.php'; var rand = Math.random(9999); var pars = 'clear=true&rand=' + rand; var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); } function clearProduct (id) { var url = 'cart.php'; var rand = Math.random(9999); var pars = 'clearProduct=true&id=' + id + '&rand=' + rand; var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); } function showResponse (originalRequest) { $('loading').style.display = "none"; $('clearCart').style.display = "block"; $('cart').innerHTML = originalRequest.responseText; } function showLoad () { $('clearCart').style.display = "none"; $('loading').style.display = "block"; }
The first function we created addProduct is what is called when a product is added to the shopping cart. We then call another function sendData and pass the ID of the product that was dropped in the cart.
The next function sendData we send the product ID to the server to store in a SESSION. For more information using this function visit the previous workshops where we went into greater detail.
The clearCart and clearProduct functions are almost identical to the sendData function, but instead we are clearing the cart and clearing the product respectively in the server side SESSION.
The showResponse function is updating the shopping cart with products in the server side SESSION as well as hiding the loading div and showing the clear cart button.
The showLoad function hides the clear cart button and shows the loading status div.
Again we have covered all of these functions earlier in previous workshops.
Here is the complete XHTML, CSS and JavaScript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Ajax Workshop 3: Shopping Cart using Script.aculo.us</title> <script src="prototype.js" type="text/javascript"></script> <script src="scriptaculous.js" type="text/javascript"></script> <style media="screen" type="text/css"> body { font-family:"Trebuchet MS"; font-size:12px; } #cart { background-color:#FFFF66; border:dashed gray 1px; height:100px; width:500px; padding:5px; margin-top:10px; overflow: auto; } #products { background-color:#FFF; border:dashed gray 1px; height:100px; width:500px; padding:5px; } .box { background-color:#CCFF33; border:solid gray 1px; margin:10px; padding:4px; width:50px; height:50px; float:left; cursor:pointer; } #loading { display:none; float:right; } #clearCart { color:blue; text-decoration:underline; cursor:pointer; float:right } #clearCart:hover { background-color:#CCFFCC; color:#000099; } </style> <script language="javascript" type="text/javascript"> function addProduct(element, dropon, event) { sendData(element.id); } function sendData (prod) { var url = 'cart.php'; var rand = Math.random(9999); var pars = 'product_id=' + prod + '&rand=' + rand; var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); } function clearCart () { var url = 'cart.php'; var rand = Math.random(9999); var pars = 'clear=true&rand=' + rand; var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); } function clearProduct (id) { var url = 'cart.php'; var rand = Math.random(9999); var pars = 'clearProduct=true&id=' + id + '&rand=' + rand; var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); } function showResponse (originalRequest) { $('loading').style.display = "none"; $('clearCart').style.display = "block"; $('cart').innerHTML = originalRequest.responseText; } function showLoad () { $('clearCart').style.display = "none"; $('loading').style.display = "block"; } </script> </head> <body> <h1>Ajax Workshop 3: Shopping Cart using <a href="http://script.aculo.us">Script.aculo.us</a> </h1> <h2>Drag the products into the shopping cart</h2> <div id="products"> <div style="float:left; font-weight:bold">Products</div> <div id="clearCart" onclick="clearCart();">Clear Cart</div> <div id="loading"><img src="indicator.gif" alt="loading..." /></div> <br style="clear:both" /> <div class="box" id="product_1">1</div> <div class="box" id="product_2">2</div> <div class="box" id="product_3">3</div> <div class="box" id="product_4">4</div> <div class="box" id="product_5">5</div> <div class="box" id="product_6">6</div> </div> <div id="cart"> <div style="float:left; font-weight:bold">Shopping Cart</div> </div> <script type="text/javascript"> var products = document.getElementsByClassName('box'); for (var i = 0; i < products.length; i++) { new Draggable(products[i].id, {ghosting:true, revert:true}) } Droppables.add('cart', {onDrop:addProduct}) </script> </body> </html>
Time for the server side Cart.php.
<?php session_start(); function stringForJavascript($in_string) { $str = ereg_replace("[\r\n]", " \\n\\\n", $in_string); $str = ereg_replace('"', '\\"', $str); Return $str; } if (isset($_GET['clearProduct'])) { $_SESSION['cart'][$_GET['id']]--; if ($_SESSION['cart'][$_GET['id']] == 0) { unset($_SESSION['cart'][$_GET['id']]); } foreach ($_SESSION['cart'] as $key => $value) { print "$key = $value <span style=\"color:blue; text-decoration:underline; cursor:pointer\" onclick=\"clearProduct('$key');\">DELETE</span><br />"; } sleep(1); die; } if (isset($_GET['clear'])) { unset($_SESSION['cart']); sleep(1); die; } $prodid = $_GET['product_id']; $_SESSION['cart'][$prodid] = 1 + $_SESSION['cart'][$prodid]; foreach ($_SESSION['cart'] as $key => $value) { print "$key = $value <span style=\"color:blue; text-decoration:underline; cursor:pointer\" onclick=\"clearProduct('$key');\">DELETE</span><br />"; } sleep(1); ?>
We start off by calling the session_start() function which allow us to access and modify the SESSION global variable. We then have created a function for returning a string that JavaScript can read.
Next we are using a conditional statement to check whether we are adding a product, clearing the cart or removing a product. Depending on what action is called we manipulate the SESSION global variable and send back the contents of the shopping cart.
I am not going to cover all the basics of the SESSION global variable but if you like you can read up on it at http://php.net/session.










i can’t drag the Products her is my example : http://pligg.awardspace.com/cart/
very intersting lessons, thanks
Make sure that all of the Javascript files that were included with Script.aculo.us are included in the same directory as the main file.
I am in need of getting some ASP code instead of the PHP for the cart. Is there any way you can translate? Do you know of any sites that have ASP instead of PHP for the code?
I just cant seem to get it working.
Thank you for your time,
David
hey thanks so much
it has help me out on a project i’m doing very much.
mmm is there a way to keep track of what’s in the cart?
for example if I’ve left the shop cart page, then go back to it again. My items which I’ve chosen are still intact?
thanks for this tutorial
ahhh silly me… ok i think i know what i have misunderstood.
because the products aren’t in any picture format, so i wasnt able to see them in the cart when i refreshed. but when i refreshed and then add item, all those items which ived added before appeared.
sorry about that!!
hi. IM new to this so do bear :0
IM getting this error when i test it my local machine
$value) { print “$key = $value DELETE
“; } sleep(1); die; } if (isset($_GET['clear'])) { unset($_SESSION['cart']); sleep(1); die; } $prodid = $_GET['product_id']; $_SESSION['cart'][$prodid] = 1 + $_SESSION['cart'][$prodid]; foreach ($_SESSION['cart'] as $key => $value) { print “$key = $value DELETE
“; } sleep(1); ?>
got absolutely no idea where to begin deciphering this.
thanks for your time and help!
Hi people, this post is amazing but i’m looking forward to finding the code for ASP instead of PHP because i’m working with ASP.Net .I’d really appreciate your help, thanks in advance.
marquito
hi David, could you please help me out to have the Cart’s code for ASP instead of PHP.
thanks 4 ur time
hello
i use your code in my program , i get and javascript error :
‘DRAGABBLE’ is undefied !
but i include all javascripts tools/
my prptotype.js file version is 1.4
please help me , thx
hello
i complete this toturials by CART box not get any product !?
whats happend?
i can drag product and run all modules of cart.php but cartbox not drop anyprodoct ?!!!!
please help me , thx
hi,
I’m looking someone who can explain some capacibily of this scripts to control grag and drop ???
i need to built like a shopping card but when i drag n’drop i don’t want that system count the number of same produits and i want to control the association of produits - my products are journey (holidays for an tourism web site) and customer can’t add the same days in his basket …
Thanks
hi is it possible to make it onclick add to cart??
managed to get the add to cart to work but how do i get all the cart items through out various page or display the cart items when it is refreshed..
Hi,
i have tried to develop the sample shopping cart application as mentioned in script.aculo.us , managed to some extent.
when i drag an item over the droppable element , the ajax request is fired but what ever i m rendering in that controller that is not getting reflected . can anybody help me?
Thanks alot
When I add the first item to the cart I get the following error:
Notice: Undefined index: cart in /var/www/html/shopping/util/cart.php on line 25
This error goes away when I add another of the same product to the cart. Why is it doing this, and how can I resolve the problem?
My second question is similar to Malcolm’s. I use Ajax to call the different catalog pages within my main page, when I click to any of the other catalog pages, the items disappear from the cart until I add another. What do I need to do so that after adding an item it stays displayed unless I remove it or clear the cart?
Thank you!
Why sleep(1) in PHP?
Undefined index:cart in cart.php on line 25
i have the same problem
What can i do??¿?¿?
Amazing, IM going to use this right now
Thanks for this tutorial! This tutorial taught me two things, ajax shopping cart and PHP since I needed this code for coldfusion.
Nice tutorial exept the fact that THIS SHIT AIN’T WORKIN’ at least the JS it outputs some errors as mentioned in above comments. Strange, the example is OK but when you download it outputs errors. Any fix suggestions.
Good article
“managed to get the add to cart to work but how do i get all the cart items through out various page or display the cart items when it is refreshed.”
–
Hi, did you ever work this out? I have tried adding, and then removing an item using , but with no luck. Pretty messy anyway.
Anyone have any ideas?
Thanks
Tom.
Ok worked it out (mod feel free to adjust the reply so it makes more sense!).
Firstly itll only work if you’re using the cart on a PHP page. You need to add session_start() to the top.
Then, within the cart div, add
foreach ($_SESSION['cart'] as $key => $value) {
print “$key = $value DELETE”;
}
Done.
hi all this is a great tutorial i wish i read it before i done the cart in PHP
i wanted to ask is there a way to delete the revert effect after droping item t the box ??? (like after dropping the item we are still holding will be disapear insted of returning to its position like http://www.panic.com/goods )
Thank you
PHP is not the acronym of HyperText PreProcessing.
PHP means : Php: HyperText Processor.
omg
You are the man. The article is great and it has helped me alot. Keep it up!
PAMOJA!!
hiiiiiiiii…………
Thank you thanks a lot…for the script….it is working …good work ….thanx again..