http://www.ajaxlessons.com/2006/02/19/ajax-workshop-3-shopping-cart-using-scriptaculous/ 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. Here is what it looks like when complete
by Anna 안나 2008. 7. 6. 17:13