PHP Shopping Cart with jQuery AJAX

In this article add to cart functionality work using ajax and php session,so add to cart work without page refresh ,with delete item from cart using ajax.

Code Written in php and jquery easy logic work in three phase add,remove,and empty cart for this three jquery work with ajax call.

Create Database ajax_script

CREATE TABLE IF NOT EXISTS `product` (
  `product_id` int(20) NOT NULL AUTO_INCREMENT,
  `product_title` varchar(150) NOT NULL,
  `product_desc` text NOT NULL,
  `product_brand` varchar(100) NOT NULL,
  `product_price` decimal(12,2) NOT NULL,
  `product_image` varchar(100) NOT NULL,
  `product_status` enum('0','1') NOT NULL COMMENT '0-active,1-inactive',
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;


INSERT INTO `product` (`product_id`, `product_title`, `product_desc`, `product_brand`, `product_price`, `product_image`, `product_status`) VALUES
(1, 'Vagitable', 'This is best Vagitable', 'test brand', '200.00', 'intro_cream_of_crop.jpg', '1'),
(2, 'Broccoli', 'Broccoli is best in test', 'new brand', '250.00', 'broccoli.jpg', '1'),
(3, 'cucumbers', 'Friesh cucumbers for saled', 'test brand', '150.00', 'cucumbers.jpg', '1'),
(4, 'carrots', 'carrots is testy', 'new brand', '300.00', 'carrots.jpg', '1');

confing.php

<?php 
session_start();
$conn  = @mysql_connect("localhost","root","");
mysql_select_db("ajax_script",$conn);
?>

index.php

<?php include"confing.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Add to Cart in php using ajax</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
	<div class="row">
  <div class="col-sm-12" ><>
		<nav class="navbar navbar-default navbar-fixed-top">
		<div class="container-fluid">
		  <div class="navbar-header">
			<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
			  <span class="sr-only">Toggle navigation</span>
			  <span class="icon-bar"></span>
			  <span class="icon-bar"></span>
			  <span class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="#">Add To Cart Example</a>
		  </div>
		  
		  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">	  
			<ul class="nav navbar-nav navbar-right" style="margin-right:5%;" >
			  <li class="dropdown cart_data"  >
				<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <img src="cart.png" style="width:40px" > 0 - Items<span class="caret"></span></a>
			  </li>
			</ul>
		  </div>
		</div>
	  </nav>
  </div>
   </div> 
  
 <div class="row content" style="padding-top:2%;" >  
    <div class="col-sm-12">
	   <h2>add to cart in php using session and jquery</h2>
	  <hr/>
	  <div class="container">
    <div class="row">
	
	<?php 
	$query = "select * from product";
	$rs = mysql_query($query,$conn) or die("failed".mysql_error());
	while($data = mysql_fetch_assoc($rs)){
	?>
        <div class="col-md-3">
              <div class="thumbnail">
                <img src="images/<?php echo $data['product_image']; ?>" alt="" class="img-responsive">
                <div class="caption">
                  <h4 class="pull-right"><?php echo $data['product_price']; ?></h4>
                  <h4><a href="#">Vagitable</a></h4>
                  <p><?php echo $data['product_desc']; ?></p>
                </div>
                <div class="ratings" style="text-align:center;" >
                  Quantity:  <input type="number" class="quantity<?php echo $data['product_id']; ?>" min="1"  style="max-width:50px;" value="1" >
                </div>
				<br />
                <div class="space-ten"></div>
                <div class="btn-ground text-center">
				    
                    <button type="button" class="btn btn-primary" onclick="add_cart('<?php echo $data['product_id']; ?>')" ><i class="fa fa-shopping-cart"></i> Add To Cart</button>
                   
                </div>
                <div class="space-ten"></div>
              </div>
            </div>
	<?php } ?>
    </div>
</div>
    </div>
  </div>
</div>

<script>

function add_cart(p_id=""){
	var quantity = $(".quantity"+p_id).val();
	$.ajax({
		type:"post",
		url:"ajax.php",
		data:{action:'add',p_id:p_id,quantity:quantity},
		success:function(result){
			$('.cart_data').html(result);
		}
	});
}


add_cart();
function remove_cart(p_id){
	//alert(p_id);
	$.ajax({
		type:"post",
		url:"ajax.php",
		data:{action:'delete',p_id:p_id},
		success:function(result){
			$('.cart_data').html(result);
		}
	});
}
function empty_cart(){
	$.ajax({
		type:"post",
		url:"ajax.php",
		data:{action:'empty'},
		success:function(result){
			$('.cart_data').html(result);
		}
	});
}

</script>
</body>
</html>

ajax.php

<?php
include"confing.php";
$action = $_REQUEST['action'];
@$p_id = trim($_REQUEST['p_id']);
//$_SESSION['product_cart'] = array();
if ($action == 'add') {
	@$quantity = $_REQUEST['quantity'];
	if (!empty($p_id)) {
		$query = "select * from product where product_id = '" . $p_id . "'";
		$rs = mysql_query($query, $conn) or die("failed" . mysql_error());
		$product_data = mysql_fetch_assoc($rs);

		$product = array("p_id" => $product_data['product_id'], "title" => $product_data['product_title'], "price" => $product_data['product_price'] * $quantity, "image" => $product_data['product_image'], "quantity" => $quantity);

		if (isset($_SESSION['product_cart']) && !empty($_SESSION['product_cart'])) {
			if (!array_key_exists($product_data['product_id'], $_SESSION['product_cart'])) {

				$_SESSION['product_cart'][$product_data['product_id']] = $product;
			} else {

				$_SESSION['product_cart'][$product_data['product_id']]['price'] = $_SESSION['product_cart'][$product_data['product_id']]['price'] + ($product_data['product_price'] * $quantity);
				$_SESSION['product_cart'][$product_data['product_id']]['quantity'] = $_SESSION['product_cart'][$product_data['product_id']]['quantity'] + $quantity;
			}
		} else {
			$_SESSION['product_cart'][$product_data['product_id']] = $product;
		}
	}
}
if ($action == "delete") {
	unset($_SESSION['product_cart'][$p_id]);
}

if ($action == "empty") {
	session_destroy();
}
?>

<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <img src="cart.png" style="width:40px" > <?php echo count(@$_SESSION['product_cart']); ?> - Items<span class="caret"></span></a>
<ul class="dropdown-menu dropdown-cart" role="menu">
<?php
if (isset($_SESSION['product_cart'])) {
	foreach ($_SESSION['product_cart'] as $data) {
		?>
			<li>
				<span class="item">
					<span class="item-left" style="color:#0000" >
						<img src="images/<?php echo $data['image']; ?>" alt="" style="width:60px;" />
						<span class="item-info" style="color:#000;" >
							<span><?php echo $data['title']; ?></span>
							<span>Quantity : <?php echo $data['quantity']; ?></span>
							<span>Price : <?php echo $data['price']; ?> INR</span>
						</span>
					</span>
					<span class="item-right">
						<button class="btn btn-xs btn-danger pull-right" onclick="remove_cart('<?php echo $data['p_id']; ?>')" >x</button>
					</span>
				</span>
			</li>
	<?php }
} ?>
	<li class="divider"></li>
	<li><a class="text-center" href="">View Cart</a></li>
	<li><a class="text-center" href="#" onclick="empty_cart();" >Empty Cart</a></li>

Leave a Reply

Your email address will not be published. Required fields are marked *