Hello, you will learn CodeIgniter 4 CRUD Ajax in this tutorial. We saw the CodeIgniter 4 CRUD (Create, Read, Update, Delete) example in the previous article, however, in this tutorial, I built the Ajax approach.
We will use ajax to deliver requests to the Codeigniter 4 Controller function in this project, which will make the website much faster.
The use of ajax in CRUD processes speeds up and improves the responsiveness of a website, allowing modifications to be made without reloading the page.
Bootstrap:Â The frontend files were created using the Bootstrap framework. In addition, I used the bootstrap modal to do CRUD operations on a single page (index.php). There is no need to make any more files.
SweetAlert:Â To show CRUD operations messages in an animated style, I used the SweetAlert JavaScript library.
Table Content
1. Download Codeigniter 4
2. Turn Development Mode On
3. Enable Codeigniter Errors
4. Basic Configurations
5. Make Database And Table
6. Database Connection
7. Create Model
8. Loading url Helper
9. Creat Controller
    #9.1 Create Record
    #9.2 Read Record
    #9.3 Update Record
    #9.4 Delete Record
1. Download Codeigniter 4
In this step, you'll download the most recent version of Codeigniter 4 and unzip the setup into xampp/htdocs/ on your local server. Change the name of the download folder to "Codeigniter-4-CRUD-Ajax."
If you're using WampServer, extract CodeIgniter to the www folder. If you're using XAMPP, extract it to the htdocs folder.
In the public folder, I've already included the bootstrap package, jQuery library, and SweetAlert library.
look at the files structure:
xampp/
├── htdocs/
├── Codeigniter-4-CRUD-Ajax/
├── app/
├── controllers/
│ └── BaseController
│ └── Home
│ └── StudentController
├── Models/
│ └── StudentModel
├── Views
│ └── frontend.php
│ └── index.php
public/
├── bootstrap/
│ ├── css/
│ │ └── bootstrap.min.js
│ ├── js/
│ │ └── bootstrap.min.js
│ ├── fonts/
│ │ └── glyphicons-halflings-regular.eot
│ │ └── glyphicons-halflings-regular.svg
│ │ └── glyphicons-halflings-regular.ttf
│ │ └── glyphicons-halflings-regular.woff
│ │ └── glyphicons-halflings-regular.woff2
├── js/
│ └── jquery-1.12.4-jquery.min.js
├── sweetalert/
│ └── sweetalert.min.js
│system
│writable
│env
2. Turn Development Mode On
We have an env file at the root of the CodeIgniter 4 installation.
By default, CodeIgniter starts in production mode. Now let us use it in development mode first. So that if we run into trouble while working, an error message will appear.
# CI_ENVIRONMENT = production
Remove # and update it to
CI_ENVIRONMENT = development
3. Enable Codeigniter Errors
Before we begin developing an Ajax CRUD application in the Codeigniter 4 framework, we must first enable Codeigniter 4 errors. This step is necessary because if we do not enable the display of errors on the web page, we will be unable to determine where the issue occurred.
Set display errors to 1 instead of 0 in the app/Config/Boot/development.php file.
ini_set('display_errors', '1');
After that, we must enter the app/Config/Boot/production.php file and change the value of display errors to 1 instead of 0.
ini_set('display_errors', '1');
4. Basic Configurations
Next, on the app/config/app.php file, you'll specify some basic setup, so navigate to application/config/config.php and open it in a text editor.
Then, as shown below, empty the index page "index.php" from this file. Change the public $indexPage =" " as shown below.
public $baseURL = 'http://localhost:8080';
to
*
* @var string
*/
public $baseURL = 'http://localhost/Codeigniter-4-CRUD-Ajax/';
/**
* --------------------------------------------------------------------------
* Index File
* --------------------------------------------------------------------------
*
* Typically this will be your index.php file, unless you've renamed it to
* something else. If you are using mod_rewrite to remove the page set this
* variable so that it is blank.
*
* @var string
*/
public $indexPage = '';
5. Make Database And Table
You need to construct a database called codeigniter_ajax_crud_db in this stage. Create a database with the name codeigniter_ajax_cru in your PHPMyAdmin.
After you've successfully created a database, run the SQL statement below to create a student table in it.
CREATE TABLE `tbl_student` (
`student_id` int(11) NOT NULL,
`firstname` varchar(40) NOT NULL,
`lastname` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
6. Database Connection
You must connect our project to the database in this stage. Open the database.php file in a text editor by going to app/Config/Database.php. You must set up database details in this file after opening it in a text editor, as shown below.
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'codeigniter_ajax_crud_db',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
7. Create Model
The schema, which is a prototype of table values, is defined using the model. So, under the app/Models/ folder, we must declare a new StudentModel.php file. To create the Student Model, add the following code to the same file.
The name of the database table must be defined in the $table variable of this class.
protected $table = 'tbl_student';
The primary key for the student table must be defined in the $primaryKey variable.
protected $primaryKey = 'student_id';
We must define table fields names (firstname, lastname) in the $allowedFields variable, which will be utilized for database operations.
protected $allowedFields = ['firstname','lastname'];
app/Models/StudentModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class StudentModel extends Model
{
protected $DBGroup = 'default';
protected $table = 'tbl_student';
protected $primaryKey = 'student_id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = 'array';
protected $useSoftDelete = false;
protected $protectFields = true;
protected $allowedFields = ['firstname','lastname'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
}
8. Loading url Helper
Search for $helpers in the app\Controllers\BaseController.php file, then add this url helper to the $helpers array.
The base url() and site url() functions will be loaded by this url helper.
protected $helpers = [ ];
to
protected $helpers = ['url'];
9. Creat Controller
In this section of the tutorial, we'll create a new controller called StudentController.php in the app\Controllers folder. This controller will handle ajax() requests and conduct operations like Insert, Update, Delete, and View.
We'll go over each function in this controller one by one to execute CRUD tasks.
First, Display the index page:
First, we import the StudentModel class for database operations in this class file.
index() – This function displays the default index page for our webpage.
app/Controllers/StudentController.php
<?php
namespace App\Controllers;
use App\Models\StudentModel;
class StudentController extends BaseController
{
// view index file
public function index()
{
return view('index');
}
// create new student records
public function CreateStudent()
{
}
//fetch all students records
public function ReadStudent()
{
}
//edit or get specific student record id
public function EditStudent()
{
}
// update existing student records
public function UpdateStudent()
{
}
// delete existing student records
public function DeleteStudent()
{
}
}
Add Routes,
From the /app/Config folder, open Routes.php. This route should be added to it.
I commented on default Home::index, which triggers Codeigniter 4 to open the default index page.
Our URL route, which shows our index.php file, is included.
Our controller is StudentController, and the function index displays our index.php file.
\app\Config\Routes.php
//$routes->get('/', 'Home::index');
$routes->get('/', 'StudentController::index');
Create a frontend.php structure file in the /app/Views directory. This is the theme for the parent. Open the frontend.php file and paste the following code into it.
Look at how I incorporated the bootstrap CSS and JS library before closing the /head> tag. Also included is the jQuery library, which assists in CRUD operations via the $.ajax() function.
I also integrated the SweetAlert JavaScript library, which displays each CRUD operation notification with an animated effect.
We'll transform this template file to an index.php file and use its body to dynamically attach page views.
Look at the renderSection() method's one argument, "body," which is the section's name. This allows us to include our body content.
/app/Views/frontend.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>Codeigniter 4 CRUD Ajax - Onlyxcodes</title>
<link rel="stylesheet" href="<?= base_url('public/bootstrap/css/bootstrap.min.css') ?>">
<script src="<?= base_url('public/js/jquery-1.12.4-jquery.min.js') ?>"></script>
<script src="<?= base_url('public/bootstrap/js/bootstrap.min.js') ?>"></script>
<script src="<?= base_url('public/sweetalert/sweetalert.min.js') ?>"></script>
</head>
<body>
<?= $this->renderSection("body") ?>
</body>
</html>
Note:- I've created CRUD operations in the index.php file. I've put all jQuery and Ajax codes, as well as the bootstrap, insert modal, and update modal, in the index.php file.
#9.1 Create Record:
We loaded our index.php file in the previous step. You will now learn how to insert data into the table in this stage.
To open a Bootstrap modal, we first needed an insert button.
The bootstrap insert modal is opened by clicking the button below. I included the button codes in the index.php file separately.
data-toggle="modal" –  it opens the bootstrap insert modal window
data-target="#addModal" – This attribute will open an insert modal with the addModal Id attribute.
<button data-toggle="modal" data-target="#addModal" class="btn btn-warning"><span class="glyphicon glyphicon-plus"></span> Add Student</button>
Bootstrap Insert Modal
To insert new records, we needed to use the bootstrap modal.
Below is bootstrap insert modal codes. The code I have included in the index.php file separately.Â
This bootstrap modal has the id="addModal" attribute target Id for the data-target="#addModal" attribute.
When a user clicks the Add Student button, a window appears that comprises two fields (first name and last name) and two buttons ( insert and close).
And after a user fills out the form fields, we'll submit this bootstrap modal form request using jQuery and the $.ajax() method.
Two-span tags are accessible after input tags. The error messages from the ajax() method are displayed in this span tag.
<!-- Add Modal Start-->
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ModalLabel">Create New Student</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="addStudent" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">Firstname:</label>
<div class="col-sm-10">
<input type="text" id="txt_firstname" class="form-control" placeholder="enter firstname">
<span id="error_firstname" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Lastname:</label>
<div class="col-sm-10">
<input type="text" id="txt_lastname" class="form-control" placeholder="enter lastname">
<span id="error_lastname" class="text-danger"></span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btn_insert" class="btn btn-success">Insert</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Add Modal End-->
jQuery Ajax Codes
When the users pressed the insert button, the click() method caused and triggered a button click event. The bootstrap modal insert button's id attribute value is #btn_insert.
Before proceeding to the $.ajax() procedure, the JavaScript checks for form validation. No fields are left blank due to the JavaScript validation check.
If no JavaScript validation is conducted, the $.ajax() method is called. This function's job is to submit a form request to the URL "create-student" using the HTTP POST method and get a response from the server without reloading the page.
<script>
$(document).ready(function(){
displaystudent();
$(document).on('click','#btn_insert',function(){
var firstname = $('#txt_firstname').val();
var lastname = $('#txt_lastname').val();
if(firstname == ''){
error_firstname = 'please enter firstname';
$('#error_firstname').text(error_firstname);
}
else if(lastname == ''){
error_lastname = 'please enter lastname';
$('#error_lastname').text(error_lastname);
}
else{
$.ajax({
url:'<?= site_url('create-student') ?>',
method:'post',
data:
{
student_firstname:firstname,
student_lastname:lastname
},
success:function(response){
$('#addModal').modal('hide');
$('#addModal').find('input').val('');
$('#error_firstname').text('');
$('#error_lastname').text('');
$('#tableData').html('');
displaystudent();
swal("Inserted", response.status, "success");
}
});
}
});
});
More Explanation:
#txt_firstname is the id attribute value for the first name text box. Using this attribute value, the val() method fetches the value of the first name text field.
#txt_lastname is the id attribute value for the last name text field. Using this property value, the val() method retrieves the value of the last name text box.
The create-student URL is stored in the site_url() function, which we will put in the Routes.php file.
The success function displays inserted data within the <tbody> tag. #tableData is the value of the <tbody> tag's id property.
The SweetAlert's swal() function displays an animated insert successfully message.
The response.status parameter is provided in the swal() function. The insert successful message is stored in the status variable, which is returned by the CreateStudent() function.
The displaystudent() function loads all table records; we'll go over these function codes in the upcoming section.
$('#addModal').modal('hide'); – this code hide the modal.
The find() function finds all input tags after records have been inserted in the bootstrap modal and blank them.
$('#addModal').find('input').val(''); – After inserting data, this code clears all fields.
After inserting data, the $('#error_firstname').text(' ') and $('#error_lastname').text(' ') codes blank all error messages.
$('#tableData').html(' '); – After data has been inserted, this code removes duplicate HTML data from the table body.
The id attribute value of the bootstrap inserts modal is #addModal.
Routes.php file discussion,
From the /app/Config folder, open Routes.php. Incorporate the routes listed below.
The URL of the $.ajax() function URL property, which we mentioned in the $.ajax() method, is create-student.
Our controller is StudentController, and CreateStudent is the function that adds new records to the database. In the next phase, we'll create.
\app\Config\Routes.php
$routes->post('/create-student', 'StudentController::CreateStudent');
StudentController.php file discussion,
CreateStudent() – This function is used to insert new data into the MySQL database.
Created StudentModel class object name is $StudentModel.
Inside $data [ ] array,
To extract data property values from a user-inputted $.ajax() function, I used the getPost() method.
The ajax() data property has two values: student_firstname and student_lastname. The values of these variables are determined by the first name and last name variables.
The $data array variable should be included in the save() procedure.
If no errors occur, the save() method will be used to add a new record to the student table.
We set to insert a successful message and set the $data variable to hold field values inside an array. This array is assigned to the variable $output.
Paste the $output variable into the setJSON() method, which converts all results to JSON and returns them all.
app/Controllers/StudentController.php
<?php
namespace App\Controllers;
use App\Models\StudentModel;
class StudentController extends BaseController
{
// view index file
public function index()
{
return view('index');
}
// create new student records
public function CreateStudent()
{
$StudentModel = new StudentModel();
$data = [
'firstname' => $this->request->getPost("student_firstname"),
'lastname' => $this->request->getPost("student_lastname"),
];
$StudentModel->save($data);
$output = array('status' => 'Student Inserted Successfully', 'data' => $data);
return $this->response->setJSON($output);
}
//fetch all students records
public function ReadStudent()
{
}
//edit or get specific student record id
public function EditStudent()
{
}
// update existing student records
public function UpdateStudent()
{
}
// delete existing student records
public function DeleteStudent()
{
}
}
The bootstrap inserts modal comes when a user clicks the add button:
The result of the swal() function after data has been added is as follows:
#9.2 Read Record:
jQuery Ajax Code
Within jQuery coding, I created the displaystudent() function separately.
The responsibility of the $.ajax() function is to use the HTTP GET method to send a request to the URL "fetch-student" and acquire a tabular response from the server without reloading the page.
The each() method of the success() function displays table data in tabular form.
response.allstudents is available in the each() method. The allstudents variable is an array variable that is returned by the ReadStudent() function and contains the values of all table rows.
function displaystudent()
{
$.ajax({
url:'<?= site_url('fetch-student') ?>',
method:'get',
success:function(response){
$.each(response.allstudents,function(key, value){
$('#tableData').append('<tr>\
<td> '+value['student_id']+' </td>\
<td> '+value['firstname']+' </td>\
<td> '+value['lastname']+' </td>\
<td>\
<a id="btn_edit" table-id='+value['student_id']+' data-toggle="modal" data-target="#updateModal" class="btn btn-warning">Edit</a>\
</td>\
<td>\
<a id="btn_delete" table-id='+value['student_id']+' class="btn btn-danger">Delete</a>\
</td>\
</tr>');
});
}
});
}
More Explanation:
The fetch-student URL is stored in the site_url() function, which we will put in the Routes.php file.
The id attribute of the <tbody> tag is #tableData. The <tbody> tag contains all of the data.
Look at the last two columns, where there is two edit and delete hyperlinks.
The edit link takes you to the bootstrap edit modal, which includes the edit form.
The table id value is contained in the edit hyperlink table-id property attribute value. In the next step, we'll use this to edit a specific record.
When you click the delete hyperlink next to a certain record, the data is removed.
The table id information is also stored in the delete hyperlink table-id property attribute value. In the next step, we'll use this to delete certain table row records.
Table Codes
Look at the table codes below. I made it in the index.php file independently. Through the $.ajax() technique, all database records are loaded into the <tbody> tag.
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
Routes.php Discussion,
From the /app/Config folder, open Routes.php file. Include the routes mentioned below.
The URL of the $.ajax() function, which we covered in the displaystudent() function, is fetch-student.
Our controller is StudentController, and the ReadStudent method displays all table records.Â
\app\Config\Routes.php
$routes->get('/fetch-student', 'StudentController::ReadStudent');
StudentController.php file discussion,
ReadStudent() – We built an object of the StudentModel class in this function, and we used this object to fetch data from the table using the findAll() method.
If $StudentModel->findAll(); is called correctly, it will return all of the data in the $data array variable.
Set all of the data in the student table to JSON format and return it with the setJSON() method.
app/Controllers/StudentController.php
<?php
namespace App\Controllers;
use App\Models\StudentModel;
class StudentController extends BaseController
{
// view index file
public function index()
{
return view('index');
}
// create new student records
public function CreateStudent()
{
}
//fetch all students records
public function ReadStudent()
{
$StudentModel = new StudentModel();
$data['allstudents'] = $StudentModel->findAll();
return $this->response->setJSON($data);
}
//edit or get specific student record id
public function EditStudent()
{
}
// update existing student records
public function UpdateStudent()
{
}
// delete existing student records
public function DeleteStudent()
{
}
}
All records are displayed visually below :
#9.3 Update Record:
We need to show data from the click edit hyperlink before we can update data.
Ajax displaystudent() function codes have already been explained. Edit hyperlink was found in the last-second column.
The database table id values are stored in the table-id attribute value.
data-toggle="modal" – it is open the update modal windowÂ
data-target="#updateModal" – That attribute will open a specified modal with the
Examine the id property value btn_edit; we'll use this to handle the edit hyperlink click event in jQuery and Ajax.
<td>\
<a id="btn_edit" table-id='+value['student_id']+' data-toggle="modal" data-target="#updateModal" class="btn btn-warning">Edit</a>\
</td>\
Bootstrap Update Modal
This modal id="updateModal" attribute target Id for the attribute data-target="#updateModal" is bootstrap update modal code.
When a user hits the edit hyperlink, a modal appears that displays the database id row records that have been targeted.
This modal contains two buttons update and close.
When a user edits the form fields, we will submit this bootstrap modal form request using jQuery and the $.ajax() method.
Inside these modal codes, look before closing </form> tag an input hidden tag is available.Â
hidden_id is the value of the hidden tag's id property. In the next step, we'll use this attribute value to submit an edit id request to the server using the ajax() function.
Two-span tags are accessible after input tags. When a user does not fill in values, this span tag displays error messages. The ajax() method is responsible for the error messages.
<!-- Update Modal Start-->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ModalLabel">Update Student</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="updateStudent" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">Firstname:</label>
<div class="col-sm-10">
<input type="text" id="firstname_update" class="form-control" placeholder="enter firstname">
<span id="error_firstname_update" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Lastname:</label>
<div class="col-sm-10">
<input type="text" id="lastname_update" class="form-control" placeholder="enter lastname">
<span id="error_lastname_update" class="text-danger"></span>
</div>
</div>
<input type="hidden" id="hidden_id">
</form>
</div>
<div class="modal-footer">
<button type="button" id="btn_update" class="btn btn-primary">Update</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Update Modal End-->
jQuery & Ajax Codes
When a user clicked the edit hyperlink, the click() method caused and triggered a hyperlink click event. The Edit anchor tag's id attribute value is #btn_edit.
The variable student id is kept via $(this).attr('table-id').
The attr() method returns the table's current id value.
The $.ajax() function sends a request to the URL "edit-student" using the HTTP GET method and receives a response from the server in the bootstrap update modal fields without reloading the page.
$(document).on('click','#btn_edit', function(){
var student_id = $(this).attr('table-id');
$.ajax({
url:'<?= site_url('edit-student') ?>/',
method:'get',
data:{sid:student_id},
success:function(response){
$('#updateModal').modal('show');
$('#firstname_update').val(response.row.firstname);
$('#lastname_update').val(response.row.lastname);
$('#hidden_id').val(response.row.student_id);
}
});
});
More Explanation:
The edit-student URL is kept in the site_url() function, which we will implement in the Routes.php file.
The response.row is available in the val() method. The row is array variable originates from the EditStudent() function, and it displays the database id row records that have been targeted.
$('#updateModal').modal('show'); - this code show the update modal.
#firstname_update is the id attribute value for the first name text box. Using this attribute value, the val() method displays the edit value of the first name text field.
#lastname_update is the id attribute value for the last name text box. Using this property value, the val() method displays the edit value of the last name text box.
The id attribute value of the input type is hidden tag is #hidden_id. Before closing the </form> tag, have a look at this hidden tag in the bootstrap update modal.
The hidden tag will be used to update the database table id row entries that have been targeted.
Routes.php discussion,
From the /app/Config folder, open Routes.php. Integrate the routes described below.
The URL of the $.ajax() function URL attribute we described in the jQuery & Ajax code is edit-student.
Our controller is StudentController, and the function EditStudent displays specified database table id row records.
\app\Config\Routes.php
$routes->get('/edit-student', 'StudentController::EditStudent');
StudentController.php File Discussion,
EditStudent() – This function displays records with a specific id row.
Used getGet() method to get $.ajax() function data property current id values from the current edit hyperlink click event.
The value of the ajax() data property is sid. And the $id variable is in control of this variable's value.
In the find() method, pass the $id variable. If the table's id is found, the find() method returns the records.
The target id row records are stored in the row array variable. We return records from the setJSON() function, which creates records in the JSON format.
app/Controllers/StudentController.php
<?php
namespace App\Controllers;
use App\Models\StudentModel;
class StudentController extends BaseController
{
// view index file
public function index()
{
return view('index');
}
// create new student records
public function CreateStudent()
{
}
//fetch all students records
public function ReadStudent()
{
}
//edit or get specific student record id
public function EditStudent()
{
$StudentModel = new StudentModel();
$id = $this->request->getGet('sid');
$data['row'] = $StudentModel->find($id);
return $this->response->setJSON($data);
}
// update existing student records
public function UpdateStudent()
{
}
// delete existing student records
public function DeleteStudent()
{
}
}
Following the display of specific table id row data, we will now update specific id row data in this phase.
We've already seen that the update button is available in the bootstrap update modal.
<button type="button" id="btn_update" class="btn btn-primary">Update</button>
After a user edits a record and clicks the update button, we'll handle the button click event in the jQuery method and use the ajax() function to update the records.
jQuery Ajax Codes
When users pressed the update button, the click() method caused and triggered the update button click event. The bootstrap update modal update button's id attribute value is #btn_update.
Before continuing to the $.ajax() function, the JavaScript checks for form validation. No fields are left blank according to the JavaScript validation check.
If no JavaScript validation is executed, the $.ajax() method is called. This function's goal is to submit a form request to the URL "update-student" using the HTTP POST method and get a response from the server without reloading the page.
$(document).on('click','#btn_update', function(){
var firstname = $('#firstname_update').val();
var lastname = $('#lastname_update').val();
var hiddenId = $('#hidden_id').val();
if(firstname == ''){
error_firstname = 'please enter firstname';
$('#error_firstname_update').text(error_firstname);
}
else if(lastname == ''){
error_lastname = 'please enter lastname';
$('#error_lastname_update').text(error_lastname);
}
else{
$.ajax({
url:'<?= site_url('update-student') ?>',
method:'post',
data:
{
update_firstname:firstname,
update_lastname:lastname,
update_id:hiddenId
},
success:function(response){
$('#updateModal').modal('hide');
$('#error_firstname_update').text('');
$('#error_lastname_update').text('');
$('#tableData').html('');
displaystudent();
swal("Updated", response.status, "success");
}
});
}
});
More Explanation:
The update-student URL is saved in the site_url() function, which we will send in the Routes.php file.
#firstname_update is the id attribute value for the first name text box. Using this attribute value, the val() method retrieves the editable value of the first name text field.
#lastname_update is the id attribute value for the last name text field. Using this property value, the val() method retrieves the editable value of the last name text field.
The SweetAlert's swal() function displays an animated update successfully message.
The response.status element is included in the swal() function. The update successful message is stored in the status variable, which is returned by the UpdateStudent() function.
The displaystudent() function loads updated records.Â
$('#updateModal').modal('hide'); – this code hide the update modal.
$('#error_firstname_update').text(' ') and $('#error_lastname_update').text(' ') codes blank the all error messages after updated records.
$('#tableData').html(' '); – After data is updated, this code removes duplicate HTML data from the table body.
The bootstrap update modal's id attribute value is #updateModal.
Routes.php Discussion,
From the /app/Config folder, open Routes.php. Combine the routes indicated below.
The URL of the $.ajax() function URL property, which we mentioned in the $.ajax() method, is update-student.
Our controller is StudentController, and the UpdateStudent function updates existing records.
\app\Config\Routes.php
$routes->post('/update-student', 'StudentController::UpdateStudent');
StudentController.php File Discussion,
UpdateStudent() – This function is used to update existing table records.
$StudentModel is the name of the newly created StudentModel class object.
The $.ajax() function data property id value of the hidden tag was obtained using the getPost() method. This id value is then assigned to the $id variable.
Inside $data [ ] array,
The $.ajax() function data property values were obtained using the getPost() method.
The ajax() data property has two values: update_firstname and update_lastname. The values of these variables are controlled by the firstname and lastname variables.
Send the $id and $data array variables to the update() method, and it will update any existing records with the specified id.
We set the $data variable to hold field values and update the successful message inside an array. The $output variable is assigned to this array.
Paste the $output variable into the setJSON() method, which converts all results to JSON and returns them all.
app/Controllers/StudentController.php
<?php
namespace App\Controllers;
use App\Models\StudentModel;
class StudentController extends BaseController
{
// view index file
public function index()
{
return view('index');
}
// create new student records
public function CreateStudent()
{
}
//fetch all students records
public function ReadStudent()
{
}
//edit or get specific student record id
public function EditStudent()
{
}
// update existing student records
public function UpdateStudent()
{
$StudentModel = new StudentModel();
$id = $this->request->getPost("update_id");
$data = [
'firstname' => $this->request->getPost("update_firstname"),
'lastname' => $this->request->getPost("update_lastname"),
];
$StudentModel->update($id, $data);
$output = array('status' => 'Student Updated Successfully', 'data' => $data);
return $this->response->setJSON($output);
}
// delete existing student records
public function DeleteStudent()
{
}
}
The bootstrap update modal appears when a user clicks on the edit hyperlink:
The response of the swal() function after data has been updated is as follows:
#9.4 Delete Record:
In this section, you will learn to delete a record.
You've already looked at the function codes for displaystudent(). The delete hyperlink was in the last column.
Look table-id attribute value holds database table id values.
Look at the id attribute value btn_delete using this we will handle the delete hyperlink click event.
<td>\
<a id="btn_delete" table-id='+value['student_id']+' class="btn btn-danger">Delete</a>\
</td>\
jQuery & Ajax CodesÂ
When a user clicked the delete hyperlink, the click() method caused and activated a delete hyperlink click event. The Delete anchor tag's id attribute value is #btn delete.
The variable student_id is saved with $(this).attr('table-id').
The attr() method returns the table's current id value.
The job of the $.ajax() function is to use the HTTP GET method to send an id request to the URL "delete-student" and get a response from the server without having to reload the page.
The delete-student URL is maintained in the site_url() function, which we will add in the Routes.php file.
The swal() function within the success() function displays the deleted successfully message in an animated style.
The response.status parameter is present in the swal() function. The delete successful message is stored in the status variable, which is delivered by the DeleteStudent() function.
After a specific record is deleted, the displaystudent() function loads all table records.
$(document).on('click','#btn_delete', function(){
var student_id = $(this).attr('table-id');
$.ajax({
url:'<?= site_url('delete-student') ?>/',
method:'get',
data:{delete_id:student_id},
success:function(response){
swal("Deleted", response.status, "success");
$('#tableData').html('');
displaystudent();
}
});
});
Routes.php file Discussion,
From the /app/Config folder, open Routes.php. Use the routes given below.
The URL of the $.ajax() function URL property we discussed earlier in the $.ajax() method is delete-student.
Our controller is StudentController, and the function DeleteStudent deletes existing records.Â
\app\Config\Routes.php
$routes->get('/delete-student', 'StudentController::DeleteStudent');
StudentController.php File Discussion,
DeleteStudent() – This function delete existing table records.
The $.ajax() function data property current id values were obtained using the getGet() method from the current delete hyperlink click event.
The value of the ajax() data property is delete id. And the $id variable is in responsible for this variable's value.
In the delete() method, paste the $id variable. If an id is found in the table, the delete() method is used to remove records.
The delete successful message of array property is stored in the $output variable, and the setJSON() method converts the message to JSON format.
app/Controllers/StudentController.php
<?php
namespace App\Controllers;
use App\Models\StudentModel;
class StudentController extends BaseController
{
// view index file
public function index()
{
return view('index');
}
// create new student records
public function CreateStudent()
{
}
//fetch all students records
public function ReadStudent()
{
}
//edit or get specific student record id
public function EditStudent()
{
}
// update existing student records
public function UpdateStudent()
{
}
// delete existing student records
public function DeleteStudent()
{
$StudentModel = new StudentModel();
$id = $this->request->getGet("delete_id");
$StudentModel->delete($id);
$output = array('status' => 'Deleted Successfully');
return $this->response->setJSON($output);
}
}
The swal() function produces the following output when a user clicks on the delete hyperlink and data is deleted:
index.php file all codes
The frontend.php file can be extended using the extend() method.
Between $this->section("body") and $this->endSection(), append body content.
Look $this->endSection() code is available end of line.
app\Views\index.php\
<?= $this->extend("frontend") ?>
<?= $this->section("body") ?>
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="https://www.onlyxcodes.com/">onlyxcodes</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="https://www.onlyxcodes.com/2021/12/codeigniter-4-crud-ajax.html">Back to Tutorial</a></li>
</ul>
</div>
</div>
</nav>
<div class="wrapper">
<div class="container">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="card mt-5">
<div class="panel-heading">
<button data-toggle="modal" data-target="#addModal" class="btn btn-warning"><span class="glyphicon glyphicon-plus"></span> Add Student</button>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
</div>
</div>
</div>
<!-- Add Modal Start-->
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ModalLabel">Create New Student</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="addStudent" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">Firstname:</label>
<div class="col-sm-10">
<input type="text" id="txt_firstname" class="form-control" placeholder="enter firstname">
<span id="error_firstname" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Lastname:</label>
<div class="col-sm-10">
<input type="text" id="txt_lastname" class="form-control" placeholder="enter lastname">
<span id="error_lastname" class="text-danger"></span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btn_insert" class="btn btn-success">Insert</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Add Modal End-->
<!-- Update Modal Start-->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ModalLabel">Update Student</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="updateStudent" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">Firstname:</label>
<div class="col-sm-10">
<input type="text" id="firstname_update" class="form-control" placeholder="enter firstname">
<span id="error_firstname_update" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Lastname:</label>
<div class="col-sm-10">
<input type="text" id="lastname_update" class="form-control" placeholder="enter lastname">
<span id="error_lastname_update" class="text-danger"></span>
</div>
</div>
<input type="hidden" id="hidden_id">
</form>
</div>
<div class="modal-footer">
<button type="button" id="btn_update" class="btn btn-primary">Update</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Update Modal End-->
</div>
</div>
</div>
</div>
<?= $this->endSection() ?>
<?= $this->section("body") ?>
<script>
$(document).ready(function(){
displaystudent();
$(document).on('click','#btn_insert',function(){
var firstname = $('#txt_firstname').val();
var lastname = $('#txt_lastname').val();
if(firstname == ''){
error_firstname = 'please enter firstname';
$('#error_firstname').text(error_firstname);
}
else if(lastname == ''){
error_lastname = 'please enter lastname';
$('#error_lastname').text(error_lastname);
}
else{
$.ajax({
url:'<?= site_url('create-student') ?>',
method:'post',
data:
{
student_firstname:firstname,
student_lastname:lastname
},
success:function(response){
$('#addModal').modal('hide');
$('#addModal').find('input').val('');
$('#error_firstname').text('');
$('#error_lastname').text('');
$('#tableData').html('');
displaystudent();
swal("Inserted", response.status, "success");
}
});
}
});
$(document).on('click','#btn_edit', function(){
var student_id = $(this).attr('table-id');
$.ajax({
url:'<?= site_url('edit-student') ?>/',
method:'get',
data:{sid:student_id},
success:function(response){
$('#updateModal').modal('show');
$('#firstname_update').val(response.row.firstname);
$('#lastname_update').val(response.row.lastname);
$('#hidden_id').val(response.row.student_id);
}
});
});
$(document).on('click','#btn_update', function(){
var firstname = $('#firstname_update').val();
var lastname = $('#lastname_update').val();
var hiddenId = $('#hidden_id').val();
if(firstname == ''){
error_firstname = 'please enter firstname';
$('#error_firstname_update').text(error_firstname);
}
else if(lastname == ''){
error_lastname = 'please enter lastname';
$('#error_lastname_update').text(error_lastname);
}
else{
$.ajax({
url:'<?= site_url('update-student') ?>',
method:'post',
data:
{
update_firstname:firstname,
update_lastname:lastname,
update_id:hiddenId
},
success:function(response){
$('#updateModal').modal('hide');
$('#error_firstname_update').text('');
$('#error_lastname_update').text('');
$('#tableData').html('');
displaystudent();
swal("Updated", response.status, "success");
}
});
}
});
$(document).on('click','#btn_delete', function(){
var student_id = $(this).attr('table-id');
$.ajax({
url:'<?= site_url('delete-student') ?>/',
method:'get',
data:{delete_id:student_id},
success:function(response){
swal("Deleted", response.status, "success");
$('#tableData').html('');
displaystudent();
}
});
});
});
function displaystudent()
{
$.ajax({
url:'<?= site_url('fetch-student') ?>',
method:'get',
success:function(response){
$.each(response.allstudents,function(key, value){
$('#tableData').append('<tr>\
<td> '+value['student_id']+' </td>\
<td> '+value['firstname']+' </td>\
<td> '+value['lastname']+' </td>\
<td>\
<a id="btn_edit" table-id='+value['student_id']+' data-toggle="modal" data-target="#updateModal" class="btn btn-warning">Edit</a>\
</td>\
<td>\
<a id="btn_delete" table-id='+value['student_id']+' class="btn btn-danger">Delete</a>\
</td>\
</tr>');
});
}
});
}
</script>
<?= $this->endSection() ?>
StudentController.php file all codes
app/Controllers/StudentController.php
<?php
namespace App\Controllers;
use App\Models\StudentModel;
class StudentController extends BaseController
{
// view index file
public function index()
{
return view('index');
}
// create new student records
public function CreateStudent()
{
$StudentModel = new StudentModel();
$data = [
'firstname' => $this->request->getPost("student_firstname"),
'lastname' => $this->request->getPost("student_lastname"),
];
$StudentModel->save($data);
$output = array('status' => 'Student Inserted Successfully', 'data' => $data);
return $this->response->setJSON($output);
}
//fetch all students records
public function ReadStudent()
{
$StudentModel = new StudentModel();
$data['allstudents'] = $StudentModel->findAll();
return $this->response->setJSON($data);
}
//edit or get specific student record id
public function EditStudent()
{
$StudentModel = new StudentModel();
$id = $this->request->getGet('sid');
$data['row'] = $StudentModel->find($id);
return $this->response->setJSON($data);
}
// update existing student records
public function UpdateStudent()
{
$StudentModel = new StudentModel();
$id = $this->request->getPost("update_id");
$data = [
'firstname' => $this->request->getPost("update_firstname"),
'lastname' => $this->request->getPost("update_lastname"),
];
$StudentModel->update($id, $data);
$output = array('status' => 'Student Updated Successfully', 'data' => $data);
return $this->response->setJSON($output);
}
// delete existing student records
public function DeleteStudent()
{
$StudentModel = new StudentModel();
$id = $this->request->getGet("delete_id");
$StudentModel->delete($id);
$output = array('status' => 'Deleted Successfully');
return $this->response->setJSON($output);
}
}
Routes.php file all codes
\app\Config\Routes.php
//$routes->get('/', 'Home::index');
$routes->get('/', 'StudentController::index');
$routes->post('/create-student', 'StudentController::CreateStudent');
$routes->get('/fetch-student', 'StudentController::ReadStudent');
$routes->get('/edit-student', 'StudentController::EditStudent');
$routes->post('/update-student', 'StudentController::UpdateStudent');
$routes->get('/delete-student', 'StudentController::DeleteStudent');
No comments:
Post a Comment