Monday 5 November 2018

Shopping Cart with Add Bulk Item into Cart using PHP Ajax



If you have seen eCommerce Website or Online stores sites, If it is user friendly, then it will increase conversion and websites usability. One small feature of your website will stand you top and it will convert into profitability. This is because all revenue of your website comes from buyer or users of websites, If your online shopping cart has some feature that are very useful to user and user friendly, user can easily understand and it's decrease user efforts for place an order on your website, then your website revenue will jump to high. For this we have to give some features to our shopping cart and decrease the flow of process, so buyer can easily use our website. For this here we have discuss one features for shopping cart, which will decrease Buyers efforts for place an order, an that feature is add multiple or bulk item into Shopping cart.

Now question arise how can buyer can add bulk or multiple product into his Shopping cart by single click. Here we will make simple script using PHP with Ajax in which we have step by step describe how user can add bulk product into Shopping cart by single click. For this we have use use Checkbox selection, by checkboxes user can select multiple item which he want to add into cart, once all item has been selected, then he can click on Add to cart button. Once he has click on add to cart button, all selected item will be added into his cart. This feature will improve our shopping cart output, before we have to click on single item add to cart button, then that product will be added into cart. For multiple product add into cart we have to click multiple time Add to cart button for add multiple product into Shopping cart. But this type of functionality will decrease the click on Add to cart button, and in single click all item has been added into Shopping Cart.

Add multiple or Bulk product into Shopping Cart using PHP with Ajax we are make here. In this post first we will load all product details from Mysql database and display on web page using Ajax request with PHP script. On product load, you can find checkbox selection for select multiple item. After this we have use PHP with Ajax for display shopping cart details. Here we have use PHP SESSION variable for store shopping cart details. So, this shopping cart detail we can fetch all pages of website and this details will not be remove on accidental page refresh. By Ajax with PHP script, it will fetch shopping cart details for SESSION variable and display on web page with single item remove button and clear shopping cart button. Buyer can select multiple or Bulk item for add into his cart. Once all item has been selected then all he can click on Add to cart button, and all item added into cart. If same item has been again add into cart, then that item quantity will be automatically increase. Here user can remove single item or all item from shopping cart. So, this is simple tutorial on Shopping cart with Add multiple product into Cart using PHP with Ajax. Below you can find complete source code of this tutorial.






Source Code


Database



--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_product`
--

CREATE TABLE IF NOT EXISTS `tbl_product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  `price` double(10,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--
-- Dumping data for table `tbl_product`
--

INSERT INTO `tbl_product` (`id`, `name`, `image`, `price`) VALUES
(1, 'Samsung J2 Pro', '1.jpg', 100.00),
(2, 'HP Notebook', '2.jpg', 299.00),
(3, 'Panasonic T44 Lite', '3.jpg', 125.00);


index.php



<?php
//index.php
?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Ajax Shopping Cart by using Bootstrap Popover</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center"><a href="#">PHP Ajax Shopping Cart with Add Multiple Item into Cart</a></h3>
   <br />
   
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">Cart Details</div>
      <div class="col-md-6" align="right">
       <button type="button" name="clear_cart" id="clear_cart" class="btn btn-warning btn-xs">Clear</button>
      </div>
     </div>
    </div>
    <div class="panel-body" id="shopping_cart">

    </div>
   </div>

   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">Product List</div>
      <div class="col-md-6" align="right">
       <button type="button" name="add_to_cart" id="add_to_cart" class="btn btn-success btn-xs">Add to Cart</button>
      </div>
     </div>
    </div>
    <div class="panel-body" id="display_item">

    </div>
   </div>
  </div>
 </body>
</html>

<script>  
$(document).ready(function(){

 load_product();

 load_cart_data();
    
 function load_product()
 {
  $.ajax({
   url:"fetch_item.php",
   method:"POST",
   success:function(data)
   {
    $('#display_item').html(data);
   }
  });
 }

 function load_cart_data()
 {
  $.ajax({
   url:"fetch_cart.php",
   method:"POST",
   success:function(data)
   {
    $('#shopping_cart').html(data);
   }
  });
 }

 $(document).on('click', '.select_product', function(){
  var product_id = $(this).data('product_id');
  if($(this).prop('checked') == true)
  {
   $('#product_'+product_id).css('background-color', '#f1f1f1');
   $('#product_'+product_id).css('border-color', '#333');
  }
  else
  {
   $('#product_'+product_id).css('background-color', 'transparent');
   $('#product_'+product_id).css('border-color', '#ccc');
  }
 });

 $('#add_to_cart').click(function(){
  var product_id = [];
  var product_name = [];
  var product_price = [];
  var action = "add";
  $('.select_product').each(function(){
   if($(this).prop('checked') == true)
   {
    product_id.push($(this).data('product_id'));
    product_name.push($(this).data('product_name'));
    product_price.push($(this).data('product_price'));
   }
  });

  if(product_id.length > 0)
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price, action:action},
    success:function(data)
    {
     $('.select_product').each(function(){
      if($(this).prop('checked') == true)
      {
       $(this).attr('checked', false);
       var temp_product_id = $(this).data('product_id');
       $('#product_'+temp_product_id).css('background-color', 'transparent');
       $('#product_'+temp_product_id).css('border-color', '#ccc');
      }
     });

     load_cart_data();
     alert("Item has been Added into Cart");
    }
   });
  }
  else
  {
   alert('Select atleast one item');
  }

 });

 $(document).on('click', '.delete', function(){
  var product_id = $(this).attr("id");
  var action = 'remove';
  if(confirm("Are you sure you want to remove this product?"))
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{product_id:product_id, action:action},
    success:function()
    {
     load_cart_data();
     alert("Item has been removed from Cart");
    }
   })
  }
  else
  {
   return false;
  }
 });

 $(document).on('click', '#clear_cart', function(){
  var action = 'empty';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{action:action},
   success:function()
   {
    load_cart_data();
    alert("Your Cart has been clear");
   }
  });
 });
    
});

