Skip to Content
PHPCODE
CRUD operation in Codeigniter using Ajax
codeigniter code / September 26, 2021

In CodeIgniter, CRUD Operations are the most often used web application capability. The CRUD (Create, Read, Update, and Delete) actions in CodeIgniter are used to manipulate data in the database (Fetch, Insert, Update, and Delete). When an action is requested in a CodeIgniter CRUD application, the page is usually refreshed and forwarded. CRUD activities can also be implemented in CodeIgniter without requiring a page refresh by utilising jQuery and Ajax.

Integrate this functionality without reloading the page if you want to make the CodeIgniter CRUD feature more user-friendly. In this article, we’ll teach you how to use jQuery and Ajax to provide CRUD functionality in CodeIgniter without having to reload the page. Using jQuery, Ajax, and MySQL, the example script shows how to incorporate data management (view, add, edit, and remove) features into the CodeIgniter 3 framework.

To construct a CodeIgniter CRUD application with Bootstrap 4 using jQuery, Ajax, and MySQL, the following functionality will be built.

Get the members’ information from the database and display it on a web page.
Fill in the blanks in the database with information about the members.
In the database, edit and update member information.
Remove all member information from the database.
The procedures of add/edit/delete will work on a single page without requiring a page refresh.
Examine the file structure before beginning to build a CodeIgniter AJAX CRUD application.

 

codeigniter_ajax_crud/
├── application/
│   ├── controllers/
│   │   └── Members.php
│   ├── models/
│   │   └── Member.php
│   └── views/
│       ├── templates/
│       │   ├── header.php
│       │   └── footer.php
│       └── members/
│           ├── index.php
│           └── view.php
└── assets/
    ├── css/
    ├── js/
    ├── images/
    └── bootstrap/

Make a database table.

A table in the database must be built to store and handle the data. In the MySQL database, the following SQL creates a members table with some basic fields.

