Skip to main content

Ajax Jquery Shopping cart by using Codeigniter Cart Library

For initialize Codeigniter cart class in your application, you have to write this code.
$this->load->library("cart");
After initialize Codeigniter Cart library, suppose you want to add some item into cart then first you have to make array and in that array you have to define four keys like "id", "name", "qty", "price". This four keys are required field in cart library. Suppose you have miss any key then it will not add item into cart. After this suppose you want to add more field then in fifth keys you can write "options" with value and in value you can define extra field in array format with value. But you want to add only one fields then you have to simply write name in keys and value define in value.
$data = array(
   "id"  => $_POST["product_id"],
   "name"  => $_POST["product_name"],
   "qty"  => $_POST["quantity"],
   "price"  => $_POST["product_price"]
);
For Insert above item details into cart we have use insert() method of this library and it will insert item into cart. When we have you this method for insert item into cart then it will return rowid value. It identify unique id of particular item detail in cart.
$this->cart->insert($data);
After insert item into cart now we want to fetch cart item and display on web page. So we have use this class contents() method which return array of cart item. When we have use this method then we can fetch cart item one by one. Suppose we want to get sub total of single item then this method will return single item sub total get from subtotal array variable. Here we have also define remove button also with class remove_inventory we will use as selector in jquery code and in id attribute we have store rowid variable value. From this variable we will get the unique id of particular item. For get the whole cart total, so we can use total() method of this class which return total of whole cart. 
$output = ''; $output .= ' <h3>Shopping Cart</h3><br /> <div class="table-responsive"> <div align="right"> <button type="button" id="clear_cart" class="btn btn-warning">Clear Cart</button> </div> <br /> <table class="table table-bordered"> <tr> <th width="40%">Name</th> <th width="15%">Quantity</th> <th width="15%">Price</th> <th width="15%">Total</th> <th width="15%">Action</th> </tr> '; $count = 0; foreach($this->cart->contents() as $items) { $count++; $output .= ' <tr> <td>'.$items["name"].'</td> <td>'.$items["qty"].'</td> <td>'.$items["price"].'</td> <td>'.$items["subtotal"].'</td> <td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'">Remove</button></td> </tr> '; } $output .= ' <tr> <td colspan="4" align="right">Total</td> <td>'.$this->cart->total().'</td> </tr> </table> </div> '; if($count == 0) { $output = '<h3 align="center">Cart is Empty</h3>'; } return $output;
After viewing cart item on web page now we want to remove single item from shopping cart. So we want to get unique rowid of particular item. After getting this value then after we have make one array with keys like rowid and quantity. In quantity key we have store zero as value. After this we have use update() and we have update particular item quantity to zero. In this cart library when quantity value will be zero then it will automatically remove that item. So this way we can remove single item from Codeigniter Shopping cart library.
               $row_id = $_POST["row_id"];
  $data = array(
   'rowid'  => $row_id,
   'qty'  => 0
  );
  $this->cart->update($data);
Suppose you want to remove all items from the cart, then it is very easy in Codeigniter class. You have to use only simple destroy() method of this library. This method will remove all items from this cart and it will display empty cart.
$this->cart->destroy();

Controllers - Shopping_cart.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Shopping_cart extends CI_Controller {
 
 function index()
 {
  $this->load->model("shopping_cart_model");
  $data["product"] = $this->shopping_cart_model->fetch_all();
  $this->load->view("shopping_cart", $data);
 }

 function add()
 {
  $this->load->library("cart");
  $data = array(
   "id"  => $_POST["product_id"],
   "name"  => $_POST["product_name"],
   "qty"  => $_POST["quantity"],
   "price"  => $_POST["product_price"]
  );
  $this->cart->insert($data); //return rowid 
  echo $this->view();
 }

 function load()
 {
  echo $this->view();
 }

 function remove()
 {
  $this->load->library("cart");
  $row_id = $_POST["row_id"];
  $data = array(
   'rowid'  => $row_id,
   'qty'  => 0
  );
  $this->cart->update($data);
  echo $this->view();
 }

 function clear()
 {
  $this->load->library("cart");
  $this->cart->destroy();
  echo $this->view();
 }
 
 function view()
 {
  $this->load->library("cart");
  $output = '';
  $output .= '
  <h3>Shopping Cart</h3><br />
  <div class="table-responsive">
   <div align="right">
    <button type="button" id="clear_cart" class="btn btn-warning">Clear Cart</button>
   </div>
   <br />
   <table class="table table-bordered">
    <tr>
     <th width="40%">Name</th>
     <th width="15%">Quantity</th>
     <th width="15%">Price</th>
     <th width="15%">Total</th>
     <th width="15%">Action</th>
    </tr>

  ';
  $count = 0;
  foreach($this->cart->contents() as $items)
  {
   $count++;
   $output .= '
   <tr> 
    <td>'.$items["name"].'</td>
    <td>'.$items["qty"].'</td>
    <td>'.$items["price"].'</td>
    <td>'.$items["subtotal"].'</td>
    <td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'">Remove</button></td>
   </tr>
   ';
  }
  $output .= '
   <tr>
    <td colspan="4" align="right">Total</td>
    <td>'.$this->cart->total().'</td>
   </tr>
  </table>

  </div>
  ';

  if($count == 0)
  {
   $output = '<h3 align="center">Cart is Empty</h3>';
  }
  return $output;
 }
}

Models - Shopping_cart_model.php

<?php
class Shopping_cart_model extends CI_Model
{
 function fetch_all()
 {
  $query = $this->db->get("product");
  return $query->result();
 }
}

Views - shopping_cart.php

<html>
<head>
    <title>Codeigniter Shopping Cart with Ajax JQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
 <br /><br />
 
 <div class="col-lg-6 col-md-6">
  <div class="table-responsive">
   <h3 align="center">Codeigniter Shopping Cart with Ajax JQuery</h3><br />
   <?php
   foreach($product as $row)
   {
    echo '
    <div class="col-md-4" style="padding:16px; background-color:#f1f1f1; border:1px solid #ccc; margin-bottom:16px; height:400px" align="center">
     <img src="'.base_url().'images/'.$row->product_image.'" class="img-thumbnail" /><br />
     <h4>'.$row->product_name.'</h4>
     <h3 class="text-danger">$'.$row->product_price.'</h3>
     <input type="text" name="quantity" class="form-control quantity" id="'.$row->product_id.'" /><br />
     <button type="button" name="add_cart" class="btn btn-success add_cart" data-productname="'.$row->product_name.'" data-price="'.$row->product_price.'" data-productid="'.$row->product_id.'" />Add to Cart</button>
    </div>
    ';
   }
   ?>
      
  </div>
 </div>
 <div class="col-lg-6 col-md-6">
  <div id="cart_details">
   <h3 align="center">Cart is Empty</h3>
  </div>
 </div>
 
</div>
</body>
</html>
<script>
$(document).ready(function(){
 
 $('.add_cart').click(function(){
  var product_id = $(this).data("productid");
  var product_name = $(this).data("productname");
  var product_price = $(this).data("price");
  var quantity = $('#' + product_id).val();
  if(quantity != '' && quantity > 0)
  {
   $.ajax({
    url:"<?php echo base_url(); ?>shopping_cart/add",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
    success:function(data)
    {
     alert("Product Added into Cart");
     $('#cart_details').html(data);
     $('#' + product_id).val('');
    }
   });
  }
  else
  {
   alert("Please Enter quantity");
  }
 });

 $('#cart_details').load("<?php echo base_url(); ?>shopping_cart/load");

 $(document).on('click', '.remove_inventory', function(){
  var row_id = $(this).attr("id");
  if(confirm("Are you sure you want to remove this?"))
  {
   $.ajax({
    url:"<?php echo base_url(); ?>shopping_cart/remove",
    method:"POST",
    data:{row_id:row_id},
    success:function(data)
    {
     alert("Product removed from Cart");
     $('#cart_details').html(data);
    }
   });
  }
  else
  {
   return false;
  }
 });

 $(document).on('click', '#clear_cart', function(){
  if(confirm("Are you sure you want to clear cart?"))
  {
   $.ajax({
    url:"<?php echo base_url(); ?>shopping_cart/clear",
    success:function(data)
    {
     alert("Your cart has been clear...");
     $('#cart_details').html(data);
    }
   });
  }
  else
  {
   return false;
  }
 });

});
</script>

Database

-- Database: `testing1`
--

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

--
-- Table structure for table `product`
--

CREATE TABLE IF NOT EXISTS `product` (
  `product_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  `product_name` varchar(250) NOT NULL,
  `product_price` varchar(30) NOT NULL,
  `product_image` varchar(250) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`product_id`, `category_id`, `product_name`, `product_price`, `product_image`) VALUES
(1, 1, 'ASUS Laptop 1500', '799.00', 'asus-laptop.jpg'),
(2, 1, 'Microsoft Surface Pro 3', '898.00', 'surface-pro.jpg'),
(3, 1, 'Samsung EVO 32GB', '12.00', 'samsung-sd-card.jpg'),
(4, 1, 'Desktop Hard Drive', '50.00', 'computer-hard-disk.jpg'),
(5, 1, 'External Hard Drive', '80.00', 'external-hard-disk.jpg'),
(6, 2, 'Crock-Pot Oval Slow Cooker', '34.00', 'crok-pot-cooker.jpg'),
(7, 2, 'Magic Blender System', '80.00', 'blender.jpg'),
(8, 2, 'Cordless Hand Vacuum', '40.00', 'vaccum-cleaner.jpg'),
(9, 2, 'Dishwasher Detergent', '15.00', 'detergent-powder.jpg'),
(10, 2, 'Essential Oil Diffuser', '20.00', 'unpower-difuser.jpg'),
(11, 3, 'Medical Personalized', '11.00', 'hand-bag.jpg'),
(12, 3, 'Best Bridle Leather Belt', '64.00', 'mens-belt.jpg'),
(13, 3, 'HANDMADE Bow set', '24.00', 'pastal-colors.jpg'),
(14, 3, 'Ceramic Coffee Mug', '18.00', 'coffee-mug.jpg'),
(15, 3, 'Wine Birthday Glass', '18.00', 'wine-glass.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `product`
--
ALTER TABLE `product`
  ADD PRIMARY KEY (`product_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=16;

Comments

Popular posts from this blog

Insert Fetch Update Delete Mysql data in Codeigniter

Database -- -- Table structure for table `tbl_user` -- CREATE TABLE IF NOT EXISTS `tbl_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(200) NOT NULL, `last_name` varchar(200) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=95 ; -- -- Dumping data for table `tbl_user` -- INSERT INTO `tbl_user` (`id`, `first_name`, `last_name`) VALUES (91, 'Harold', 'Jones'), (89, 'Christine', 'Smith'), (88, 'Marker', 'Angela'), (87, 'Romeo', 'Mary'), (86, 'Smith', 'John'); Controller - main.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Main extends CI_Controller { //functions public function index(){ $this->load->model("main_model"); $data["fetch_data"] = $this->main_model->...

How to Generate Excel File in Codeigniter using PHPExcel

Libraries/Excel.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); require_once('PHPExcel.php'); class Excel extends PHPExcel { public function __construct() { parent::__construct(); } } ?> Libraries/IOFactory.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); require_once('PHPExcel/IOFactory.php'); class IOFactory extends PHPExcel_IOFactory { public function __construct() { parent::__construct(); } } ?> Controllers/Excel_export.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Excel_export extends CI_Controller { function index() { $this->load->model("excel_export_model"); $data["employee_data"] = $this->excel_export_model->fetch_data(); $this->load->view("excel_export_view", $data); } function action() { $this->load->model(...

Core php login logout and register view delete

Core php login logout and register view delete Database.php CREATE TABLE IF NOT EXISTS register.`users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `trn_date` datetime NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE IF NOT EXISTS register.`new_record` ( `id` int(11) NOT NULL AUTO_INCREMENT, `trn_date` datetime NOT NULL, `name` varchar(50) NOT NULL, `age`int(11) NOT NULL, `submittedby` varchar(50) NOT NULL, PRIMARY KEY (`id`) ); Auth.php <?php session_start(); if(!isset($_SESSION["username"])){ header("Location: login.php"); exit(); } ?> Dashbaord .php <!DOCTYPE html> <html lang="en"> <head> <title>Dashboard</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.boo...