Showing posts with label php shopping cart. Show all posts
Showing posts with label php shopping cart. Show all posts

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"]);
 }
}

?>

Thursday, 30 August 2018

Create Shopping Cart Application using AngularJS with PHP



In this post we have will make simple online shopping cart application by using AngularJS with PHP script. Here we have use PHP script from make shopping cart app in AngularJS, because AngularJS is a client front-end web application development javascript framework. So, if buyer has add some product into cart then product will be store under shopping cart, but if buyer has refresh web page then all shopping cart data will be lost, so here when again user visit shopping cart page then he can view product which he has added into cart. For this here we have use PHP script with AngularJS for developing simple shopping cart application. In this application we have use PHP SESSION variable for store shopping cart data and this data will be access across the site. So, if page refresh or buyer close site and again go to shopping cart site then he can view all product which he had added into cart.

This is simple web application in which buyer can add product into shopping cart which he want to buy from list of product and he can view shopping cart details like which product he has added into cart with all product details like name, price, quantity and remove button. Here for make shopping cart we have use AngularJS to implement some basic task like add product into cart, remove product from cart. For this all shopping cart operation we have use AngularJS as front-end development and for back-end we have use PHP script.









Load Product using AngularJS with PHP


In AngularJS Shopping cart application first we want to load product on web page with Add to cart button. Here we have store product details under Mysql database, so below you can find in javascript code in which we have make one loadProduct() function. This function send Ajax request to PHP script for fetch data from Mysql database and PHP script will send back product data to Ajax request which we have store under $scope.product expression and by using ng-repeat directive we have display on web page. But we want to called this function on page load, so by using ng-init directive we have add this loadProduct() function, this directive will called this function when page has been load into browser and it will list product on web page. Below you can find source code for this.





index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart using AngularJS</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container" ng-app="shoppingCart" ng-controller="shoppingCartController" ng-init="loadProduct()">
   <br />
   <h3 align="center">PHP Shopping Cart using AngularJS</h3>
   <br />
   <form method="post">
    <div class="row">
     <div class="col-md-3" style="margin-top:12px;" ng-repeat = "product in products">
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
       <img ng-src="images/{{product.image}}" class="img-responsive" /><br />
       <h4 class="text-info">{{product.name}}</h4>
       <h4 class="text-danger">{{product.price}}</h4>
       <input type="button" name="add_to_cart" style="margin-top:5px;" class="btn btn-success form-control" value="Add to Cart" ng-click="addtoCart(product)" />
      </div>
     </div>
    </div>
   </form>
  </div>
 </body>
</html>

<script>

var app = angular.module('shoppingCart', []);

app.controller('shoppingCartController', function($scope, $http){
 
 $scope.loadProduct = function(){
  $http.get('fetch.php').success(function(data){
                      $scope.products = data;
                })
 };
 
});
</script>


fetch.php



<?php

//fetch.php

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

$query = "SELECT * FROM tbl_product";
$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
 $data[] = $row;
}

echo json_encode($data);

?>


Load Cart Details using AngularJS with PHP


Once all product has been display on web page by using AngularJS with PHP. Now we want to display buyer shopping cart details on web page using AngularJS with PHP. For this we have make fetchCart() AngularJS function. This function has send ajax request to fetch_cart.php page. Under this fetch_cart.php file script has been fetch data from $_SESSION variable. Here we have use PHP $_SESSION variable for store shopping cart data. So php script will convert this $_SESSION variable data into json string by using json_encode() function return back ajax success function which has been store under $scope.carts expression.

