Want to learn coding through videos for free?
Check my youtube channel => HERE!

How to Create a Shopping Cart Using Codeigniter and Ajax [FULL TUTORIAL]

How to Create a Shopping Cart Using Codeigniter and Ajax [FULL TUTORIAL]

If you are serious about Shopping cart. You need to learn how to create a shopping cart using Codeigniter and Ajax.

Why?

Well, because every e-commerce website there are a lots of images need to load at the same time. if you do not use Ajax, you are in troubles.

In today’s tutorial you are going to learn everything you need to know how to create shopping cart using codeigniter and Ajax, step by step.

Let’s do this.

What is the shopping cart?

Shopping cart is a cart that serves to accommodate shopping items on E-Commerce applications.

If you are creating e-commerce project today, you will love this.

Codeigniter is a awesome open source php framework that has complete libraries and helpers, including a library cart, which is destined to create shopping carts on E-Commerce.

AJAX (Asyncronous Javascript and XML) is a technique or method used to communicate with servers from behind the scenes and without loading the whole of web pages, So that saving server bandwidth and making the web faster and more interactive.

Pretty awesome right?

Codeigniter has cart library and AJAX is a method to communicate with servers from behind the scenes and without loading the whole of web pages.

So that, we could have a awesome shopping cart.

Alright, Let’s get start it.

 

Step 1. Preparation

This is important!

If you missed this step, it means you missed the whole of this tutorial.

Good preparation will determine your success following this tutorial. The better your preparation, the more likely you will succeed in following this tutorial.

Do not skip this step, though it feels complex.

So, what do you need to prepare?

Here’s the list:

#1. Codeigniter

Codeigniter is the main php framework we will use in this tutorial. If you do not have it yet, please download it at the official website:

www.codeigniter.com 

#2. Bootstrap

Bootstrap is a framework to beautify the user interface (UI). If you do not have it yet, please download it first at the official website:

www.getbootstrap.com 

#3. Jquery

This is important!

Jquery is a javascript framework that works to help simplify the writing of AJAX-based scripts.

If you do not have it yet, please download it first at the official website:

www.jquery.com

#4. Images

Besides codeigniter, jquery, and bootstrap. Also prepare some product images. Not need much, just 6 pictures.

This is my product images looks like:

Ok, Let's continue!

 

Step 2. Creating of database structures

In this tutorial, I use mysql as Database Management System (DBMS).

If you also use mysql, you will love this tutorial.

But,

If you are using other DBMS like Oracle, SQL Server, Maria DB, or MongoDB.

No, Problem!

Provided you understand SQL (Structured Query Language) better.

Ok, Let's continue!

Please create a database, here I create a database with named cart_db.

If you create a database with the same name it will be better.

You can execute this query to create the database:

CREATE DATABASE cart_db;

That query will generate a database with named cart_db.

After that,

Create a table with name product with structure like this:

Database Structures

To create a table with structure like that,

Please execute this query:

CREATE TABLE product(
product_id INT(11) PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(100),
product_price INT(11),
product_image VARCHAR(40)
)ENGINE=INNODB;

After that, Insert some data to product table by following this query:

INSERT INTO product(product_name,product_price,product_image) VALUES
('212 Sexy Men','72','1.jpg'),
('Adidas Dive','10','2.jpg'),
('Aigner Pour Homme','46','3.jpg'),
('Aigner No 1 OUD','57','4.jpg'),
('Aigner Etienne','53','5.jpg'),
('Aigner Too Feminine','46','6.jpg');

So that, we have some data to product table like this:

Ok, Let's continue!

 

Step 3. Setup Codeigniter

Extract codeigniter that has been downloaded earlier to www folder (if you use wampserver) or htdocs (if you use XAMPP).

Because I use wampserver. So, I extract it to c:/wamp/www/

And then, rename codeigniter project to be cart.

Like this:

Web Root

Open cart folder and create assets folder. And then include the bootstrap and jquery files inside the assets folder.

After that, create one more new folder and named images. Next, copy 6 product images we prepare before to Images folder.

So that look like this:

Project Structures

 