CREATE TABLE `members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`gender` enum('Male','Female') COLLATE utf8_unicode_ci NOT NULL,
`country` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config \

autoload.php
Define the widely used library and helper to load automatically on every request in the config/autoload.php file.

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

the supervisor (Members.php)
Based on an AJAX POST request, the Members controller executes CRUD activities (view, add, edit, and remove).

__construct() – Loads the Member model, which is used to handle database-related tasks.

index() – Using the getRows() method, fetch all member records from the database and give data to the view for listing.

memData() — Retrieves data from the database for a single member depending on their ID. The member data is returned in JSON format.

listView() – Retrieves all data from the database for all members. The data is returned in HTML format.

add() is a function that is used to add items to a

Using an AJAX request, get the data from the form fields.

Validate the data entered into the form fields.

The insert() method of the Member model is used to store member data in the database.
Returns the AJAX response in JSON format.
edit() — Gets and validates data from form fields sent via AJAX request.
Using the update() method of the Member model, update member data in the database based on the ID.
Returns the AJAX response in JSON format.
delete() – Using the ID provided by the AJAX request, delete member data from the database.
The status is returned in JSON format.

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Members extends CI_Controller {
function __construct() {
parent::__construct();
// Load member model
$this->load->model('member');
}
public function index(){
$data = array();
// Get rows count
$conditions['returnType'] = 'count';
$rowsCount = $this->member->getRows($conditions);
// Get rows
$conditions['returnType'] = '';
$data['members'] = $this->member->getRows($conditions);
$data['title'] = 'Members List';
// Load the list page view
$this->load->view('templates/header', $data);
$this->load->view('members/index', $data);
$this->load->view('templates/footer');
}
public function memData(){
$id = $this->input->post('id');
if(!empty($id)){
// Fetch member data
$member = $this->member->getRows(array('id'=>$id));
// Return data as JSON format
echo json_encode($member);
}
}
public function listView(){
$data = array();
// Fetch all records
$data['members'] = $this->member->getRows();
// Load the list view
$this->load->view('members/view', $data);
}
public function add(){
$verr = $status = 0;
$msg = '';
$memData = array();
// Get user's input
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$gender = $this->input->post('gender');
$country = $this->input->post('country');
// Validate form fields
if(empty($first_name) || empty($last_name)){
$verr = 1;
$msg .= 'Please enter your name.<br/>';
}
if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
$verr = 1;
$msg .= 'Please enter a valid email.<br/>';
}
if(empty($country)){
$verr = 1;
$msg .= 'Please enter your country.<br/>';
}
if($verr == 0){
// Prepare member data
$memData = array(
'first_name'=> $first_name,
'last_name' => $last_name,
'email' => $email,
'gender' => $gender,
'country' => $country
);
// Insert member data
$insert = $this->member->insert($memData);
if($insert){
$status = 1;
$msg .= 'Member has been added successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}
public function edit(){
$verr = $status = 0;
$msg = '';
$memData = array();
$id = $this->input->post('id');
if(!empty($id)){
// Get user's input
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$gender = $this->input->post('gender');
$country = $this->input->post('country');
// Validate form fields
if(empty($first_name) || empty($last_name)){
$verr = 1;
$msg .= 'Please enter your name.<br/>';
}
if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
$verr = 1;
$msg .= 'Please enter a valid email.<br/>';
}
if(empty($country)){
$verr = 1;
$msg .= 'Please enter your country.<br/>';
}
if($verr == 0){
// Prepare member data
$memData = array(
'first_name'=> $first_name,
'last_name' => $last_name,
'email' => $email,
'gender' => $gender,
'country' => $country
);
// Update member data
$update = $this->member->update($memData, $id);
if($update){
$status = 1;
$msg .= 'Member has been updated successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}
}else{
$msg .= 'Some problem occurred, please try again.';
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}
public function delete(){
$msg = '';
$status = 0;
$id = $this->input->post('id');
// Check whether member id is not empty
if(!empty($id)){
// Delete member
$delete = $this->member->delete($id);

if($delete){
$status = 1;
$msg .= 'Member has been removed successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}else{
$msg .= 'Some problem occurred, please try again.';
} 
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}
}
Modeling (Member.php)
The database operations are handled by the Member model (Fetch, Add, Edit, and Delete).
Define the table name with __construct().
getRows() – Retrieves the members’ data from the database using the parameters supplied in $params. If successful, returns the data array; if unsuccessful, returns FALSE.
insert() — Inserts data from a member into the database. If successful, returns the row ID; if unsuccessful, returns FALSE.
update() – Based on the row ID, update member data in the database. If the function succeeds, it returns TRUE; if it fails, it returns FALSE.
remove() – Using the row ID, delete a record from the database. If the function succeeds, it returns TRUE; if it fails, it returns FALSE.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Member extends CI_Model{
function __construct() {
// Set table name
$this->table = 'members';
}
/*
* Fetch members data from the database
* @param array filter data based on the passed parameters
*/
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->table);
if(array_key_exists("conditions", $params)){
foreach($params['conditions'] as $key => $val){
$this->db->where($key, $val);
}
}
if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
$result = $this->db->count_all_results();
}else{
if(array_key_exists("id", $params)){
$this->db->where('id', $params['id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('first_name', 'asc');
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
}
}
// Return fetched data
return $result;
}
/*
* Insert members data into the database
* @param $data data to be insert based on the passed parameters
*/
public function insert($data = array()) {
if(!empty($data)){
// Add created and modified date if not included
if(!array_key_exists("created", $data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified", $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
// Insert member data
$insert = $this->db->insert($this->table, $data);
// Return the status
return $insert?$this->db->insert_id():false;
}
return false;
}
/*
* Update member data into the database
* @param $data array to be update based on the passed parameters
* @param $id num filter data
*/
public function update($data, $id) {
if(!empty($data) && !empty($id)){
// Add modified date if not included
if(!array_key_exists("modified", $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
// Update member data
$update = $this->db->update($this->table, $data, array('id' => $id));
// Return the status
return $update?true:false;
}
return false;
}
/*
* Delete member data from the database
* @param num filter data based on the passed parameter
*/
public function delete($id){
// Delete member data
$delete = $this->db->delete($this->table, array('id' => $id));
// Return the status
return $delete?true:false;
}
}

1. templates/ The views/templates/ directory contains the web page’s element sections (header, footer, etc.).

templates/header.php (version 1.1)
The header.php file contains the web page’s header.

In CodeIgniter, jQuery and Ajax are utilised to handle CRUD activities without refreshing the page, thus be sure to include the jQuery library.
The Bootstrap framework is used to style the data table, form fields, and links, as well as to add a modal dialogue popup to the web page. As a result, include the Bootstrap 4 CSS and JS library files.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $title; ?> | CodeIgniter CRUD without Page Refresh</title>
<!-- jQuery library -->
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
<!-- Bootstrap library -->
<link rel="stylesheet" href="<?php echo base_url('assets/bootstrap/bootstrap.min.css'); ?>">
<script src="<?php echo base_url('assets/bootstrap/bootstrap.min.js'); ?>"></script>
<!-- Stylesheet file -->
<link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>">
</head>
<body>
templates/footer.php (1.2)
The footer.php file contains the web page’s footer.
</body>
</html>

2. members/ The views/members/ directory contains the Members controller’s view files.

members/index.php (version 2.1)
This view displays all of the member’s information in a tabular manner and uses jQuery and Ajax to handle CRUD (View, Add, Edit/Update, and Delete) requests.

HTML Code: The member’s information is first retrieved from the database and shown in an HTML table with Edit and Delete buttons.

An Add link is added at the top of the data list to start the create request.
When you click the Add button, a Bootstrap modal popup with an HTML form to add a new member displays.
When you click the Edit button, a Bootstrap modal box with an HTML form and pre-filled data displays, allowing you to amend the member’s information.
A confirmation dialogue comes when you click the Delete button. Following confirmation, a delete request is sent to the database to remove the record.

<div class="container">
<!-- Display status message -->
<div class="statusMsg"></div>
<div class="row">
<div class="col-md-12 head">
<h5><?php echo $title; ?></h5>
<!-- Add link -->
<div class="float-right">
<a href="javascript:void(0);" class="btn btn-success" data-type="add" data-toggle="modal" data-target="#modalUserAddEdit"><i class="plus"></i> New Member</a>
</div>
</div>
<!-- Data list table --> 
<table class="table table-striped table-bordered">
<thead class="thead-dark">
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Gender</th>
<th>Country</th>
<th>Action</th>
</tr>
</thead>
<tbody id="userData">
<?php if(!empty($members)){ foreach($members as $row){ ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['last_name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['gender']; ?></td>
<td><?php echo $row['country']; ?></td>
<td>
<a href="javascript:void(0);" class="btn btn-warning" rowID="<?php echo $row['id']; ?>" data-type="edit" data-toggle="modal" data-target="#modalUserAddEdit">edit</a>
<a href="javascript:void(0);" class="btn btn-danger" onclick="return confirm('Are you sure to delete data?')?userAction('delete', '<?php echo $row['id']; ?>'):false;">delete</a>
</td>
</tr>
<?php } }else{ ?>
<tr><td colspan="7">No member(s) found...</td></tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<!-- Modal Add and Edit Form -->
<div class="modal fade" id="modalUserAddEdit" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title"><span id="hlabel">Add New</span> Member</h4>
<button type="button" class="close" data-dismiss="modal">&times;</button>
</div>
<!-- Modal Body -->
<div class="modal-body">
<div class="statusMsg"></div>
<form role="form">
<div class="form-group">
<label>First name</label>
<input type="text" class="form-control" name="first_name" id="first_name" placeholder="Enter first name" >
</div>
<div class="form-group">
<label>Last name</label>
<input type="text" class="form-control" name="last_name" id="last_name" placeholder="Enter last name" >
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" id="email" placeholder="Enter email" >
</div>
<div class="form-group">
<label>Gender</label>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="gender1" name="gender" class="custom-control-input" value="Male" checked="checked" >
<label class="custom-control-label" for="gender1">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="gender2" name="gender" class="custom-control-input" value="Female" >
<label class="custom-control-label" for="gender2">Female</label>
</div>
</div>
<div class="form-group">
<label>Country</label>
<input type="text" class="form-control" name="country" id="country" placeholder="Enter country" >
</div>
<input type="hidden" class="form-control" name="id" id="id"/>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="userSubmit">SUBMIT</button>
</div>
</div>
</div>
</div>

JavaScript Code: With the CodeIgniter application, the following JavaScript code handles Ajax requests.

getUsers() — Using the jQuery $.post() method, retrieve the members data from the Members controller (members/listView). The content of the member data list is updated with the response data if the request is successful.

userAction() – Using jQuery and Ajax, send add, edit, and remove requests to the Members controller (members/add | members/edit | members/delete). The user sees the response message if it is successful.

exhibited. bs.modal — The data-type property value is changed based on the add/edit request using this Bootstrap modal event.

When an Add request is made, the userAction() parameter is assigned to the onclick attribute of the submit button (#userSubmit) with the add parameter.

If an Edit request is made, the onclick attribute of the submit button (#userSubmit) with edit param is set as the userAction(). The editUser() function is also used to pre-fill the data of the member in the modal form depending on the rowID.

hidden.bs.modal — Removes the onclick attribute from the submit button (#userSubmit) using the Bootstrap modal event hidden.bs.modal. The modal form and web page also have the pre-filled form data and the status message deleted.

<script>
// Update the members data list
function getUsers(){
$.post( "<?php echo base_url('members/listView/'); ?>", function( data ){
$('#userData').html(data);
});
}
// Send CRUD requests to the server-side script
function userAction(type, id){
id = (typeof id == "undefined")?'':id;
var userData = '', frmElement = '';
if(type == 'add'){
frmElement = $("#modalUserAddEdit");
userData = frmElement.find('form').serialize();
}else if (type == 'edit'){
frmElement = $("#modalUserAddEdit");
userData = frmElement.find('form').serialize();
}else{
frmElement = $(".row");
userData = 'id='+id;
}
frmElement.find('.statusMsg').html('');
$.ajax({
type: 'POST',
url: '<?php echo base_url('members/'); ?>'+type,
dataType: 'JSON',
data: userData,
beforeSend: function(){
frmElement.find('form').css("opacity", "0.5");
},
success:function(resp){
frmElement.find('.statusMsg').html(resp.msg);
if(resp.status == 1){
if(type == 'add'){
frmElement.find('form')[0].reset();
}
getUsers();
}
frmElement.find('form').css("opacity", "");
}
});
}
// Fill the user's data in the edit form
function editUser(id){
$.post( "<?php echo base_url('members/memData/'); ?>", {id: id}, function( data ){
$('#id').val(data.id);
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#email').val(data.email);
$('input:radio[name="gender"]').filter('[value="'+data.gender+'"]').attr('checked', true);
$('#country').val(data.country);
}, "json");
}
// Actions on modal show and hidden events
$(function(){
$('#modalUserAddEdit').on('show.bs.modal', function(e){
var type = $(e.relatedTarget).attr('data-type');
var userFunc = "userAction('add');";
$('#hlabel').text('Add New');
if(type == 'edit'){
userFunc = "userAction('edit');";
var rowId = $(e.relatedTarget).attr('rowID');
editUser(rowId);
$('#hlabel').text('Edit');
}
$('#userSubmit').attr("onclick", userFunc);
});
$('#modalUserAddEdit').on('hidden.bs.modal', function(){
$('#userSubmit').attr("onclick", "");
$(this).find('form')[0].reset();
$(this).find('.statusMsg').html('');
});
});
</script>

members/view.php (version 2.2)
The listView() method of the Members controller uses this view to display the members’ data in HTML format.

<?php if(!empty($members)){ foreach($members as $row){ ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['last_name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['gender']; ?></td>
<td><?php echo $row['country']; ?></td>
<td>
<a href="javascript:void(0);" class="btn btn-warning" rowID="<?php echo $row['id']; ?>" data-type="edit" data-toggle="modal" data-target="#modalUserAddEdit">edit</a>
<a href="javascript:void(0);" class="btn btn-danger" onclick="return confirm('Are you sure to delete data?')?userAction('delete', '<?php echo $row['id']; ?>'):false;">delete</a>
</td>
</tr>
<?php } }else{ ?>
<tr><td colspan="7">No member(s) found...</td></tr>
<?php } ?>

Note :

Our sample AJAX CRUD application with CodeIgniter and MySQL demonstrates how to use the CodeIgniter framework to build data management features without having to reload the page. To manage data in the database, the user does not need to visit the pages. Using jQuery and Ajax, you can implement the add, edit, update, and delete functions with the MySQL database. The CRUD operations can be readily incorporated without page refresh using the CodeIgniter sample Ajax CRUD application.

 

 

 

 

PHPCODE © 2024