Thursday 1 September 2016

PHP Drag and Drop Shopping Cart by Ajax jQuery



Hi friends in this post we are going to develop product drag and drop PHP shopping cart by using Jquery with Ajax by using drag and drop event without page refresh. Here I will fetch product from database and display on webpage and user can add that product to shopping cart by using simple drag and drop product to the cart and adding product to cart and all product details are stored in session variable. This all process done without page refresh. If buyer do not want to buy any of the shopping cart product then he can also removed that product from shopping cart this is done by clear this session of that item from the cart and item will be removed from the shopping cart without page refresh event. This is an advance shopping cart in which I have only use php jquery Ajax with mysql database, if you are looking to learn drag and drop product shopping cart by using PHP with Jquery Ajax. In this shopping cart user can add product to shopping cart by drag and drop item to product drag area division and below item which we have added to our cart with details like item name quantity price, if you already add item to cart, again you cannot add item to cart, you can also remove item from this shopping cart.

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=4 ;  
 --  
 -- 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  
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "test");  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | PHP Shopping Cart by jQuery Drag and Drop</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>  
           .product_drag_area{  
                width:600px;  
                height:200px;  
                border:2px dashed #ccc;  
                color:#ccc;  
                line-height:200px;  
                text-align:center;  
                font-size:24px;  
           }  
           .product_drag_over{  
                color:#000;  
                border-color:#000;  
           }  
           </style>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:700px;">  
                <h3 align="center">PHP Shopping Cart by jQuery Drag and Drop</h3><br />  
                <?php  
                $query = "SELECT * FROM tbl_product ORDER BY id ASC";  
                $result = mysqli_query($connect, $query);  
                if(mysqli_num_rows($result) > 0)  
                {  
                     while($row = mysqli_fetch_array($result))  
                     {  
                ?>  
                <div class="col-md-4">  
                     <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; cursor:move" align="center">  
                          <img src="<?php echo $row["image"]; ?>" data-id="<?php echo $row['id']; ?>" data-name="<?php echo $row['name']; ?>" data-price="<?php echo $row['price']; ?>" class="img-responsive product_drag" />  
                          <h4 class="text-info"><?php echo $row["name"]; ?></h4>  
                          <h4 class="text-danger">$ <?php echo $row["price"]; ?></h4>  
                     </div>  
                </div>  
                <?php  
                     }  
                }  
                ?>  
                <div style="clear:both"></div>  
                <br />  
                <div align="center">  
                     <div class="product_drag_area">Drop Product Here</div>  
                </div>  
                <div id="dragable_product_order">  
                </div>  
           </div>  
           <br />  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(data){  
      $('.product_drag_area').on('dragover', function(){  
           $(this).addClass('product_drag_over');  
           return false;  
      });  
      $('.product_drag_area').on('dragleave', function(){  
           $(this).removeClass('product_drag_over');  
           return false;  
      });  
      $('.product_drag').on('dragstart', function(e){  
           e.originalEvent.dataTransfer.setData("id", $(this).data("id"));  
           e.originalEvent.dataTransfer.setData("name", $(this).data("name"));  
           e.originalEvent.dataTransfer.setData("price", $(this).data("price"));  
      });  
      $('.product_drag_area').on('drop', function(e){  
           e.preventDefault();  
           $(this).removeClass('product_drag_over');  
           var id = e.originalEvent.dataTransfer.getData('id');  
           var name = e.originalEvent.dataTransfer.getData('name');  
           var price = e.originalEvent.dataTransfer.getData('price');  
           var action = "add";  
           $.ajax({  
                url:"action.php",  
                method:"POST",  
                data:{id:id, name:name, price:price, action:action},  
                success:function(data){  
                     $('#dragable_product_order').html(data);  
                }  
           })  
      });  
      $(document).on('click', '.remove_product', function(){  
           if(confirm("Are you sure you want to remove this product?"))  
           {  
                var id = $(this).attr("id");  
                var action="delete";  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     data:{id:id, action:action},  
                     success:function(data){  
                          $('#dragable_product_order').html(data);  
                     }  
                });  
           }  
           else  
           {  
                return false;  
           }  
      });  
 });  
 </script>  



action.php


 <?php  
 //action.php  
 session_start();  
 if($_POST["action"] == "add")  
 {  
      if(isset($_SESSION['shopping_cart']))  
      {  
           $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");  
           if(!in_array($_POST["id"], $item_array_id))  
           {  
                $count = count($_SESSION["shopping_cart"]);  
                $item_array = array(  
                     'item_id'               =>     $_POST["id"],  
                     'item_name'               =>     $_POST["name"],  
                     'item_price'          =>     $_POST["price"],  
                     'item_quantity'          =>     '1'  
                );  
                $_SESSION["shopping_cart"][$count] = $item_array;  
           }  
           else  
           {  
                echo '<script>alert("Item Already Added")</script>';  
           }  
      }  
      else  
      {  
           $item_array = array(  
                'item_id'               =>     $_POST["id"],  
                'item_name'               =>     $_POST["name"],  
                'item_price'          =>     $_POST["price"],  
                'item_quantity'          =>     '1'  
           );  
           $_SESSION["shopping_cart"][0] = $item_array;  
      }  
      echo make_cart_table();  
 }  
 if($_POST["action"] == "delete")  
 {  
      foreach($_SESSION["shopping_cart"] as $keys => $values)  
      {  
           if($values['item_id'] == $_POST["id"])  
           {  
                unset($_SESSION["shopping_cart"][$keys]);  
                echo make_cart_table();  
           }  
      }  
 }  
 function make_cart_table()  
 {  
      $output = '';  
      if(!empty($_SESSION["shopping_cart"]))  
      {  
           $total = 0;  
           $output .= '  
                <h3>Order Details</h3>  
                <div class="table-responsive">  
                     <table class="table table-bordered">  
                          <tr>  
                               <th width="40%">Item Name</th>  
                               <th width="10%">Quantity</th>  
                               <th width="20%">Price</th>  
                               <th width="20%">Action</th>  
                          </tr>  
           ';  
           foreach($_SESSION["shopping_cart"] as $keys => $values)  
           {  
                $output .= '  
                     <tr>  
                          <td>'.$values["item_name"].'</td>  
                          <td>'.$values["item_quantity"].'</td>  
                          <td>'.$values["item_price"].'</td>  
                          <td><a href="#" class="remove_product" id="'.$values["item_id"]. '"><span class="text-danger">Remove</span></a></td>  
                     </tr>  
                ';  
                $total = $total + ($values["item_quantity"] * $values["item_price"]);  
           }  
           $output .= '  
                <tr>  
                     <td colspan="3" align="right">Total</td>  
                     <td>$ <span id="total_price">'.number_format($total, 2).'</span></td>  
                </tr>  
           </table>  
           ';  
      }  
      return $output;  
 }  
 ?>  

2 comments: