Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Codeigniter 4 Ajax Crud using DataTables Tutorial

Last Updated on July 26, 2024 by

The codeigniter 4 ajax crud with datatables and bootstrap modals allow users to perform CRUD operations with searching, sorting, filtering data on datatables in applications.

Let’s start building codeigniter 4 ajax crud with datatables and bootstrap modals:

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 DB Table

Run the following sql query to create table in DB:

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: Creating the Model

Go to the app/models directory and create a model file called ItemModel.php in it:

<?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: Creating the Controller

Create a controller named Items.php in app/Controllers/:

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

Create a view named items_view.php in app/Views/:

<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter 4 AJAX CRUD with DataTables Example - Itcodstuff.com</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>CodeIgniter 4 AJAX CRUD with DataTables</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>

<!-- Modal for Add and 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" value="" 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 getting data from ajax');
            }
        });
    }

    function delete_item(id) {
        if(confirm('Are you sure delete this data?')) {
            $.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: Load DataTables and jQuery in the View

Ensure you have the necessary DataTables and jQuery libraries loaded 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 the Application

Type the url: http://localhost/your_project_name/public/products on browser and test this application

Leave a Comment