Simple E commerce shopping cart script using Codeigniter with Ajax | 2my4edge

09 February 2022

Simple E commerce shopping cart script using Codeigniter with Ajax

Simple shopping cart using Codeigniter with Ajax, Shopping cart is using to make e-commerce project. this is one of the most important needs for all web developers. here I'm going give you and very simple code to make the flow of shopping cart with ajax. these all combination of some of my previous articles. refer those also for your reference. CodeIgniter provides predefined cart class, we are just using it for our need. Let's see the process.

Simple codeigniter shopping cart
LIVE DEMO           DATABASE FILE            DOWNLOAD

VIDEO DEMO
First of all, we need to load the library in constructor of our controller, then all the functions are mentioned in our controller. Let see the Controller first. Here i have used a welcome controller. if you want to change the controller you can change it.

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

class Welcome extends CI_Controller {

    public function __construct()
    {
    parent::__construct();
    //Load Library and model.
    $this->load->library('cart');
    $this->load->model('cart_model');
    }

    public function index()
    {
        //Get all data from database
        $data['products'] = $this->cart_model->get_all();
        //send all product data to "welcome_message", which fetch from database.
        $this->load->view('welcome_message',$data);
    }



    function add()
    {
    // Set array for send data.
    $insert_data = array(
                'id' => $this->input->post('id'),
                'name' => $this->input->post('name'),
                'price' => $this->input->post('price'),
                'image' => $this->input->post('image'),
                'qty' => 1
                );
    // This function add items into cart.
    $this->cart->insert($insert_data);
    echo $fefe = count($this->cart->contents());
    // This will show insert data in cart.
    }

    


    function remove() {
    $rowid = $this->input->post('rowid');
    // Check rowid value.
    if ($rowid==="all"){
    // Destroy data which store in session.
        $this->cart->destroy();
    }else{
    // Destroy selected rowid in session.
    $data = array(
            'rowid' => $rowid,
            'qty' => 0
            );
    // Update cart data, after cancel.
    $this->cart->update($data);
    }
    echo $fefe = count($this->cart->contents());
    // This will show cancel data in cart.
    }




    function update_cart(){
    // Recieve post values,calcute them and update
    $rowid = $_POST['rowid'];
    $price = $_POST['price'];
    $amount = $price * $_POST['qty'];
    $qty = $_POST['qty'];

    $data = array(
        'rowid' => $rowid,
        'price' => $price,
        'amount' => $amount,
        'qty' => $qty
        );
    $this->cart->update($data);
    echo $data['amount'];
    }

    function billing_view(){
    // Load "billing_view".
    $this->load->view('billing_view');
    }

    public function save_order()
    {
    // This will store all values which inserted from user.
    $customer = array(
        'name' => $this->input->post('name'),
        'email' => $this->input->post('email'),
        'address' => $this->input->post('address'),
        'phone' => $this->input->post('phone')
        );
    // And store user information in database.
    $cust_id = $this->cart_model->insert_customer($customer);
    $order = array(
        'date' => date('Y-m-d'),
        'customerid' => $cust_id
        );
    $ord_id = $this->cart_model->insert_order($order);
    if ($cart = $this->cart->contents()){
    foreach ($cart as $item){
    $order_detail = array(
        'orderid' => $ord_id,
        'productid' => $item['id'],
        'quantity' => $item['qty'],
        'price' => $item['price']
        );
    // Insert product imformation with order detail, store in cart also store in database.
    $cust_id = $this->cart_model->insert_order_detail($order_detail);
        }
    }
    $this->cart->destroy();
    // After storing all imformation in database load "billing_success".
    $this->load->view('billing_success');
    }



    public function opencart()
    {
        $data['cart']  = $this->cart->contents();
        $this->load->view("cart_modal", $data);
    }





    }

MODELS - Cart_model.php
<?php
class Cart_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function get_all(){
        $query=$this->db->query("SELECT p.*
                                 FROM products p 
                                 ORDER BY p.id ASC");
        return $query->result_array();
    }

    // Insert customer details in "customer" table in database.
    public function insert_customer($data)
    {
        $this->db->insert('customers', $data);
        $id = $this->db->insert_id();
        return (isset($id)) ? $id : FALSE;
    }

    // Insert order date with customer id in "orders" table in database.
    public function insert_order($data)
    {
        $this->db->insert('orders', $data);
        $id = $this->db->insert_id();
        return (isset($id)) ? $id : FALSE;
    }

    // Insert ordered product detail in "order_detail" table in database.
    public function insert_order_detail($data)
    {
        $this->db->insert('order_detail', $data);
    }




}

Then finally view pages, Here we have 4 View pages. To make it simple.

1. welcome_messsage.php    - Landing page
2. cart_modal.php                 - Cart modal view, fetching from ajax.
3. billing_view.php               - Placed order page
4. billing_success.php          -  Success message page.

WELCOME_MESSAGE.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Shopping cart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
rel="stylesheet" id="bootstrap-css">
</head>
<body>

<div class="container">

<button class="btn btn-primary pull-right" data-toggle="modal" data-target="#exampleModal" 
onclick="javascript:opencart()" >
    <span>
      Cart ( <span class="cartcount"><?php echo count($this->cart->contents());  ?></span> )
    </span>
</button>
</div>


<div class="container catalog-grid">
<div class="row">
      <?php 
      if(isset($products) && is_array($products) && count($products)){
      $i=1;
      foreach ($products as $key => $data) { 
      ?>
        <div class="col-lg-3 col-md-4 col-sm-6">
        <div class="tile">
            <div class="price-label price<?php echo $data['id'] ?>" 
rel="<?php echo $data['price'] ?>">INR <?php echo $data['price'] ?></div>
            <img class="image<?php echo $data['id'] ?>" rel="<?php echo $data['image'] ?>" 
src="<?php echo base_url(); ?>/images/<?php echo $data['image'] ?>" 
alt="<?php echo $data['id'] ?>">
            <span class="tile-overlay"></span>
          <div class="footer">
            <p class="name<?php echo $data['id'] ?>" 
rel="<?php echo $data['id'] ?>"><?php echo $data['name'] ?></p>
            <button class="btn btn-primary" 
onclick="javascript:addtocart(<?php echo $data['id'] ?>)">Add to Cart</button>
          </div>
        </div>
      </div>
      <?php
        $i++;
          } }
        ?>
</div>
</div>


<script type="text/javascript">
    function addtocart(p_id)
    {
        var price = $('.price'+p_id).attr('rel');
        var image = $('.image'+p_id).attr('rel');
        var name  = $('.name'+p_id).text();
        var id    = $('.name'+p_id).attr('rel');
            $.ajax({
                    type: "POST",
                    url: "<?php echo site_url('welcome/add');?>",
                    data: "id="+id+"&image="+image+"&name="+name+"&price="+price,
                    success: function (response) {
                       $(".cartcount").text(response);
                    }
                });
    }


  function opencart()
  {
      $.ajax({
                  type: "POST",
                  url: "<?php echo site_url('welcome/opencart');?>",
                  data: "",
                  success: function (response) {
                  $(".displaycontent").html(response);
                  }
              });
  }

</script>

<div class="modal fade bs-example-modal-lg displaycontent" id="exampleModal" tabindex="-1" >

</body>
</html>



CART_MODAL.PHP
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title" id="exampleModalLabel">Cart details</h4>
</div>
<div class="modal-content">
<div class="col-lg-12 col-md-12">
    <h2 class="title">Shopping cart</h2>
    <table class="items-list col-lg-12 col-md-12 table-hover">
        <tbody>
        <tr>
        <th>&nbsp;</th>
        <th>Product name</th>
        <th>Product price</th>
        <th>Quantity</th>
        <th>Total</th>
        <th>Delete</th>
      </tr>
      <!--Item-->
      <?php 
        if(isset($cart) && is_array($cart) && count($cart)){
        $i=1;
        foreach ($cart as $key => $data) { 
        ?>
      <tr class="item first rowid<?php echo $data['rowid'] ?>">
        <td class="thumb">
           <img src="<?php echo base_url(); ?>/images/<?php echo $data['image'] ?>" 
                                                alt="<?php echo $data['id'] ?>">
        </td>
        <td class="name"><?php echo $data['name'] ?></td>
        <td class="price">INR 
            <span class="price<?php echo $data['rowid'] ?>"><?php echo $data['price'] ?>
            </span>
        </td>
        <td class="qnt-count">
          <input class="quantity qty<?php echo $data['rowid'] ?> form-control" 
                              type="number" min="1" value="<?php echo $data['qty'] ?>">
          <span class="Update" 
         onclick="javascript:updateproduct('<?php echo $data['rowid'] ?>')">Update</span>
        </td>
        <td class="total">INR <span class="subtotal subtotal<?php echo $data['rowid'] ?>">
                                            <?php echo $data['subtotal'] ?></span></td>
        <td class="delete"><i class="icon-delete" 
           onclick="javascript:deleteproduct('<?php echo $data['rowid'] ?>')">X</i></td>
      </tr>

      <?php
        $i++;
          } }
      ?>
     
      <tr class="item">
        <td class="thumb" colspan="4" align="right">&nbsp;</td>
        <td class="">INR <span class="grandtotal">0</span> </td>
        <td>&nbsp;</td>
      </tr>
    </tbody></table>
  </div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="javascript:deleteproduct('all')">
                                                    Clear Cart</button>
<a href="<?php echo site_url('welcome/billing_view') ?>">
      <button type="button" class="btn btn-primary">Place Order</button>
</a>
</div>
</div>
</div>
</div>



<script type="text/javascript">
function deleteproduct(rowid)
{
var answer = confirm ("Are you sure you want to delete?");
if (answer)
{
$.ajax({
      type: "POST",
      url: "<?php echo site_url('welcome/remove');?>",
      data: "rowid="+rowid,
      success: function (response) {
          $(".rowid"+rowid).remove(".rowid"+rowid); 
          $(".cartcount").text(response);  
          var total = 0;
          $('.subtotal').each(function(){
              total += parseInt($(this).text());
              $('.grandtotal').text(total);
          });              
      }
  });
}
}

var total = 0;
$('.subtotal').each(function(){
total += parseInt($(this).text());
$('.grandtotal').text(total);
});


function updateproduct(rowid)
{
var qty = $('.qty'+rowid).val();
var price = $('.price'+rowid).text();
var subtotal = $('.subtotal'+rowid).text();
$.ajax({
  type: "POST",
  url: "<?php echo site_url('welcome/update_cart');?>",
  data: "rowid="+rowid+"&qty="+qty+"&price="+price+"&subtotal="+subtotal,
  success: function (response) {
          $('.subtotal'+rowid).text(response);
          var total = 0;
          $('.subtotal').each(function(){
              total += parseInt($(this).text());
              $('.grandtotal').text(total);
          });     
  }
});
}


</script>



BILLING_VIEW.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Shopping cart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
                                            rel="stylesheet" id="bootstrap-css">

</head>
<body>

<div id="bill_info">

<?php
$grand_total = 0;
// Calculate grand total.
if ($cart = $this->cart->contents()):
foreach ($cart as $data):
$grand_total = $grand_total + $data['subtotal'];
endforeach;
endif;
?>       
  <form name="billing" method="post" action="<?php echo site_url('welcome/save_order') ?>" >
    <div align="center">
    <h1 align="center">Billing Info</h1>
    <table border="0" cellpadding="2px">
     <tr><td>Order Total:</td><td><strong>INR <?php echo $grand_total; ?></strong></td></tr>
        <tr><td>Your Name:</td><td><input type="text" name="name" required=""/></td></tr>
        <tr><td>Address:</td><td><input type="text" name="address" required="" /></td></tr>
        <tr><td>Email:</td><td><input type="text" name="email" required="" /></td></tr>
        <tr><td>Phone:</td><td><input type="text" name="phone"  required="" /></td></tr>
 <tr><td><a class ='fg-button teal' id='back' href="<?php echo site_url(); ?>">Back</a></td>
             <td><input class ='fg-button teal' type="submit" value="Place Order" /></td>
        </tr> 
     
    </table>
    </div>
</form>
</div>


</body>
</html>


BILLING_SUCCESS.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Shopping cart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
                                                rel="stylesheet" id="bootstrap-css">

</head>
<body>

<div id="bill_info">    
    <div id='result_div'>
    <h1 align='center'>Thank You! your order has been placed!</h1>
    <p id='go_back' align='center'>
    <a class='fg-button teal' href="<?php echo base_url(); ?>">Go back</a>
    </p>        
    </div>

</div>


</body>
</html>

I hope this tutorial is really help full to you, if you have any query, Please post as comment, i will reply you as soon as possible. For more update keep visiting our website and keep in touch with in social networks.

14 comments:

  1. Daroga Haffu Singh4/12/2017 9:20 AM

    Are Dada, Kitna ChhapTe Ho Mahine Me AdSense Se , Tanik Batado Maraj, NyoChhawar Deno Padego, Sasur !!!

    ReplyDelete
  2. This video is really useful and I will apply these tips during next shopping. Maybe they will also help me to write my essay or in some other situations. I'll wait for some more information from you.

    ReplyDelete
  3. Codeigniter cart can't insert data.
    is there a library required for Codeigniter cart.
    Please help me. i am waiting fro ur response. thanks

    ReplyDelete
  4. This block is very useful for me
    Thanks sir allowt

    ReplyDelete
  5. Thanx for such a nice tutorial but one issue after clear cart cart_modal view remain as it is..kindly help me to resolve it..

    ReplyDelete
  6. Thanx for such a nice tutorial but one issue when clear cart it destroy cart items but cart modal items remain there..in the modal view kindly help to resolve it..

    ReplyDelete
  7. Marketplaces are beneficial for both the online retailers as well as the customers. Entrepreneurs can start their business with zero inventories and also earn commission from the listed vendors.  ecommerce platform

    ReplyDelete
  8. This video such as a great video, but now I still have a problem with view pup up to display the cart.

    ReplyDelete
  9. what is line mean "echo $fefe = count($this->cart->contents());"?

    ReplyDelete
  10. Web based shopping is the ideal answer for the home headed and for the people who track down shopping a troublesome assignment. Internet shopping has ended up being an aid for the individuals who live in rustic regions as well. leather boot break in
    pistol single action vs double action

    ReplyDelete
  11. Web based shopping is the ideal answer for the home headed and for the people who track down shopping a troublesome assignment. Internet shopping has ended up being an aid for the individuals who live in rustic regions as well. single action vs double action pistols
    <a href="https://outdoorspap

    ReplyDelete

^