In this tutorial, we are going to see a shopping cart example. In this example, we add products to the cart using drag and drop. In a previous tutorial, we have seen PHP shopping cart with jQuery AJAX.
In this example, we have draggable product items. We are adding these items to the cart by dragging and dropping them. The draggable product data can be transferred to PHP via an AJAX call to perform cart Actions.
A drag event object is used to access this data during the event handling.
It shows HTML code to display a list of product images with names and prices from the database. We can drag this image and drop it into the shopping cart DIV.
<?php
require_once("DataSource.php");
$db_handle = new DataSource();
?>
<HTML>
<HEAD>
<TITLE>PHP Shopping Cart with jQuery AJAX</TITLE>
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
...
</HEAD>
<BODY>
<div id="product-grid">
<div class="txt-heading">Products</div>
<?php
$product_array = $db_handle->select("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
?>
<div class="product-item" data-name="<?php echo $product_array[$key]["name"]; ?>" data-price="<?php echo "$".$product_array[$key]["price"]; ?>">
<div class="product-image"><img class="draggable" src="<?php echo $product_array[$key]["image"]; ?>" id="<?php echo $product_array[$key]["code"]; ?>"></div>
<div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
</div>
<?php
}
}
?>
</div>
<div class="clear-float"></div>
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart <a id="btnEmpty" onClick="cartAction('empty','');">Empty Cart</a></div>
<div id="cart-item"></div>
</div>
<script>
$(document).ready(function () {
cartAction('','');
})
</script>
</BODY>
</HTML>
This code is for handling add-to-cart with jQuery drag and drop. In the previous tutorial, we have seen how to move images using jQuery drag and drop.
This code gets a draggable image element id on drag. With the reference of this id, it triggers to add to cart AJAX action on the drop event to edit the cart item in the database.
$(document).ready(function() {
$('.draggable').on('dragstart', function(e){
var source_id = $(this).attr('id');
e.originalEvent.dataTransfer.setData("source_id", source_id);
});
$("#cart-item").on('dragenter', function (e){
e.preventDefault();
$(this).css('background', '#BBD5B8');
});
$("#cart-item").on('dragover', function (e){
e.preventDefault();
});
$("#cart-item").on('drop', function (e){
e.preventDefault();
$(this).css('background', '#FFFFFF');
var product_code = e.originalEvent.dataTransfer.getData('source_id');
cartAction('add',product_code);
});
});
This code calls AJAX request based on the cart action. It is to perform the add-to-cart, remove-cart-item and empty-the-cart as requested by the user.
function cartAction(action,product_code) {
var queryString = "";
if(action != "") {
switch(action) {
case "add":
queryString = 'action='+action+'&code='+ product_code;
break;
case "remove":
queryString = 'action='+action+'&code='+ product_code;
break;
case "empty":
queryString = 'action='+action;
break;
}
}
jQuery.ajax({
url: "ajax_action.php",
data:queryString,
type: "POST",
success:function(data){
$("#cart-item").html(data);
},
error:function (){}
});
}
This code includes PHP-side functions invoked for the AJAX request. It gives an input field to edit the quantity for the added cart item.
<?php
session_start();
require_once("DataSource.php");
$db_handle = new DataSource();
if(!empty($_POST["action"])) {
switch($_POST["action"]) {
case "add":
$query = "SELECT * FROM tblproduct WHERE code=?";
$paramType = "s";
$paramArray = array($_POST["code"]);
$productByCode = $db_handle->select($query, $paramType, $paramArray);
$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>'1', 'price'=>$productByCode[0]["price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["code"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_POST["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
?>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Price</strong></th>
<th><strong>Action</strong></th>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["code"]; ?></td>
<td><input name="quantity" value="<?php echo $item["quantity"]; ?>" size=3 onChange="calculateTotal(<?php echo $item["quantity"]; ?>,this.value,<?php echo $item["price"]; ?>);" /></td>
<td align=right><?php echo "$".$item["price"]; ?></td>
<td><a onClick="cartAction('remove','<?php echo $item["code"]; ?>')" class="btnRemoveAction cart-action">Remove Item</a></td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td colspan="5" align=right><strong>Total: </strong> $<div id="totalAmount" style="float:right;"><?php echo $item_total; ?></div></td>
</tr>
</tbody>
</table>
<?php
}
?>
After adding to the cart, we can change the item quantity. Based on the selected quantity, the total amount is calculated dynamically. The code is,
function calculateTotal(qty,qty_new,price) {
var total = $('#totalAmount').html();
total = parseInt(total) - (parseInt(qty)*parseInt(price));
total = parseInt(total) + (parseInt(qty_new)*parseInt(price));
$('#totalAmount').html(total);
}
This SQL script is to import the product database table and loads the demo data into it.
Import this SQL before running this code. It will show the product gallery on the landing page.
--
-- Database: `shopping_cart`
--
-- --------------------------------------------------------
--
-- Table structure for table `tblproduct`
--
CREATE TABLE `tblproduct` (
`id` int(8) NOT NULL,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`image` text NOT NULL,
`price` double(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tblproduct`
--
INSERT INTO `tblproduct` (`id`, `name`, `code`, `image`, `price`) VALUES
(1, 'FinePix 3D Camera', '3DcAM01', 'product-images/camera.jpg', 1500.00),
(2, 'EXP Hard Drive', 'USB02', 'product-images/external-hard-drive.jpg', 800.00),
(3, 'Ultra Wrist Watch', 'wristWear03', 'product-images/watch.jpg', 300.00);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tblproduct`
--
ALTER TABLE `tblproduct`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `product_code` (`code`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tblproduct`
--
ALTER TABLE `tblproduct`
MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;