Now we want to display cart details on web page in table format, for this we have use ng-repeat directive. By using this directive it will display shopping cart details on web page. Now we want to display total of whole shopping cart at then end of cart. For this we have make new function setTotals(). This function will return total of whole shopping cart and total will be display in shopping cart. Lastly we want to load cart details on web page load. So this function also we have add into ng-init directive. So when page has been load this function will be called and buyer can see his shopping cart details on web page load.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart using AngularJS</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container" ng-app="shoppingCart" ng-controller="shoppingCartController" ng-init="loadProduct(); fetchCart();">
   <br />
   <h3 align="center">PHP Shopping Cart using AngularJS</h3>
   <br />
   <form method="post">
    <div class="row">
     <div class="col-md-3" style="margin-top:12px;" ng-repeat = "product in products">
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
       <img ng-src="images/{{product.image}}" class="img-responsive" /><br />
       <h4 class="text-info">{{product.name}}</h4>
       <h4 class="text-danger">{{product.price}}</h4>
       <input type="button" name="add_to_cart" style="margin-top:5px;" class="btn btn-success form-control" value="Add to Cart" ng-click="addtoCart(product)" />
      </div>
     </div>
    </div>
   </form>
   <br />
   <h3 align="center">Your Cart Details</h3>
   <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>
     <tr ng-repeat = "cart in carts">
      <td>{{cart.product_name}}</td>
      <td>{{cart.product_quantity}}</td>
      <td>{{cart.product_price}}</td>
      <td>{{cart.product_quantity * cart.product_price}}</td>
      <td><button type="button" name="remove_product" class="btn btn-danger btn-xs" ng-click="removeItem(cart.product_id)">Remove</button></td>
     </tr>
     <tr>
      <td colspan="3" align="right">Total</td>
      <td colspan="2">{{ setTotals() }}</td>
     </tr>
    </table>
   </div>
  </div>
 </body>
</html>

<script>

var app = angular.module('shoppingCart', []);

app.controller('shoppingCartController', function($scope, $http){
 
 $scope.loadProduct = function(){
  $http.get('fetch.php').success(function(data){
            $scope.products = data;
        })
 };
 
 $scope.carts = [];
 
 $scope.fetchCart = function(){
  $http.get('fetch_cart.php').success(function(data){
            $scope.carts = data;
        })
 };
 
 $scope.setTotals = function(){
  var total = 0;
  for(var count = 0; count<$scope.carts.length; count++)
  {
   var item = $scope.carts[count];
   total = total + (item.product_quantity * item.product_price);
  }
  return total;
 };
 
});

</script>


fetch_cart.php



<?php

//fetch_cart.php

session_start();

if(isset($_SESSION["shopping_cart"]))
{
 echo json_encode($_SESSION["shopping_cart"]); 
}


?>


Add Item into Cart using AngularJS with PHP


This is main task of shopping cart, how to add product or item add into cart using AngularJS with PHP. For this also we have make AngularJS function, this function has been called by using ng-click directive which we have use with Add to cart button. So when buyer has click particular product add to cart button then it will called addtoCart() function using ng-click directive. Under this function it has send product details get from addtoCart() function argument in array format using Ajax request send to add_item.php script.

At PHP script side data has been received json format and that data has been get using file_get_contents() and by using json_decode() function it has been converted into PHP array object. After this it will make new $_SESSION variable if buyer add first item and add product details under that session variable in array format. But suppose buyer already added same item into cart then only particular item quantity will be increase.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart using AngularJS</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container" ng-app="shoppingCart" ng-controller="shoppingCartController" ng-init="loadProduct(); fetchCart();">
   <br />
   <h3 align="center">PHP Shopping Cart using AngularJS</h3>
   <br />
   <form method="post">
    <div class="row">
     <div class="col-md-3" style="margin-top:12px;" ng-repeat = "product in products">
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
       <img ng-src="images/{{product.image}}" class="img-responsive" /><br />
       <h4 class="text-info">{{product.name}}</h4>
       <h4 class="text-danger">{{product.price}}</h4>
       <input type="button" name="add_to_cart" style="margin-top:5px;" class="btn btn-success form-control" value="Add to Cart" ng-click="addtoCart(product)" />
      </div>
     </div>
    </div>
   </form>
   <br />
   <h3 align="center">Your Cart Details</h3>
   <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>
     <tr ng-repeat = "cart in carts">
      <td>{{cart.product_name}}</td>
      <td>{{cart.product_quantity}}</td>
      <td>{{cart.product_price}}</td>
      <td>{{cart.product_quantity * cart.product_price}}</td>
      <td><button type="button" name="remove_product" class="btn btn-danger btn-xs" ng-click="removeItem(cart.product_id)">Remove</button></td>
     </tr>
     <tr>
      <td colspan="3" align="right">Total</td>
      <td colspan="2">{{ setTotals() }}</td>
     </tr>
    </table>
   </div>
  </div>
 </body>
</html>

<script>

var app = angular.module('shoppingCart', []);

app.controller('shoppingCartController', function($scope, $http){
 
 $scope.loadProduct = function(){
  $http.get('fetch.php').success(function(data){
            $scope.products = data;
        })
 };
 
 $scope.carts = [];
 
 $scope.fetchCart = function(){
  $http.get('fetch_cart.php').success(function(data){
            $scope.carts = data;
        })
 };
 
 $scope.setTotals = function(){
  var total = 0;
  for(var count = 0; count<$scope.carts.length; count++)
  {
   var item = $scope.carts[count];
   total = total + (item.product_quantity * item.product_price);
  }
  return total;
 };
 
 $scope.addtoCart = function(product){
  $http({
            method:"POST",
            url:"add_item.php",
            data:product
        }).success(function(data){
   $scope.fetchCart();
        });
 };
 
});