Step 4. Configuration Codeigniter

Next step is the configuration on the codeigniter.

Here are some files you need to configure:

1. Autoload.php

To configure the autoload.php, please open the folder:

application/config/autoload.php

like this:

Autoload

Open autoload.php using text editor like Notepad++ or Sublime Text.

And then find this code:

$autoload['libraries'] = array();
$autoload['helper'] = array();

Set to be like this:

$autoload['libraries'] = array('database', 'cart');
$autoload['helper'] = array('url');

2. Config.php

To configure the config.php, please open the folder:

application/config/config.php

like this:

Config

Open config.php file using text editor, and then find this code:

$config['base_url'] = '';

Set to be like this:

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

3. Database.php

To configure the database.php, please open the folder:

application/config/database.php

like this:

database

Open database.php file using text editor, and then find this code:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        'username' => '',
        'password' => '',
        'database' => '', 
        '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
);

Set to be like this:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'cart_db', 
        '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
);

 

Step 5. Controller

Go ahead and create a controller file controllers/Product.php with the following this code:

<?php
class Product extends CI_Controller{
        
        function __construct(){
                parent::__construct();
                $this->load->model('product_model');
        }

        function index(){
                $data['data']=$this->product_model->get_all_product();
                $this->load->view('product_view',$data);
        }

        function add_to_cart(){ 
                $data = array(
                        'id' => $this->input->post('product_id'), 
                        'name' => $this->input->post('product_name'), 
                        'price' => $this->input->post('product_price'), 
                        'qty' => $this->input->post('quantity'), 
                );
                $this->cart->insert($data);
                echo $this->show_cart(); 
        }

        function show_cart(){ 
                $output = '';
                $no = 0;
                foreach ($this->cart->contents() as $items) {
                        $no++;
                        $output .='
                                <tr>
                                        <td>'.$items['name'].'</td>
                                        <td>'.number_format($items['price']).'</td>
                                        <td>'.$items['qty'].'</td>
                                        <td>'.number_format($items['subtotal']).'</td>
                                        <td><button type="button" id="'.$items['rowid'].'" class="romove_cart btn btn-danger btn-sm">Cancel</button></td>
                                </tr>
                        ';
                }
                $output .= '
                        <tr>
                                <th colspan="3">Total</th>
                                <th colspan="2">'.'Rp '.number_format($this->cart->total()).'</th>
                        </tr>
                ';
                return $output;
        }

        function load_cart(){ 
                echo $this->show_cart();
        }

        function delete_cart(){ 
                $data = array(
                        'rowid' => $this->input->post('row_id'), 
                        'qty' => 0, 
                );
                $this->cart->update($data);
                echo $this->show_cart();
        }
}

 

Step 6. Model

Go ahead and create a model file models/Product_model.php with the following this code:

<?php
class Product_model extends CI_Model{

        function get_all_product(){
                $result=$this->db->get('product');
                return $result;
        }
        
}

 

Step 7. View

Go ahead and create a view file views/product_view.php with the following this code:

<!DOCTYPE html>
<html>
<head>
        <title>Shopping cart using codeigniter and AJAX</title>
        <link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/bootstrap.css'?>">
</head>
<body>
<div class="container"><br/>
        <h2>Shopping Cart Using Ajax and Codeigniter</h2>
        <hr/>
        <div class="row">
                <div class="col-md-8">
                        <h4>Product</h4>
                        <div class="row">
                        <?php foreach ($data->result() as $row) : ?>
                                <div class="col-md-4">
                                        <div class="thumbnail">
                                                <img width="200" src="<?php echo base_url().'assets/images/'.$row->product_image;?>">
                                                <div class="caption">
                                                        <h4><?php echo $row->product_name;?></h4>
                                                        <div class="row">
                                                                <div class="col-md-7">
                                                                        <h4><?php echo number_format($row->product_price);?></h4>
                                                                </div>
                                                                <div class="col-md-5">
                                                                        <input type="number" name="quantity" id="<?php echo $row->product_id;?>" value="1" class="quantity form-control">
                                                                </div>
                                                        </div>
                                                        <button class="add_cart btn btn-success btn-block" data-productid="<?php echo $row->product_id;?>" data-productname="<?php echo $row->product_name;?>" data-productprice="<?php echo $row->product_price;?>">Add To Cart</button>
                                                </div>
                                        </div>
                                </div>
                        <?php endforeach;?>
                                
                        </div>

                </div>
                <div class="col-md-4">
                        <h4>Shopping Cart</h4>
                        <table class="table table-striped">
                                <thead>
                                        <tr>
                                                <th>Items</th>
                                                <th>Price</th>
                                                <th>Qty</th>
                                                <th>Total</th>
                                                <th>Actions</th>
                                        </tr>
                                </thead>
                                <tbody id="detail_cart">

                                </tbody>
                                
                        </table>
                </div>
        </div>
