0% found this document useful (0 votes)
728 views

CRUD Without Reload Page Using Ajax and Codeigniter

This document provides steps to create a CRUD (create, read, update, delete) application without page reloads using CodeIgniter and AJAX. It outlines preparing the necessary tools, creating a database structure, configuring CodeIgniter, creating a controller and model, and using Bootstrap modals and datatables for forms and data display. The goal is to build a single-page CRUD app instead of needing separate pages for each operation.

Uploaded by

Abdul Syukur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
728 views

CRUD Without Reload Page Using Ajax and Codeigniter

This document provides steps to create a CRUD (create, read, update, delete) application without page reloads using CodeIgniter and AJAX. It outlines preparing the necessary tools, creating a database structure, configuring CodeIgniter, creating a controller and model, and using Bootstrap modals and datatables for forms and data display. The goal is to build a single-page CRUD app instead of needing separate pages for each operation.

Uploaded by

Abdul Syukur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

CRUD Without Reload Page Using

Ajax and Codeigniter [FULL


TUTORIAL]
 JANUARY 25, 2018
 I think you'll agree if I say this:

 “It is very difficult to create CRUD (Create Read Update Delete)

application without reload page using Codeigniter and AJAX.”

 Good News:

 Well, It turns out, you can easily create CRUD application without

reload page using Codeigniter and AJAX Jquery,

 Right Now.!

 This is the way I used a few months ago for my own project.

 Today, in this tutorial, I will explain to you clearly how to make CRUD

application without reload page using Codeigniter and Ajax Jquery.

 STEP-BY-STEP!

 What is AJAX?
 AJAX (Asynchronous Javascript And XML) is a method or technique

of web-based programming to create interactive web application.

 With Ajax, Web applications can send and retrieve data from a server

asynchronously (in the background) without interfering with the

display and behavior of the existing page.

 Pretty cool right?

 In this tutorial, I use BOOTSTRAP modals to create input and update

form.

 BOOTSTRAP modals helps us make it easier to create

CRUD(Create Read Update Delete) applications in just one page.

 Awesome right?

 Before bootstrap coming up, to make a CRUD application requires

several pages.

 There are page to display data from database, create form page, and

edit form page.

 OK, 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. Datatables

 Datatables is a plugin built from jquery to display data in table form

and has integrated with filters, show per page, and pagination.

 To download datatables please download at following

link: https://datatables.net/download/index.

 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

name db_crud.

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

 Please execute this query to create the database:


1 CREATE DATABASE db_crud;

 That query will generate a database with name db_crud.

 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_code varchar(15) PRIMARY KEY,

3 product_name VARCHAR(100),

4 product_price INT(11)

)ENGINE=INNODB;
5

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

 Like this:

 Open crud_ajax folder and create assets folder. And then include

the bootstrap, datatables, and jquery files inside the assets 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');

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/crud_ajax/';

 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';

2 $query_builder = TRUE;

4 $db['default'] = array(

5 'dsn' => '',

'hostname' => 'localhost',


6
'username' => '',
7
'password' => '',
8
'database' => '',
9
'dbdriver' => 'mysqli',
10 'dbprefix' => '',
11 'pconnect' => FALSE,
12 'db_debug' => (ENVIRONMENT !== 'production'),

13 'cache_on' => FALSE,


14 'cachedir' => '',

15 'char_set' => 'utf8',

'dbcollat' => 'utf8_general_ci',


16
'swap_pre' => '',
17
'encrypt' => FALSE,
18
'compress' => FALSE,
19
'stricton' => FALSE,
20 'failover' => array(),
21 'save_queries' => TRUE

22 );

23

24

 Set to be like this:

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

3
$db['default'] = array(
4
'dsn' => '',
5
'hostname' => 'localhost',
6
'username' => 'root',
7
'password' => '',
8 'database' => 'db_crud',
9 'dbdriver' => 'mysqli',

10 'dbprefix' => '',

11 'pconnect' => FALSE,

'db_debug' => (ENVIRONMENT !== 'production'),


12
'cache_on' => FALSE,
13
'cachedir' => '',
14
'char_set' => 'utf8',
15
'dbcollat' => 'utf8_general_ci',
16
'swap_pre' => '',
17 'encrypt' => FALSE,
18 'compress' => FALSE,

19 'stricton' => FALSE,

'failover' => array(),


20
'save_queries' => TRUE
21
);
22

23

24

 Step 5. Controller
 Go ahead and create a controller file controllers/Product.php with

the following this code:

1 <?php
2 class Product extends CI_Controller{

3 function __construct(){

4 parent::__construct();

$this->load->model('product_model');
5
}
6
function index(){
7
$this->load->view('product_view');
8
}
9

10
function product_data(){
11 $data=$this->product_model->product_list();
12 echo json_encode($data);

13 }

14

15 function save(){

$data=$this->product_model->save_product();
16
17 echo json_encode($data);

18 }

19
function update(){
20
$data=$this->product_model->update_product();
21
echo json_encode($data);
22
}
23

24
function delete(){
25 $data=$this->product_model->delete_product();
26 echo json_encode($data);
27 }

28

29 }

