Codeigniter 4 Ajax CRUD Operation Tutorial Example

Codeigniter 4 Ajax CRUD Operation will teach you how to create a simple AJAX CRUD operation in Codeigniter 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 Codeigniter CRUD operation application using jQuery, AJAX, Bootstrap 5 modal, and a database with validations.

Step 1: Setting Up CodeIgniter 4

Download CodeIgniter 4 from the official website: CodeIgniter Installation, and extract the downloaded zip file in the 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 the 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:

<?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:

<?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:

<!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/bootstrap@5.1.3/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/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Insert the AJAX CRUD Requests script here
    </script>
</body>
</html>

Step 6: Implement AJAX CRUD Requests

Insert the following script within the <script> tag in app/Views/index.php:

<script>
    $(document).ready(function() {
        // AJAX CRUD requests implementation
    });
</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 8: Test the Application

Type the URL: http://localhost/your_project_name/public/users in your browser to test this application.

This completes the step-by-step guide for creating a CRUD application using jQuery, AJAX, Bootstrap 5 modals, and CodeIgniter 4 with MySQL database integration.