</div>

<script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.2.1.js'?>"></script>
<script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
<script type="text/javascript">
        $(document).ready(function(){
                $('.add_cart').click(function(){
                        var product_id    = $(this).data("productid");
                        var product_name  = $(this).data("productname");
                        var product_price = $(this).data("productprice");
                        var quantity      = $('#' + product_id).val();
                        $.ajax({
                                url : "<?php echo site_url('product/add_to_cart');?>",
                                method : "POST",
                                data : {product_id: product_id, product_name: product_name, product_price: product_price, quantity: quantity},
                                success: function(data){
                                        $('#detail_cart').html(data);
                                }
                        });
                });

                
                $('#detail_cart').load("<?php echo site_url('product/load_cart');?>");

                
                $(document).on('click','.romove_cart',function(){
                        var row_id=$(this).attr("id"); 
                        $.ajax({
                                url : "<?php echo site_url('product/delete_cart');?>",
                                method : "POST",
                                data : {row_id : row_id},
                                success :function(data){
                                        $('#detail_cart').html(data);
                                }
                        });
                });
        });
</script>
</body>
</html>

 

Now, go ahead and access our custom page at http://localhost/cart/index.php/product and you will see the final result like this:

Shopping cart

Insert qty and click Add To Cart button to add product to shopping cart and click Cancel button to delete cart item.

So, that's it,

We've done it!

Don't worry, I won't leave you that soon, as we'll start dissecting each part of the code now.

We'll start with the model file models/Product_model.php as that's something will be called from our controller methods.

There is one methods, upload_image.

It's used to select data from the product table in database.

<?php
class Product_model extends CI_Model{

        function get_all_product(){
                $result=$this->db->get('product');
                return $result;
        }
        
}

Moving ahead, let's switch our attention to the controller file. Go ahead and grab the code of the constructor method.

function __construct(){
        parent::__construct();
        $this->load->model('product_model');
}

In constructor method. We've loaded the model product_model, by using $this->load->model(‘product_model’);

Next, Go ahead and grab the code of the index method.

function index(){
        $data['data']=$this->product_model->get_all_product();
        $this->load->view('product_view',$data);
}

This method is heart of out controller. It's used to call to the view, product_view and bringing value in array object to product view.

Now, we're ready to go through the main method, add_to_cart method.

This methods will handle insert some data to shopping cart.

function add_to_cart(){ 
        $data = array(
                'id' => $this->input->post('product_id'), 
                'name' => $this->input->post('product_name'), 
                'price' => $this->input->post('product_price'), 
                'qty' => $this->input->post('quantity'), 
        );
        $this->cart->insert($data);
        echo $this->show_cart(); 
}

Next, Go ahead and grab the code of the show_cart method.

function show_cart(){ 
        $output = '';
        $no = 0;
        foreach ($this->cart->contents() as $items) {
                $no++;
                $output .='
                        <tr>
                                <td>'.$items['name'].'</td>
                                <td>'.number_format($items['price']).'</td>
                                <td>'.$items['qty'].'</td>
                                <td>'.number_format($items['subtotal']).'</td>
                                <td><button type="button" id="'.$items['rowid'].'" class="romove_cart btn btn-danger btn-sm">Cancel</button></td>
                        </tr>
                ';
        }
        $output .= '
                <tr>
                        <th colspan="3">Total</th>
                        <th colspan="2">'.'Rp '.number_format($this->cart->total()).'</th>
                </tr>
        ';
        return $output;
}