30

31

 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 product_list(){

5 $hasil=$this->db->get('product');

6 return $hasil->result();

}
7

8
9 function save_product(){

10 $data = array(

11 'product_code' => $this->input->post('product_code'),

12 'product_name' => $this->input->post('product_name'),

'product_price' => $this->input->post('price'),


13
);
14
$result=$this->db->insert('product',$data);
15
return $result;
16
}
17

18 function update_product(){
19 $product_code=$this->input->post('product_code');
20 $product_name=$this->input->post('product_name');

21 $product_price=$this->input->post('price');

22

23 $this->db->set('product_name', $product_name);

$this->db->set('product_price', $product_price);
24
$this->db->where('product_code', $product_code);
25
$result=$this->db->update('product');
26
return $result;
27
}
28

29 function delete_product(){
30 $product_code=$this->input->post('product_code');
31 $this->db->where('product_code', $product_code);

32 $result=$this->db->delete('product');

33 return $result;

}
34

35
}
36

37

38


 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
<meta charset="utf-8">
4
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=
5
<title>Product List</title>
6
<link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/boot
7
<link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/jque
8 <link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/data
9 </head>

10 <body>

11 <div class="container">
<!-- Page Heading -->
12
<div class="row">
13
<div class="col-12">
14
<div class="col-md-12">
15
<h1>Product
16 <small>List</small>
17 <div class="float-right"><a href="javascript:void(0);" class="btn b
New</a></div>
18
</h1>
19
</div>
20

21
<table class="table table-striped" id="mydata">
22
<thead>
23 <tr>
24 <th>Product Code</th>

25 <th>Product Name</th>
26 <th>Price</th>

27 <th style="text-align: right;">Actions</th>

</tr>
28
</thead>
29
<tbody id="show_data">
30

31
</tbody>
32
</table>
33 </div>
34 </div>
35

36 </div>

37

38 <!-- MODAL ADD -->

39 <form>

<div class="modal fade" id="Modal_Add" tabindex="-1" role="dialog" aria-labe


40
<div class="modal-dialog modal-lg" role="document">
41
<div class="modal-content">
42
<div class="modal-header">
43
<h5 class="modal-title" id="exampleModalLabel">Add New Product</h5
44 <button type="button" class="close" data-dismiss="modal" aria-label
45 <span aria-hidden="true">&times;</span>
46 </button>

47 </div>

48 <div class="modal-body">

<div class="form-group row">


49
<label class="col-md-2 col-form-label">Product Code</labe
50
<div class="col-md-10">
51
<input type="text" name="product_code" id="product_code"
52
</div>
53 </div>
54 <div class="form-group row">

55 <label class="col-md-2 col-form-label">Product Name</labe

56 <div class="col-md-10">
57 <input type="text" name="product_name" id="product_name"

58 </div>

</div>
59
<div class="form-group row">
60
<label class="col-md-2 col-form-label">Price</label>
61
<div class="col-md-10">
62
<input type="text" name="price" id="price" class="form-co
63 </div>
64 </div>

65 </div>

66 <div class="modal-footer">

67 <button type="button" class="btn btn-secondary" data-dismiss="modal

<button type="button" type="submit" id="btn_save" class="btn btn-pr


68
</div>
69
</div>
70
</div>
71
</div>
72 </form>
73 <!--END MODAL ADD-->

74

75 <!-- MODAL EDIT -->

76 <form>

77 <div class="modal fade" id="Modal_Edit" tabindex="-1" role="dialog" aria-lab

<div class="modal-dialog modal-lg" role="document">


78
<div class="modal-content">
79
<div class="modal-header">
80
<h5 class="modal-title" id="exampleModalLabel">Edit Product</h5>
81
<button type="button" class="close" data-dismiss="modal" aria-label
82 <span aria-hidden="true">&times;</span>
83 </button>

84 </div>

85 <div class="modal-body">

86 <div class="form-group row">

<label class="col-md-2 col-form-label">Product Code</labe


87
88 <div class="col-md-10">

89 <input type="text" name="product_code_edit" id="product_c

</div>
90
</div>
91
<div class="form-group row">
92
<label class="col-md-2 col-form-label">Product Name</labe
93
<div class="col-md-10">
94 <input type="text" name="product_name_edit" id="product_n
95 </div>

96 </div>

97 <div class="form-group row">

98 <label class="col-md-2 col-form-label">Price</label>

<div class="col-md-10">
99
<input type="text" name="price_edit" id="price_edit" clas
100
</div>
101
</div>
102
</div>
103 <div class="modal-footer">
104 <button type="button" class="btn btn-secondary" data-dismiss="modal

105 <button type="button" type="submit" id="btn_update" class="btn btn-

106 </div>

107 </div>

</div>
108
</div>
109
</form>
110
<!--END MODAL EDIT-->
111

