With this Codeigniter Ajax CRUD using datatables Example Tutorial you will learn how to create a basic crud operation in Codeigniter Ajax using the datatables.
Here’s a step-by-step guide to setting up AJAX CRUD functionality with DataTables and Bootstrap modals in CodeIgniter 4:
Step 1: Install CodeIgniter 4
- Download CodeIgniter 4 from the official website: CodeIgniter Installation.
- Extract the zip file into the
xampp/htdocs
directory. - Configure the
.env
file to set up your database connection:
database.default.hostname = localhost
database.default.database = your_database_name
database.default.username = your_username
database.default.password = your_password
database.default.DBDriver = MySQLi
Step 2: Create the Database Table
Execute the following SQL commands to establish a table named items
in your database:
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Step 3: Develop the Model
In the app/Models
directory, create a model file named ItemModel.php
with the following content:
<?php
namespace App\Models;
use CodeIgniter\Model;
class ItemModel extends Model
{
protected $table = 'items';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'description'];
public function getItems() {
return $this->findAll();
}
public function getItem($id) {
return $this->find($id);
}
}
Step 4: Create the Controller
In the app/Controllers
directory, create a file named Items.php
:
<?php
namespace App\Controllers;
use App\Models\ItemModel;
use CodeIgniter\HTTP\ResponseInterface;
class Items extends BaseController
{
public function __construct()
{
$this->itemModel = new ItemModel();
}
public function index()
{
return view('items_view');
}
public function fetchItems()
{
$items = $this->itemModel->getItems();
return $this->response->setJSON($items);
}
public function insertItem()
{
$data = [
'name' => $this->request->getPost('name'),
'description' => $this->request->getPost('description')
];
$this->itemModel->insert($data);
return $this->response->setJSON(['status' => true]);
}
public function getItem($id)
{
$item = $this->itemModel->getItem($id);
return $this->response->setJSON($item);
}
public function updateItem()
{
$data = [
'name' => $this->request->getPost('name'),
'description' => $this->request->getPost('description')
];
$this->itemModel->update($this->request->getPost('id'), $data);
return $this->response->setJSON(['status' => true]);
}
public function deleteItem($id)
{
$this->itemModel->delete($id);
return $this->response->setJSON(['status' => true]);
}
}
Step 5: Design the Views
Create a view named items_view.php
in the app/Views
directory:
<!DOCTYPE html>
<html>
<head>
<title>AJAX CRUD Operations with DataTables in CodeIgniter 4</title>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
<div class="container">
<h2>AJAX CRUD with DataTables in CodeIgniter 4</h2>
<button id="btnAdd" class="btn btn-success">Add New</button>
<table id="table_id" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<!-- Bootstrap Modal for Add/Edit -->
<div class="modal fade" id="modal_form" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Item Form</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="form">
<input type="hidden" name="id"/>
<div class="form-group">
<label for="name" class="col-form-label">Name:</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="form-group">
<label for="description" class="col-form-label">Description:</label>
<textarea class="form-control" id="description" name="description"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="btnSave" onclick="save()">Save</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var save_method;
var table;
$(document).ready(function() {
table = $('#table_id').DataTable({
"ajax": {
"url": "<?php echo site_url('items/fetchItems')?>",
"type": "GET"
},
});
$('#btnAdd').click(function(){
save_method = 'add';
$('#form')[0].reset();
$('#modal_form').modal('show');
});
});
function save() {
var url;
if (save_method == 'add') {
url = "<?php echo site_url('items/insertItem')?>";
} else {
url = "<?php echo site_url('items/updateItem')?>";
}
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data) {
$('#modal_form').modal('hide');
table.ajax.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error adding / updating data');
}
});
}
function edit_item(id) {
save_method = 'update';
$('#form')[0].reset();
$.ajax({
url : "<?php echo site_url('items/getItem')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data) {
$('[name="id"]').val(data.id);
$('[name="name"]').val(data.name);
$('[name="description"]').val(data.description);
$('#modal_form').modal('show');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error fetching data');
}
});
}
function delete_item(id) {
if(confirm('Are you sure you want to delete this item?')) {
$.ajax({
url : "<?php echo site_url('items/deleteItem')?>/" + id,
type: "POST",
dataType: "JSON",
success: function(data) {
$('#modal_form').modal('hide');
table.ajax.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error deleting data');
}
});
}
}
</script>
</body>
</html>
Step 6: Include DataTables and jQuery Libraries
Ensure you have included the necessary DataTables and jQuery libraries in your items_view.php
:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
Step 7: Test Your Application
Access the application by navigating to: http://localhost/your_project_name/public/products
in your web browser to test the functionality.