</script>


add_item.php



<?php

//add_item.php

session_start();
$product_data = json_decode(file_get_contents("php://input"));
$product_id = $product_data->id;
$product_name = $product_data->name;
$product_price = $product_data->price;

if(isset($_SESSION["shopping_cart"]))
{
 $is_available = 0;
 foreach($_SESSION["shopping_cart"] as $keys => $values)
 {
  if($_SESSION["shopping_cart"][$keys]['product_id'] == $product_id)
  {
   $is_available++;
   $_SESSION["shopping_cart"][$keys]['product_quantity'] = $_SESSION["shopping_cart"][$keys]['product_quantity'] + 1;
  }
 }
 if($is_available == 0)
 {
  $item_array = array(
   'product_id'               =>     $product_id,  
   'product_name'             =>     $product_name,  
   'product_price'            =>     $product_price,  
   'product_quantity'         =>     1
  );
  $_SESSION["shopping_cart"][] = $item_array;
 }
}
else
{
 $item_array = array(
  'product_id'               =>     $product_id,  
  'product_name'             =>     $product_name,  
  'product_price'            =>     $product_price,  
  'product_quantity'         =>     1
 );
 $_SESSION["shopping_cart"][] = $item_array;
 
}
//print_r($_SESSION["shopping_cart"]);

?>


Remove Item From Cart using AngularJS with PHP


Lastly in AngularJS Shopping Cart application we want to see how can buyer can remove item from shopping cart. For this also we have create one removeItem() function. This function will remove particular product item from shopping cart when buyer click on remove button of particular item in shopping cart. This function has been called by using ng-click event of remove button. This function has send Ajax request to remove_item.php script and this script will be remove particular item from $_SESSION variable based on value of id using PHP unset() function and after removing remaining shopping cart details on web page.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart using AngularJS</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container" ng-app="shoppingCart" ng-controller="shoppingCartController" ng-init="loadProduct(); fetchCart();">
   <br />
   <h3 align="center">PHP Shopping Cart using AngularJS</h3>
   <br />
   <form method="post">
    <div class="row">
     <div class="col-md-3" style="margin-top:12px;" ng-repeat = "product in products">
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
       <img ng-src="images/{{product.image}}" class="img-responsive" /><br />
       <h4 class="text-info">{{product.name}}</h4>
       <h4 class="text-danger">{{product.price}}</h4>
       <input type="button" name="add_to_cart" style="margin-top:5px;" class="btn btn-success form-control" value="Add to Cart" ng-click="addtoCart(product)" />
      </div>
     </div>
    </div>
   </form>
   <br />
   <h3 align="center">Your Cart Details</h3>
   <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>
     <tr ng-repeat = "cart in carts">
      <td>{{cart.product_name}}</td>
      <td>{{cart.product_quantity}}</td>
      <td>{{cart.product_price}}</td>
      <td>{{cart.product_quantity * cart.product_price}}</td>
      <td><button type="button" name="remove_product" class="btn btn-danger btn-xs" ng-click="removeItem(cart.product_id)">Remove</button></td>
     </tr>
     <tr>
      <td colspan="3" align="right">Total</td>
      <td colspan="2">{{ setTotals() }}</td>
     </tr>
    </table>
   </div>
  </div>
 </body>
</html>

<script>

var app = angular.module('shoppingCart', []);

app.controller('shoppingCartController', function($scope, $http){
 
 $scope.loadProduct = function(){
  $http.get('fetch.php').success(function(data){
            $scope.products = data;
        })
 };
 
 $scope.carts = [];
 
 $scope.fetchCart = function(){
  $http.get('fetch_cart.php').success(function(data){
            $scope.carts = data;
        })
 };
 
 $scope.setTotals = function(){
  var total = 0;
  for(var count = 0; count<$scope.carts.length; count++)
  {
   var item = $scope.carts[count];
   total = total + (item.product_quantity * item.product_price);
  }
  return total;
 };
 
 $scope.addtoCart = function(product){
  $http({
            method:"POST",
            url:"add_item.php",
            data:product
        }).success(function(data){
   $scope.fetchCart();
        });
 };
 
 $scope.removeItem = function(id){
  $http({
            method:"POST",
            url:"remove_item.php",
            data:id
        }).success(function(data){
   $scope.fetchCart();
        });
 };
 
});