</script>




database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=test", "root", "");

?>


fetch_item.php



<?php

//fetch_item.php

include('database_connection.php');

$query = "SELECT * FROM tbl_product ORDER BY id DESC";

$statement = $connect->prepare($query);

if($statement->execute())
{
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  $output .= '
  <div class="col-md-3" style="margin-top:12px;margin-bottom:12px;">  
            <div style="border:1px solid #ccc; border-radius:5px; padding:16px; height:300px;" align="center" id="product_'.$row["id"].'">
             <img src="images/'.$row["image"].'" class="img-responsive" /><br />
             <h4 class="text-info">
                        <div class="checkbox">
                              <label><input type="checkbox" class="select_product" data-product_id="'.$row["id"].'" data-product_name="'.$row["name"].'" data-product_price="'.$row["price"] .'" value="">'.$row["name"].'</label>
                        </div>
                  </h4>
             <h4 class="text-danger">$ '.$row["price"] .'</h4>
            </div>
        </div>
  ';
 }
 echo $output;
}

/*$output = '
<div class="col-md-3" style="margin-top:12px;">  
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
            <img src="https://image.ibb.co/jSR5Mn/1.jpg" class="img-responsive"><br>
            <h4 class="text-info">Samsung J2 Pro</h4>
            <h4 class="text-danger">$ 100.00</h4>
            <input type="text" name="quantity" id="quantity1" class="form-control" value="1">
            <input type="hidden" name="hidden_name" id="name1" value="Samsung J2 Pro">
            <input type="hidden" name="hidden_price" id="price1" value="100.00">
            <input type="button" name="add_to_cart" id="1" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart">
      </div>
</div>
            
            
            <div class="col-md-3" style="margin-top:12px;">  
            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
                  <img src="https://image.ibb.co/mt5zgn/3.jpg" class="img-responsive"><br>
                  <h4 class="text-info">Panasonic T44 Lite</h4>
                  <h4 class="text-danger">$ 125.00</h4>
                  <input type="text" name="quantity" id="quantity3" class="form-control" value="1">
                  <input type="hidden" name="hidden_name" id="name3" value="Panasonic T44 Lite">
                  <input type="hidden" name="hidden_price" id="price3" value="125.00">
                  <input type="button" name="add_to_cart" id="3" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart">
            </div>
        </div>
            
            
            <div class="col-md-3" style="margin-top:12px;">  
            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
                  <img src="https://image.ibb.co/b57C1n/2.jpg" class="img-responsive"><br>
                  <h4 class="text-info">HP Notebook</h4>
                  <h4 class="text-danger">$ 299.00</h4>
                  <input type="text" name="quantity" id="quantity2" class="form-control" value="1">
                  <input type="hidden" name="hidden_name" id="name2" value="HP Notebook">
                  <input type="hidden" name="hidden_price" id="price2" value="299.00">
                  <input type="button" name="add_to_cart" id="2" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart">
            </div>
        </div><div class="col-md-3" style="margin-top:12px;">  
            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
                  <img src="https://image.ibb.co/eDhqnS/4.jpg" class="img-responsive"><br>
                  <h4 class="text-info">Wrist Watch</h4>
                  <h4 class="text-danger">$ 85.00</h4>
                  <input type="text" name="quantity" id="quantity4" class="form-control" value="1">
                  <input type="hidden" name="hidden_name" id="name4" value="Wrist Watch">
                  <input type="hidden" name="hidden_price" id="price4" value="85.00">
                  <input type="button" name="add_to_cart" id="4" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart">
            </div>
        </div>
';

echo $output;*/

