Вы находитесь на странице: 1из 21

 CONTACT

How to Create a Shopping Cart


Using Codeigniter and Ajax [FULL
TUTORIAL]
 JANUARY 29, 2018
 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:

1 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:

 To create a table with structure like that,

 Please execute this query:

1 CREATE TABLE product(


2 product_id INT(11) PRIMARY KEY AUTO_INCREMENT,
3 product_name VARCHAR(100),
4 product_price INT(11),
5 product_image VARCHAR(40)
)ENGINE=INNODB;
6
 After that, Insert some data to product table by following this query:

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:

 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:

 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:


 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:

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

 And then find this code:


1 $autoload['libraries'] = array();
2 $autoload['helper'] = array();
 Set to be like this:

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


2 $autoload['helper'] = array('url');
 2. Config.php

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

 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

the following this code:

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

the following this code:

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

following this code:

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

 Now, go ahead and access our custom page

at http://localhost/cart/index.php/productand you will see the final

result like this:


 Insert qty and click Add To Cart button to add product to shopping

cart and click Cancelbutton 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.

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

ahead and grab the code of the constructor method.

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

 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.

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

 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.

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.

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

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.

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

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

and grab the code of this script.

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

data to the controller, add_to_cart.

 Next, Go ahead and grab the next script.


1 $('#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.

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

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.

Вам также может понравиться