</script>


remove_item.php



<?php

//remove_item.php

session_start();

$product_data = json_decode(file_get_contents("php://input"));
$product_id = $product_data;

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

?>


So, here we have created simple shopping cart application using AngularJS with PHP. This tutorial will give you some idea regarding how to create shopping cart with AngularJS and PHP. For more updates regarding web development tutorials, you just stay connected with our website and learn new things and enjoy coding!






Wednesday, 18 April 2018

Shopping Cart by using Bootstrap Popover with Ajax PHP


In this post, we will see a simple PHP Ajax example for making a shopping cart application using Bootstrap Popover. This PHP Ajax shopping cart application is explicitly kept easy and as less as available. If you want to get this script then You can just download this script and simply customize it as per your requirement. Here, we have load a list of items for shopping cart from the mysql database by using Jquery Ajax. For every item, we can enter item quantity as per our need and simply add into cart by using Ajax with PHP. The cart details will be stored in the PHP session and which we will fetch by using Ajax function call. Here we will display shopping cart details into Bootstrap popover. So we have to just click on anchor tag and Bootstrap popover will be slide down on web page with shopping cart details. In this shopping cart we can remove single product item also and we can also clear whole shopping cart by single click using Ajax, so here ajax will send ajax request to php script and it will clear session item, so whole shopping cart will be empty.



Bootstrap Popover for Shopping Cart


Here we have use Bootstrap popover plugin for display shopping cart details. So first we have to write HTML code for Bootstrap popover. Here we have use Bootstrap nav class for header menu and on this menu we have display Bootstrap popover plugin link. So when we have click on that link then popover will be slide down on web page in which we can see cart details.


<div class="container">
   <br />
   <h3 align="center">PHP Ajax Shopping Cart by using Bootstrap Popover</h3>
   <br />
   <nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
     <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="sr-only">Menu</span>
      <span class="glyphicon glyphicon-menu-hamburger"></span>
      </button>
      <a class="navbar-brand" href="/">Webslesson</a>
     </div>
     
     <div id="navbar-cart" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
       <li>
        <a id="cart-popover" class="btn" data-placement="bottom" title="Shopping Cart">
         <span class="glyphicon glyphicon-shopping-cart"></span>
         <span class="badge"></span>
         <span class="total_price">$ 0.00</span>
        </a>
       </li>
      </ul>
     </div>
     
    </div>
   </nav>
   <div id="popover_content_wrapper" style="display: none">
    <span id="cart_details"></span>
    <div align="right">
     <a href="#" class="btn btn-primary" id="check_out_cart">
     <span class="glyphicon glyphicon-shopping-cart"></span> Check out
     </a>
     <a href="#" class="btn btn-default" id="clear_cart">
     <span class="glyphicon glyphicon-trash"></span> Clear
     </a>
    </div>
   </div>

   <div id="display_item">


   </div>
   
  </div>


For Activate Bootstrap popover we have write following jquery code, so when we have click on anchor tag with id cart-popover then popover will be slide down on web page with shopping cart details.


$('#cart-popover').popover({
  html : true,
        container: 'body',
        content:function(){
         return $('#popover_content_wrapper').html();
        }
});


Load Item for Shopping Cart


Now we have move to load product on web page for shopping cart by using PHP Ajax. For this we have make one function with Ajax request. This function has been called when page has been load on web browser this function will be called and it will display product on web page under division tag with id display_item.


<!-- index.php !-->

load_product();

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



<?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;">  
            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
             <img src="images/'.$row["image"].'" class="img-responsive" /><br />
             <h4 class="text-info">'.$row["name"].'</h4>
             <h4 class="text-danger">$ '.$row["price"] .'</h4>
             <input type="text" name="quantity" id="quantity' . $row["id"] .'" class="form-control" value="1" />
             <input type="hidden" name="hidden_name" id="name'.$row["id"].'" value="'.$row["name"].'" />
             <input type="hidden" name="hidden_price" id="price'.$row["id"].'" value="'.$row["price"].'" />
             <input type="button" name="add_to_cart" id="'.$row["id"].'" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart" />
            </div>
        </div>
  ';
 }
 echo $output;
}


?>








Fetch Shopping Cart Details


