jQuery and AJAX will allow developers to create CRUD operation application that will allow users to create, read, update, and delete data from the database without refreshing the entire web page.
Let’s start building a CRUD operation application using jquery, ajax, bootstrap 5 model, and database:
Step 1: Setting Up CodeIgniter 4
Download CodeIgniter 4 from the official website:https://codeigniter.com/user_guide/installation/index.html., and extract download zip file in xampp/htdocs directory.
Edit .env
file, and set the 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 and Table
Run the following sql query to create database and table:
CREATE DATABASE ci4_ajax_crud;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Step 3: Creating the Model
Go to the app/models
directory and create a model file called UserModel.php
in it:
<?php namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email'];
}
Step 4: Creating the Controller
Go to app/Controllers/
directory and create a new file named UserController.php
, and crud methods in it to handle ajax crud operation with mysql database:
<?php namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;
use CodeIgniter\API\ResponseTrait;
class UserController extends Controller
{
use ResponseTrait;
public function index()
{
return view('index');
}
public function fetch()
{
$model = new UserModel();
$data['users'] = $model->findAll();
return $this->response->setJSON($data);
}
public function store()
{
$model = new UserModel();
$data = [
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email'),
];
$model->save($data);
return $this->response->setJSON(['message' => 'User created successfully']);
}
public function edit($id)
{
$model = new UserModel();
$data = $model->find($id);
return $this->response->setJSON($data);
}
public function update($id)
{
$model = new UserModel();
$data = [
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email'),
];
$model->update($id, $data);
return $this->response->setJSON(['message' => 'User updated successfully']);
}
public function delete($id)
{
$model = new UserModel();
$model->delete($id);
return $this->response->setJSON(['message' => 'User deleted successfully']);
}
}
Step 5: Create List View
In the app/Views/
directory create a new file index.php
to show list of users from database with add new record button:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeIgniter 4 AJAX CRUD Example - itcodstuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container mt-5">
<h2>Users List</h2>
<button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addUserModal">Add New User</button>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="userTableBody">
<!-- Data will be appended here -->
</tbody>
</table>
<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addUserModalLabel">Add New User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="addUserForm">
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<button type="submit" class="btn btn-success">Save</button>
</form>
</div>
</div>
</div>
</div>
<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editUserModalLabel">Edit User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="editUserForm">
<input type="hidden" id="editUserId" name="id">
<div class="mb-3">
<label for="editName" class="form-label">Name</label>
<input type="text" class="form-control" id="editName" name="name" required>
</div>
<div class="mb-3">
<label for="editEmail" class="form-label">Email</label>
<input type="email" class="form-control" id="editEmail" name="email" required>
</div>
<button type="submit" class="btn btn-success">Update</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Step 6: Implement Ajax CRUD Requests
Import jQuery and use the ajax() method to make a CRUD request to the server, simply add the following code in app/views/index.php
file:
<script>
$(document).ready(function() {
// Fetch users
function fetchUsers() {
$.ajax({
url: '/UserController/fetch',
method: 'GET',
dataType: 'json',
success: function(response) {
let userTableBody = '';
$.each(response.users, function(index, user) {
userTableBody += `
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
<td>
<button class="btn btn-warning btn-sm editUserBtn" data-id="${user.id}">Edit</button>
<button class="btn btn-danger btn-sm deleteUserBtn" data-id="${user.id}">Delete</button>
</td>
</tr>
`;
});
$('#userTableBody').html(userTableBody);
}
});
}
fetchUsers();
// Add user
$('#addUserForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '/UserController/store',
method: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
$('#addUserModal').modal('hide');
$('#addUserForm')[0].reset();
fetchUsers();
}
});
});
// Edit user
$(document).on('click', '.editUserBtn', function() {
let userId = $(this).data('id');
$.ajax({
url: `/UserController/edit/${userId}`,
method: 'GET',
dataType: 'json',
success: function(response) {
$('#editUserId').val(response.id);
$('#editName').val(response.name);
$('#editEmail').val(response.email);
$('#editUserModal').modal('show');
}
});
});
// Update user
$('#editUserForm').on('submit', function(e) {
e.preventDefault();
let userId = $('#editUserId').val();
$.ajax({
url: `/UserController/update/${userId}`,
method: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
$('#editUserModal').modal('hide');
$('#editUserForm')[0].reset();
fetchUsers();
}
});
});
// Delete user
$(document).on('click', '.deleteUserBtn', function() {
if (confirm('Are you sure you want to delete this user?')) {
let userId = $(this).data('id');
$.ajax({
url: `/UserController/delete/${userId}`,
method: 'GET',
dataType: 'json',
success: function(response) {
fetchUsers();
}
});
}
});
});
</script>
Step 7: Define Routes
Edit app/Config/Routes.php
and define the following routes:
$routes->get('/users', 'UserController::index');
$routes->get('/UserController/fetch', 'UserController::fetch');
$routes->post('/UserController/store', 'UserController::store');
$routes->get('/UserController/edit/(:num)', 'UserController::edit/$1');
$routes->post('/UserController/update/(:num)', 'UserController::update/$1');
$routes->get('/UserController/delete/(:num)', 'UserController::delete/$1');
Step 7: Test the Application
Type the url: http://localhost/your_project_name/public/users
on browser and test this application