How To Create A Shopping Cart Using Codeigniter and Ajax
How To Create A Shopping Cart Using Codeigniter and Ajax
Why?
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.
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
with servers from behind the scenes and without loading the whole of
web pages.
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
#1. Codeigniter
www.codeigniter.com
#2. Bootstrap
www.getbootstrap.com
#3. Jquery
This is important!
website:
www.jquery.com
#4. Images
Step 2. Creating of database structures
In this tutorial, I use mysql as Database Management System
(DBMS).
But,
If you are using other DBMS like Oracle, SQL Server, Maria DB, or
MongoDB.
No, Problem!
named cart_db.
1
INSERT INTO product(product_name,product_price,product_image) VALUES
2 ('212 Sexy Men','72','1.jpg'),
3 ('Adidas Dive','10','2.jpg'),
4 ('Aigner Pour Homme','46','3.jpg'),
5 ('Aigner No 1 OUD','57','4.jpg'),
('Aigner Etienne','53','5.jpg'),
6 ('Aigner Too Feminine','46','6.jpg');
7
So that, we have some data to product table like this:
Like this:
Open cart folder and create assets folder. And then include the
After that, create one more new folder and named images. Next,
1. Autoload.php
application/config/autoload.php
like this:
application/config/config.php
like this:
Open config.php file using text editor, and then find this code:
1 $config['base_url'] = '';
Set to be like this:
1 $config['base_url'] = 'http://localhost/cart/';
3. Database.php
To configure the database.php, please open the folder:
application/config/database.php
like this:
Open database.php file using text editor, and then find this code:
1 $active_group = 'default';
$query_builder = TRUE;
2
3 $db['default'] = array(
4 'dsn' => '',
5 'hostname' => 'localhost',
6 'username' => '',
7 'password' => '',
8 'database' => '',
'dbdriver' => 'mysqli',
9 'dbprefix' => '',
10 'pconnect' => FALSE,
11 'db_debug' => (ENVIRONMENT !== 'production'),
12 'cache_on' => FALSE,
'cachedir' => '',
13 'char_set' => 'utf8',
14 'dbcollat' => 'utf8_general_ci',
15 'swap_pre' => '',
16 'encrypt' => FALSE,
17 'compress' => FALSE,
'stricton' => FALSE,
18 'failover' => array(),
19 'save_queries' => TRUE
20 );
21
22
23
24
Set to be like this:
1
2
3 $active_group = 'default';
$query_builder = TRUE;
4
5 $db['default'] = array(
6
'dsn' => '',
7 'hostname' => 'localhost',
8 'username' => 'root',
9 'password' => '',
10 'database' => 'cart_db',
'dbdriver' => 'mysqli',
11 'dbprefix' => '',
12 'pconnect' => FALSE,
13 'db_debug' => (ENVIRONMENT !== 'production'),
14 'cache_on' => FALSE,
15 'cachedir' => '',
'char_set' => 'utf8',
16 'dbcollat' => 'utf8_general_ci',
17 'swap_pre' => '',
18 'encrypt' => FALSE,
19 'compress' => FALSE,
'stricton' => FALSE,
20 'failover' => array(),
21 'save_queries' => TRUE
22 );
23
24
Step 5. Controller
Go ahead and create a controller file controllers/Product.php with
1 <?php
class Product extends CI_Controller{
2
3
function __construct(){
4 parent::__construct();
5 $this->load->model('product_model');
6 }
7
8 function index(){
$data['data']=$this->product_model->get_all_product();
9 $this->load->view('product_view',$data);
10 }
11
12 function add_to_cart(){
13 $data = array(
'id' => $this->input->post('product_id'),
14 'name' => $this->input->post('product_name'),
15 'price' => $this->input->post('product_price'),
16 'qty' => $this->input->post('quantity'),
17 );
18 $this->cart->insert($data);
echo $this->show_cart();
19 }
20
21 function show_cart(){
22 $output = '';
23 $no = 0;
foreach ($this->cart->contents() as $items) {
24 $no++;
25 $output .='
26 <tr>
27 <td>'.$items['name'].'</td>
28 <td>'.number_format($items['price']).'</td>
<td>'.$items['qty'].'</td>
29 <td>'.number_format($items['subtotal']).'</td>
30 <td><button type="button" id="'.$items['rowid'].'" class="romove
31 sm">Cancel</button></td>
32 </tr>
33 ';
}
34 $output .= '
35 <tr>
36 <th colspan="3">Total</th>
37 <th colspan="2">'.'Rp '.number_format($this->cart->total()).'</th>
</tr>
38 ';
39 return $output;
40 }
41
42 function load_cart(){
43 echo $this->show_cart();
}
44
45 function delete_cart(){
46 $data = array(
47 'rowid' => $this->input->post('row_id'),
48 'qty' => 0,
);
49 $this->cart->update($data);
50 echo $this->show_cart();
51 }
52 }
53
54
55
56
57
58
59
60
61
Step 6. Model
Go ahead and create a model file models/Product_model.php with
1
<?php
2 class Product_model extends CI_Model{
3
4 function get_all_product(){
5 $result=$this->db->get('product');
6 return $result;
}
7
8 }
9
Step 7. View
Go ahead and create a view file views/product_view.php with the
1 <!DOCTYPE html>
2 <html>
<head>
3 <title>Shopping cart using codeigniter and AJAX</title>
4 <link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/boot
5 </head>
6 <body>
7 <div class="container"><br/>
<h2>Shopping Cart Using Ajax and Codeigniter</h2>
8 <hr/>
9 <div class="row">
10 <div class="col-md-8">
11 <h4>Product</h4>
12 <div class="row">
<?php foreach ($data->result() as $row) : ?>
13 <div class="col-md-4">
14 <div class="thumbnail">
15 <img width="200" src="<?php echo base_url().'assets/images/'.$r
16 <div class="caption">
<h4><?php echo $row->product_name;?></h4>
17 <div class="row">
18 <div class="col-md-7">
19 <h4><?php echo number_format($row->product_price);
20 </div>
21 <div class="col-md-5">
<input type="number" name="quantity" id="<?php echo
22 </div>
23 </div>
24 <button class="add_cart btn btn-success btn-block" data-pro
25 data-productprice="<?php echo $row->product_price;?>">Add To Cart</button>
</div>
26 </div>
27 </div>
28 <?php endforeach;?>
29
30 </div>
31
32 </div>
<div class="col-md-4">
33 <h4>Shopping Cart</h4>
34 <table class="table table-striped">
35 <thead>
36 <tr>
37 <th>Items</th>
<th>Price</th>
38 <th>Qty</th>
39 <th>Total</th>
40 <th>Actions</th>
41 </tr>
</thead>
42 <tbody id="detail_cart">
43
44 </tbody>
45
46 </table>
47 </div>
48 </div>
</div>
49
50<script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.2.1.js'?>
51<script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"><
52<script type="text/javascript">
53 $(document).ready(function(){
54 $('.add_cart').click(function(){
var product_id = $(this).data("productid");
55 var product_name = $(this).data("productname");
56 var product_price = $(this).data("productprice");
57 var quantity = $('#' + product_id).val();
58 $.ajax({
url : "<?php echo site_url('product/add_to_cart');?>",
59 method : "POST",
60 data : {product_id: product_id, product_name: product_name, product_pr
61 success: function(data){
62 $('#detail_cart').html(data);
}
63 });
64 });
65
66
67 $('#detail_cart').load("<?php echo site_url('product/load_cart');?>");
68
69
70 $(document).on('click','.romove_cart',function(){
71 var row_id=$(this).attr("id");
$.ajax({
72 url : "<?php echo site_url('product/delete_cart');?>",
73 method : "POST",
74 data : {row_id : row_id},
75 success :function(data){
$('#detail_cart').html(data);
76 }
77 });
78 });
79 });
80 </script>
</body>
81</html>
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
Insert qty and click Add To Cart button to add product to shopping
Don't worry, I won't leave you that soon, as we'll start dissecting each
1
<?php
2 class Product_model extends CI_Model{
3
4 function get_all_product(){
5 $result=$this->db->get('product');
6 return $result;
}
7
8 }
9
Moving ahead, let's switch our attention to the controller file. Go
1 function __construct(){
2 parent::__construct();
3 $this->load->model('product_model');
4 }
using $this->load->model(‘product_model’);
1 function index(){
2 $data['data']=$this->product_model->get_all_product();
3 $this->load->view('product_view',$data);
4 }
view.
1
2 function add_to_cart(){
$data = array(
3 'id' => $this->input->post('product_id'),
4 'name' => $this->input->post('product_name'),
5 'price' => $this->input->post('product_price'),
6 'qty' => $this->input->post('quantity'),
7 );
$this->cart->insert($data);
8 echo $this->show_cart();
9 }
10
Next, Go ahead and grab the code of the show_cart method.
1
2
function show_cart(){
3 $output = '';
4 $no = 0;
5 foreach ($this->cart->contents() as $items) {
6 $no++;
$output .='
7 <tr>
8 <td>'.$items['name'].'</td>
9 <td>'.number_format($items['price']).'</td>
10 <td>'.$items['qty'].'</td>
11 <td>'.number_format($items['subtotal']).'</td>
<td><button type="button" id="'.$items['rowid'].'" class="romove_car
12 sm">Cancel</button></td>
13 </tr>
14 ';
15 }
$output .= '
16
<tr>
17 <th colspan="3">Total</th>
18 <th colspan="2">'.'Rp '.number_format($this->cart->total()).'</th>
19 </tr>
20 ';
return $output;
21 }
22
23
This methods will handle display shopping cart to the view.
function load_cart(){
1 echo $this->show_cart();
2 }
3
This methods will handle display shopping cart to the view at the first
load page.
1
function delete_cart(){
2 $data = array(
3 'rowid' => $this->input->post('row_id'),
4 'qty' => 0,
5 );
6 $this->cart->update($data);
echo $this->show_cart();
7 }
8
This methods will handle to delete items from cart.
Moving ahead, let's switch our attention to the view file. Go ahead
1
2 $('.add_cart').click(function(){
var product_id = $(this).data("productid");
3 var product_name = $(this).data("productname");
4 var product_price = $(this).data("productprice");
5 var quantity = $('#' + product_id).val();
6 $.ajax({
url : "<?php echo site_url('product/add_to_cart');?>",
7 method : "POST",
8 data : {product_id: product_id, product_name: product_name, product_pri
9 quantity},
10 success: function(data){
11 $('#detail_cart').html(data);
}
12 });
13 });
14
This script will handle submit form using Ajax processing for send
1
2 $(document).on('click','.romove_cart',function(){
3 var row_id=$(this).attr("id");
$.ajax({
4 url : "<?php echo site_url('product/delete_cart');?>",
5 method : "POST",
6 data : {row_id : row_id},
7 success :function(data){
$('#detail_cart').html(data);
8 }
9 });
10 });
11
This script will handle delete cart item using ajax processing.
Congratulations!
You did it. Now, you can create a shopping cart application without
If you feel this tutorial is useful for you. Please share! Perhaps, this