Now we want to make on jquery function which will fetch shopping cart details which we have store in PHP Session. So in this function we have use Ajax request which send request to PHP script and that script will fetch shopping cart details which we have store into Session variable, then that details will be converted into html table format and send back to Ajax request and it will display that cart details under Bootstrap popover by using Jquery. This jquery function will be called when page has been load on browser.


<!-- index.php !-->
<script>  
$(document).ready(function(){

load_cart_data();

function load_cart_data()
{
  $.ajax({
   url:"fetch_cart.php",
   method:"POST",
   dataType:"json",
   success:function(data)
   {
    $('#cart_details').html(data.cart_details);
    $('.total_price').text(data.total_price);
    $('.badge').text(data.total_item);
   }
  });
}
</script>



<?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>';
$data = array(
 'cart_details'  => $output,
 'total_price'  => '$' . number_format($total_price, 2),
 'total_item'  => $total_item
); 

echo json_encode($data);


?>


Add Items into Shopping Cart


Now we have completed working on display product on web page that means we have make product catalog on web page and we have also make jquery ajax function for fetch shopping cart details from PHP Session variable display on web page. On product catalog we have put 'Add to Cart' button on each product, so by clicking on that button we can add items into shopping cart by using Ajax with PHP. So, When we have click on the 'Add to cart' button, then we add particular product id and its quantity into a shopping cart. For storing shopping cart details we have use PHP SESSION variable. In Following code you can understand how to add items into shopping cart session variable and if we have add single item multiple times then it's quantity will be increment. Here we have use Ajax request with JQuery PHP for add item into cart.


<!--- index.php ---!>
<script>  
$(document).ready(function(){

 $(document).on('click', '.add_to_cart', function(){
  var product_id = $(this).attr("id");
  var product_name = $('#name'+product_id+'').val();
  var product_price = $('#price'+product_id+'').val();
  var product_quantity = $('#quantity'+product_id).val();
  var action = "add";
  if(product_quantity > 0)
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity, action:action},
    success:function(data)
    {
     load_cart_data();
     alert("Item has been Added into Cart");
    }
   });
  }
  else
  {
   alert("lease Enter Number of Quantity");
  }
 });

</script>



<?php

//action.php

session_start();

if(isset($_POST["action"]))
{
 if($_POST["action"] == "add")
 {
  if(isset($_SESSION["shopping_cart"]))
  {
   $is_available = 0;
   foreach($_SESSION["shopping_cart"] as $keys => $values)
   {
    if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])
    {
     $is_available++;
     $_SESSION["shopping_cart"][$keys]['product_quantity'] = $_SESSION["shopping_cart"][$keys]['product_quantity'] + $_POST["product_quantity"];
    }
   }
   if($is_available == 0)
   {
    $item_array = array(
     'product_id'               =>     $_POST["product_id"],  
     'product_name'             =>     $_POST["product_name"],  
     'product_price'            =>     $_POST["product_price"],  
     'product_quantity'         =>     $_POST["product_quantity"]
    );
    $_SESSION["shopping_cart"][] = $item_array;
   }
  }
  else
  {
   $item_array = array(
    'product_id'               =>     $_POST["product_id"],  
    'product_name'             =>     $_POST["product_name"],  
    'product_price'            =>     $_POST["product_price"],  
    'product_quantity'         =>     $_POST["product_quantity"]
   );
   $_SESSION["shopping_cart"][] = $item_array;
  }
 }
}

?>


Remov Single Item or Clear Cart Details


Here we have make shopping cart in which user can to remove single item from the cart by click on Remove button which can be find on in each row of cart. And We have also allow to user clear all items from cart by click on clear button which user can find under Bootstrap popover shopping cart. When we have click on Remove button, then it will call jquery code and in that we have send Ajax request to PHP script for remove particular item from PHP SESSION variable based on value of product id. For this we have use PHP unset() function for clear single item or all item from cart. In following code you can find how to use Jquery Ajax code for remove single item from cart or remove all items from shopping cart.


<!--- index.php !--->
<script>  
$(document).ready(function(){

 $(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();
     $('#cart-popover').popover('hide');
     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();
    $('#cart-popover').popover('hide');
    alert("Your Cart has been clear");
   }
  });
 });
    
});

</script>



<?php

//action.php

session_start();

if(isset($_POST["action"]))
{

 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"]);
 }
}

?>


So, this is simple tutorial on How to use Bootstrap Popover plugin for make Shopping cart by using PHP Ajax Jquery with Mysql.