?>


fetch_cart.php



<?php

//fetch_cart.php

session_start();

$total_price = 0;
$total_item = 0;

$output = '
<div class="table-responsive" id="order_table">
 <table class="table table-bordered table-striped">
  <tr>  
            <th width="40%">Product Name</th>  
            <th width="10%">Quantity</th>  
            <th width="20%">Price</th>  
            <th width="15%">Total</th>  
            <th width="5%">Action</th>  
        </tr>
';
if(!empty($_SESSION["shopping_cart"]))
{
 foreach($_SESSION["shopping_cart"] as $keys => $values)
 {
  $output .= '
  <tr>
   <td>'.$values["product_name"].'</td>
   <td>'.$values["product_quantity"].'</td>
   <td align="right">$ '.$values["product_price"].'</td>
   <td align="right">$ '.number_format($values["product_quantity"] * $values["product_price"], 2).'</td>
   <td><button name="delete" class="btn btn-danger btn-xs delete" id="'. $values["product_id"].'">Remove</button></td>
  </tr>
  ';
  $total_price = $total_price + ($values["product_quantity"] * $values["product_price"]);
  //$total_item = $total_item + 1;
 }
 $output .= '
 <tr>  
        <td colspan="3" align="right">Total</td>  
        <td align="right">$ '.number_format($total_price, 2).'</td>  
        <td></td>  
    </tr>
 ';
}
else
{
 $output .= '
    <tr>
     <td colspan="5" align="center">
      Your Cart is Empty!
     </td>
    </tr>
    ';
}
$output .= '</table></div>';

echo $output;
//echo '<pre>';
//print_r($_SESSION["shopping_cart"]);
//echo '</pre>';


?>


action.php



<?php

//action.php

session_start();

if(isset($_POST["action"]))
{
 if($_POST["action"] == "add")
 {
  $product_id = $_POST["product_id"];
  $product_name = $_POST["product_name"];
  $product_price = $_POST["product_price"];
  for($count = 0; $count < count($product_id); $count++)
  {
   $cart_product_id = array_keys($_SESSION["shopping_cart"]);
   if(in_array($product_id[$count], $cart_product_id))
   {
    $_SESSION["shopping_cart"][$product_id[$count]]['product_quantity']++;
   }
   else
   {
    $item_array = array(
     'product_id'               =>     $product_id[$count],  
     'product_name'             =>     $product_name[$count],
     'product_price'            =>     $product_price[$count],
     'product_quantity'         =>     1
    );

    $_SESSION["shopping_cart"][$product_id[$count]] = $item_array;

    
   }
  }
 }

 if($_POST["action"] == 'remove')
 {
  foreach($_SESSION["shopping_cart"] as $keys => $values)
  {
   if($values["product_id"] == $_POST["product_id"])
   {
    unset($_SESSION["shopping_cart"][$keys]);
   }
  }
 }
 if($_POST["action"] == 'empty')
 {
  unset($_SESSION["shopping_cart"]);
 }
}

?>

11 comments: