Codeigniter Ajax CRUD Tutorial Example
Today, i am going to share with you how to create CRUD Application with pagination using JQuery Ajax in Codeigniter 3.
CRUD is a basic step of any Core Language or framework. CRUD stand for Create Read Update and Delete. So in this post we will learn insert update delete in codeigniter using jquery Ajax. I gave you example from scratch so if you don't know about Codeigniter 3 then no issue. You have to just follow simple step.
There are listed bellow step you have to follow:
1)Download Fresh Codeigniter 3
2)Create Database and Configuration
3)Add Route
4)Create Controller
5)Update View
6)Create JS File
In this example i used several jquery Plugin for fire Ajax, Ajax pagination, Bootstrap, Bootstrap Validation, notification as listed bellow.
Jquery
Bootstrap
twbsPagination js
Validator JS(Bootstrap form validation example with demo using validator.js plugin)
toastr JS(Jquery notification popup box example using toastr JS plugin with demo)
After complete this c.r.u.d. application example you will be find preview as like bellow preview scheenshot:
Preview:
Step 1: Download Fresh Codeigniter 3
In First step we will download fresh version of Codeigniter 3, so if you haven't download yet then download from here : Download Codeigniter 3.
After Download successfully, extract clean new Codeigniter 3 application.
Step 2: Create Database and Configuration
In this step we will create new database "test" and add new table "items" in test database. You can use following SQL Query for create "items" table. So let's create using bellow sql query:
item table:
CREATE TABLE IF NOT EXISTS `items` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;
After create database and table successfully, we have to configuration of database in our Codeigniter 3 application, so open database.php file and add your database name, username and password.
application/config/database.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'test',
'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 3: Add Route
In this step you have to add some route in your route file. So first we will create route for items modules for lists, create, edit, update and delete.so put the bellow content in route file:
application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['items'] = "items/index";
$route['itemsCreate']['post'] = "items/store";
$route['itemsEdit/(:any)'] = "items/edit/$1";
$route['itemsUpdate/(:any)']['put'] = "items/update/$1";
$route['itemsDelete/(:any)']['delete'] = "items/delete/$1";
Step 4: Create Controller
Ok, now first we have to create one new controller api method listing, create, edit, update and delete. so create Items.php file in this path application/controllers/Items.php and put bellow code in this file:
application/controllers/Items.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Items extends CI_Controller {
/**
* Get All Data from this method.
*
* @return Response
*/
public function index()
{
$this->load->database();
if(!empty($this->input->get("search"))){
$this->db->like('title', $this->input->get("search"));
$this->db->or_like('description', $this->input->get("search"));
}
$this->db->limit(5, ($this->input->get("page",1) - 1) * 5);
$query = $this->db->get("items");
$data['data'] = $query->result();
$data['total'] = $this->db->count_all("items");
echo json_encode($data);
}
/**
* Store Data from this method.
*
* @return Response
*/
public function store()
{
$this->load->database();
$insert = $this->input->post();
$this->db->insert('items', $insert);
$id = $this->db->insert_id();
$q = $this->db->get_where('items', array('id' => $id));
echo json_encode($q->row());
}
/**
* Edit Data from this method.
*
* @return Response
*/
public function edit($id)
{
$this->load->database();
$q = $this->db->get_where('items', array('id' => $id));
echo json_encode($q->row());
}
/**
* Update Data from this method.
*
* @return Response
*/
public function update($id)
{
$this->load->database();
$insert = $this->input->post();
$this->db->where('id', $id);
$this->db->update('items', $insert);
$q = $this->db->get_where('items', array('id' => $id));
echo json_encode($insert);
}
/**
* Delete Data from this method.
*
* @return Response
*/
public function delete($id)
{
$this->load->database();
$this->db->where('id', $id);
$this->db->delete('items');
echo json_encode(['success'=>true]);
}
}
Step 5: Update View
In this step we will update view file of welcome_message.php. In this file we will write code of insert update delete and also include bootstrap, jquery, toastr and twbsPagination. So let's update following file:
application/views/welcome_message.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter 3 - Ajax CRUD Example</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Codeigniter 3 - Ajax CRUD Example</h2>
</div>
<div class="pull-right">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#create-item"> Create Item</button>
</div>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th width="200px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<ul id="pagination" class="pagination-sm"></ul>
<!-- Create Item Modal -->
<div class="modal fade" id="create-item" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Create Item</h4>
</div>
<div class="modal-body">
<form data-toggle="validator" action="items/store" method="POST">
<div class="form-group">
<label class="control-label" for="title">Title:</label>
<input type="text" name="title" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label" for="title">Description:</label>
<textarea name="description" class="form-control" data-error="Please enter description." required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button type="submit" class="btn crud-submit btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Edit Item Modal -->
<div class="modal fade" id="edit-item" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Item</h4>
</div>
<div class="modal-body">
<form data-toggle="validator" action="" method="put">
<div class="form-group">
<label class="control-label" for="title">Title:</label>
<input type="text" name="title" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label" for="title">Description:</label>
<textarea name="description" class="form-control" data-error="Please enter description." required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success crud-submit-edit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.3.1/jquery.twbsPagination.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">
<script type="text/javascript">
var url = "items";
</script>
<script src="/js/item-ajax.js"></script>
</body>
</html>
Step 6: Create JS File
In this last step we will make new folder js on your root directory and create new file item-ajax.js on that folder. In item-ajax.js file we write all code of CRUD JS that will manage listing, insert, update, delete and pagination. So let's create new file and put following code:
js/item-ajax.js
var page = 1;
var current_page = 1;
var total_page = 0;
var is_ajax_fire = 0;
manageData();
/* manage data list */
function manageData() {
$.ajax({
dataType: 'json',
url: url,
data: {page:page}
}).done(function(data){
total_page = data.total % 5;
current_page = page;
$('#pagination').twbsPagination({
totalPages: total_page,
visiblePages: current_page,
onPageClick: function (event, pageL) {
page = pageL;
if(is_ajax_fire != 0){
getPageData();
}
}
});
manageRow(data.data);
is_ajax_fire = 1;
});
}
/* Get Page Data*/
function getPageData() {
$.ajax({
dataType: 'json',
url: url,
data: {page:page}
}).done(function(data){
manageRow(data.data);
});
}
/* Add new Item table row */
function manageRow(data) {
var rows = '';
$.each( data, function( key, value ) {
rows = rows + '<tr>';
rows = rows + '<td>'+value.title+'</td>';
rows = rows + '<td>'+value.description+'</td>';
rows = rows + '<td data-id="'+value.id+'">';
rows = rows + '<button data-toggle="modal" data-target="#edit-item" class="btn btn-primary edit-item">Edit</button> ';
rows = rows + '<button class="btn btn-danger remove-item">Delete</button>';
rows = rows + '</td>';
rows = rows + '</tr>';
});
$("tbody").html(rows);
}
/* Create new Item */
$(".crud-submit").click(function(e){
e.preventDefault();
var form_action = $("#create-item").find("form").attr("action");
var title = $("#create-item").find("input[name='title']").val();
var description = $("#create-item").find("textarea[name='description']").val();
$.ajax({
dataType: 'json',
type:'POST',
url: form_action,
data:{title:title, description:description}
}).done(function(data){
getPageData();
$(".modal").modal('hide');
toastr.success('Item Created Successfully.', 'Success Alert', {timeOut: 5000});
});
});
/* Remove Item */
$("body").on("click",".remove-item",function(){
var id = $(this).parent("td").data('id');
var c_obj = $(this).parents("tr");
$.ajax({
dataType: 'json',
type:'delete',
url: url + '/' + id,
}).done(function(data){
c_obj.remove();
toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});
getPageData();
});
});
/* Edit Item */
$("body").on("click",".edit-item",function(){
var id = $(this).parent("td").data('id');
var title = $(this).parent("td").prev("td").prev("td").text();
var description = $(this).parent("td").prev("td").text();
$("#edit-item").find("input[name='title']").val(title);
$("#edit-item").find("textarea[name='description']").val(description);
$("#edit-item").find("form").attr("action",url + '/update/' + id);
});
/* Updated new Item */
$(".crud-submit-edit").click(function(e){
e.preventDefault();
var form_action = $("#edit-item").find("form").attr("action");
var title = $("#edit-item").find("input[name='title']").val();
var description = $("#edit-item").find("textarea[name='description']").val();
$.ajax({
dataType: 'json',
type:'POST',
url: form_action,
data:{title:title, description:description}
}).done(function(data){
getPageData();
$(".modal").modal('hide');
toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});
});
});
Ok, now we are ready to run our CRUD Application example. So let's run bellow command on your root directory for quick run:
php -S localhost:8000
Now you can open bellow URL on your browser:
http://localhost:8000/
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Use Sweet Alert for Delete Confirm in Codeigniter?
- How to Create a Custom Library in CodeIgniter?
- Codeigniter Crop Image Before Upload Example
- Codeigniter Get Last Executed Query Log Example
- Codeigniter Stripe Payment Gateway Integration Example
- How to Call Model Function from Another Model in Codeigniter?
- Codeigniter Dynamic Highcharts Example
- Codeigniter Delete Multiple Rows using Checkbox Example
- PHP CRUD Operation Using Ajax and JQuery Example
- Codeigniter Select2 Ajax Autocomplete from Database Example
- How to Get Current URL with Query String in Codeigniter?
- How to Get Current URL in Codeigniter?
- Laravel AJAX CRUD Tutorial Example
- How to Get IP Address in Codeigniter?
- Codeigniter 3 and AngularJS CRUD with Search and Pagination Example.