112
<!--MODAL DELETE-->
113 <form>
114 <div class="modal fade" id="Modal_Delete" tabindex="-1" role="dialog" aria-l

115 <div class="modal-dialog" role="document">

116 <div class="modal-content">

117 <div class="modal-header">

<h5 class="modal-title" id="exampleModalLabel">Delete Product</h5>


118
119 <button type="button" class="close" data-dismiss="modal" aria-label

120 <span aria-hidden="true">&times;</span>

</button>
121
</div>
122
<div class="modal-body">
123
<strong>Are you sure to delete this record?</strong>
124
</div>
125 <div class="modal-footer">
126 <input type="hidden" name="product_code_delete" id="product_code_de

127 <button type="button" class="btn btn-secondary" data-dismiss="modal

128 <button type="button" type="submit" id="btn_delete" class="btn btn-

129 </div>

</div>
130
</div>
131
</div>
132
</form>
133
<!--END MODAL DELETE-->
134

135<script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.2.1.js'?

136<script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>">

137<script type="text/javascript" src="<?php echo base_url().'assets/js/jquery.dataTables

138<script type="text/javascript" src="<?php echo base_url().'assets/js/dataTables.bootst

139

140<script type="text/javascript">
$(document).ready(function(){
141
show_product(); //call function show all product
142

143
$('#mydata').dataTable();
144

145
//function show all product
146
function show_product(){
147 $.ajax({
148 type : 'ajax',

149 url : '<?php echo site_url('product/product_data')?>',


150 async : true,

151 dataType : 'json',

success : function(data){
152
var html = '';
153
var i;
154
for(i=0; i<data.length; i++){
155
html += '<tr>'+
156 '<td>'+data[i].product_code+'</td>'+
157 '<td>'+data[i].product_name+'</td>'+

158 '<td>'+data[i].product_price+'</td>'+

159 '<td style="text-align:right;">'+

160 '<a href="javascript:void(0);" class="btn btn-info


product_name="'+data[i].product_name+'" data-price="'+data[i].product_price+'">Edit</
161
'<a href="javascript:void(0);" class="btn btn-dang
162 '</td>'+
163 '</tr>';

164 }

165 $('#show_data').html(html);

}
166

167
});
168
}
169

170
//Save product
171
$('#btn_save').on('click',function(){
172
var product_code = $('#product_code').val();
173 var product_name = $('#product_name').val();
174 var price = $('#price').val();

175 $.ajax({

176 type : "POST",

url : "<?php echo site_url('product/save')?>",


177
dataType : "JSON",
178
data : {product_code:product_code , product_name:product_name, price:
179
success: function(data){
180
181 $('[name="product_code"]').val("");

182 $('[name="product_name"]').val("");

$('[name="price"]').val("");
183
$('#Modal_Add').modal('hide');
184
show_product();
185
}
186
});
187 return false;
188 });

189

190 //get data for update record

191 $('#show_data').on('click','.item_edit',function(){

192 var product_code = $(this).data('product_code');

var product_name = $(this).data('product_name');


193
var price = $(this).data('price');
194

195
$('#Modal_Edit').modal('show');
196
$('[name="product_code_edit"]').val(product_code);
197
$('[name="product_name_edit"]').val(product_name);
198 $('[name="price_edit"]').val(price);
199 });

200

201 //update record to database

202 $('#btn_update').on('click',function(){

203 var product_code = $('#product_code_edit').val();

var product_name = $('#product_name_edit').val();


204
var price = $('#price_edit').val();
205
$.ajax({
206
type : "POST",
207
url : "<?php echo site_url('product/update')?>",
208 dataType : "JSON",
209 data : {product_code:product_code , product_name:product_name, price:

210 success: function(data){

211 $('[name="product_code_edit"]').val("");
212 $('[name="product_name_edit"]').val("");

213 $('[name="price_edit"]').val("");

$('#Modal_Edit').modal('hide');
214
show_product();
215
}
216
});
217
return false;
218 });
219

220 //get data for delete record


221 $('#show_data').on('click','.item_delete',function(){

222 var product_code = $(this).data('product_code');

223

224 $('#Modal_Delete').modal('show');

$('[name="product_code_delete"]').val(product_code);
225
});
226

227
//delete record to database
228
$('#btn_delete').on('click',function(){
229
var product_code = $('#product_code_delete').val();
230 $.ajax({
231 type : "POST",

232 url : "<?php echo site_url('product/delete')?>",

233 dataType : "JSON",

234 data : {product_code:product_code},

success: function(data){
235
$('[name="product_code_delete"]').val("");
236
$('#Modal_Delete').modal('hide');
237
show_product();
238
}
239 });
240 return false;

241 });

242
243 });

244

245</script>
</body>
246
</html>
247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

 Now, go ahead and access our custom page

at http://localhost/crud_ajax/index.php/product and you will see the

final result like this:


 So, that's it,

 We've done it!

 Please click add new button to add new product, click edit button to

update record, and click delete button to delete record.

 Congratulations!

 You did it. Now, you can create a crud 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.

You might also like