PHP Shopping Cart by jQuery Drag and Drop

In this tutorial, we are going to see a shopping cart example. In this example, we are adding products to cart by using drag and drop. In a previous tutorial, we have seen PHP shopping cart with jQuery AJAX.

In this example, we are having draggable product items. We are adding these items to cart by dragging and dropping. The draggable product data can be transferred to PHP via an AJAX call to perform cart Actions. Drag event object is used to access this data during the event handlings.

View Demo

Draggable Product Image HTML

It shows HTML code to display a list of product images with name and price from the database. We can drag this image and drop into the shopping cart DIV.

<div id="product-grid">
	<div class="txt-heading">Products</div>
	<?php
	$product_array = $db_handle->runQuery("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>

jQuery Drag and Drop add-to-cart Action

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 draggable image element id on drag. With the reference of this id, it triggers addtocart AJAX action on drop event to update 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);
	});
});

jQuery AJAX Cart Action

This code calls AJAX request base on the cart action(add-to-cart, remove-cart-item, empty-cart) 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 (){}
	});
}

PHP Shopping Cart Actions

This code includes PHP side functions invoked for the AJAX request. It gives input field to edit the quantity for the added cart item.

<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();

if(!empty($_POST["action"])) {
switch($_POST["action"]) {
	case "add":
		$productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_POST["code"] . "'");
		$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 cart we can change 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);
}

View DemoDownload

This PHP code tutorial was published on September 20, 2015.

↑ Back to Top