Codeigniter Shopping Cart using Ajax,Jquery

Want to create a Shopping Cart? This article will help you to create a simple shopping cart in Codeigniter using ajax and jquery. Lets start.



ciauto is the database name and product is the table that I use. Structure of the table is given below.


First of all we should connect the database with the project.Go to your config/database.php in the application folder and continue the database connection.

$db['default'] = array(   'dsn'  => '',   'hostname' => 'localhost',
   'username' => 'root',
   'password' => '',
   'database' => 'ciauto',   'dbdriver' => 'mysqli',   'dbprefix' => '',   'pconnect' => FALSE,   'db_debug' => (ENVIRONMENT !== 'production'),   'cache_on' => FALSE,   'cachedir' => '',   'char_set' => 'utf8',   'dbcollat' => 'utf8_general_ci',   'swap_pre' => '',   'encrypt' => FALSE,   'compress' => FALSE,   'stricton' => FALSE,   'failover' => array(),   'save_queries' => TRUE

 Change the highlighted part according to your database .Then set the base url in the config/config.php using your project name.

$config['base_url'] = 'http://localhost/Projects/CIShopingCart';

Now create a controller called ShoppingCart and set it as your default controller using application/config/routes.php.

$route['default_controller'] = 'ShoppingCart';$route['404_override'] = '';$route['translate_uri_dashes'] = FALSE;

Then write the index function of the controller.

public function index(){
    // call the Model
    $this->load->model('ShoppingCartModel');
    // call the GetData function in the model
    $data['row'] = $this->ShoppingCartModel->GetData();
    //load the view
    $this->load->view('ViewCart',$data);
}
Now write the GetData() function in ShoppingCartModel.
public function GetData(){
// to fetch data in the product table    
$query=$this->db->get('product');    
return $query->result();}

The code of the ViewCart.php is given below.
<html>
<head>
    <title>Shopping Cart</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">
            <h1 align="center">Shopping Cart Item List</h1><br />
            <?php
            foreach($value as $row)
            {
                echo '
    <div class="panel panel-default">
  <div class="panel-body">
     
     <h3>'.$row->Product_Name.'</h3><br>
     Price : '.$row->Product_price.'<br><br>
     <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.'" /><span class=\'glyphicon glyphicon-shopping-cart\' aria-hidden=\'true\'></span>  Add to Cart</button>
    </div>
    </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(); ?>ShoppingCart/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");
            }
        });
    });
</script>
Now the View of the page is given below.

Then write the Add function in the controller to load the cart library.
 public 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->viewCart();
    }


After that Write the view function to get the ordered items

public function ViewCart(){
        $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-default">
    <span class=\'glyphicon glyphicon-remove\' aria-hidden=\'true\'></span> 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"].'"><span class=\'glyphicon glyphicon-trash\' aria-hidden=\'true\'></span>  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;
    }

Here the count of the added data is stored to the $count variable and if the $count== 0, that means there is no any item int he cart,So it will display the $output of  "The Cart is empty.". If the $count is greater than 0, it will display the particular item list in the table.
Now the output will be like,



From Next article lets see how to develop functions for remove and clear cart functions. Go to my github to get the source code

Comments

Popular posts from this blog

Installing MongoDB into Windows

Microservice Architecture

How to Add Firebase to your Android Project