This methods will handle display shopping cart to the view.

Next, Go ahead and grab the code of the load_cart method.

function load_cart(){ 
        echo $this->show_cart();
}

This methods will handle display shopping cart to the view at the first load page.

Next, Go ahead and grab the code of the delete_cart method.

function delete_cart(){ 
        $data = array(
                'rowid' => $this->input->post('row_id'), 
                'qty' => 0, 
        );
        $this->cart->update($data);
        echo $this->show_cart();
}

This methods will handle to delete items from cart.

Moving ahead, let's switch our attention to the view file. Go ahead and grab the code of this script.

$('.add_cart').click(function(){
                var product_id    = $(this).data("productid");
                var product_name  = $(this).data("productname");
                var product_price = $(this).data("productprice");
                var quantity      = $('#' + product_id).val();
                $.ajax({
                        url : "<?php echo site_url('product/add_to_cart');?>",
                        method : "POST",
                        data : {product_id: product_id, product_name: product_name, product_price: product_price, quantity: quantity},
                        success: function(data){
                                $('#detail_cart').html(data);
                        }
                });
});

This script will handle submit form using Ajax processing for send data to the controller, add_to_cart.

Next, Go ahead and grab the next script.

$('#detail_cart').load("<?php echo site_url('product/load_cart');?>");

This script will handle display cart data.

Next, Go ahead and grab the last script.

$(document).on('click','.romove_cart',function(){
                var row_id=$(this).attr("id"); 
                $.ajax({
                        url : "<?php echo site_url('product/delete_cart');?>",
                        method : "POST",
                        data : {row_id : row_id},
                        success :function(data){
                                $('#detail_cart').html(data);
                        }
                });
});

This script will handle delete cart item using ajax processing.

Congratulations!

You did it. Now, you can create a shopping cart application without reloading the page with codeigniter and ajax.

If you feel this tutorial is useful for you. Please share! Perhaps, this tutorial is useful also for your friend!

Thank you very much.


Recommended for you:

#1. Dynamic Select Options Dependent Dropdown in Codeigniter and Ajax

#2. CRUD Without Reload Page Using Ajax and Codeigniter [FULL TUTORIAL]

#3. How to Upload files using Codeigniter and Ajax [Complete Tutorial]

Download Source

Comments (16)

Graham, 13 May 2018 23:22 -

Can't believe you give away so much information and yet have NO comments So allow me the honour

Ghamghami , 13 July 2018 22:10 -

This is one brilliant tutorial. Many thanks for sharing. Also, I am looking for tutorial on creating UI using semantic UI for the purposes of displaying information generated by python code. (Xml file need to be parsed and display one the page).

M Fikri, 25 May 2019 21:32 -

You are welcome

M Fikri, 25 May 2019 21:32 -

You are welcome

shabbir khan, 13 December 2018 21:12 -

very useful....thank u so much

M Fikri, 25 May 2019 21:32 -

You are welcome

Syed Sheeraz Zaidi, 18 January 2019 15:02 -

Thanks for the help worked perfectly

M Fikri, 25 May 2019 21:32 -

You are welcome

Stephen Afriyie, 14 February 2019 01:17 -

Excellent

M Fikri, 25 May 2019 21:32 -

Thanks

Inoxevious, 15 May 2019 22:01 -

when i click ADD TO CART button nothing happens, no error code....could it be my ajax is not responding to the button click call

M Fikri, 25 May 2019 21:31 -

Please cek some ajax error on console please!

Chikal, 12 June 2019 19:20 -

thank you so much, it is so helping me so much.. you are so kind dude &lt;3

Haris, 08 October 2020 12:21 -

Thanks man!

Bhagat Singh, 15 March 2021 18:07 -

This is great tutorial, it was of great help, god bless you

Chandra, 02 January 2022 09:47 -

Thanks a lot bro, you share a lot. have a nice day.

Leave a Comment