Tutorial Lengkap membuat CRUD Datatables Server Side menggunakan CodeIgniter 4, JQuery, Ajax dan Bootstrap 4.5.0

DatatablesCodeIgniter4JQueryAJAXBootstrap4.5.0
Banner

Halo Klinik Coders..

Di tutorial kali ini kita akan mempelajari Tutorial Lengkap membuat CRUD Datatables Server Side menggunakan CodeIgniter 4, JQuery, Ajax dan Bootstrap 4.5.0

Demo

Tahap#1 - Persiapan

Siapkan tool sebagai berikut :

  1. CodeIgniter

Tahap#2 - Konfigurasi env

Setelah CodeIgniter didownload, setting lah file env menjadi .env. Konfigurasi sebagai berikut :

app.baseURL = 'http://localhost:8081'
database.default.hostname = localhost
database.default.database = crud
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi

Tahap#3 - Buat Controller Home.php

<?php

namespace App\Controllers;

class Home extends BaseController
{
    public $user_model;
    public $output = [
        'sukses'    => false,
        'pesan'     => '',
        'data'      => []
    ];

    public function __construct()
    {
        $this->user_model = new \App\Models\User_model();
    }

    public function index()
    {
        return view('home');
    }

    public function tambah()
    {
        $user_model = $this->user_model;
        if ($this->request->isAJAX()) {
            $data = [
                'nama_user' => $this->request->getVar('nama_user'),
                'alamat'    => $this->request->getVar('alamat')
            ];

            $simpan = $user_model->tambah($data);
            if ($simpan) {
                $this->output['sukses'] = true;
                $this->output['pesan']  = 'Data ditemukan';
            }

            echo json_encode($this->output);
        }
    }

    public function edit()
    {
        $user_model = $this->user_model;
        if ($this->request->isAJAX()) {
            $id_user = $this->request->getVar('id_user');
            $result = $user_model->edit($id_user);
            if ($result) {
                $this->output['sukses'] = true;
                $this->output['pesan']  = 'Data ditemukan';
                $this->output['data']   = $result;
            }

            echo json_encode($this->output);
        }
    }

    public function update()
    {
        $user_model = $this->user_model;
        if ($this->request->isAJAX()) {
            $data = [
                'nama_user' => $this->request->getVar('nama_user'),
                'alamat'    => $this->request->getVar('alamat')
            ];
            $id_user = $this->request->getVar('id_user');
            $simpan = $user_model->ubah($data, $id_user);
            if ($simpan) {
                $this->output['sukses'] = true;
                $this->output['pesan']  = 'Data diupdate';
            }

            echo json_encode($this->output);
        }
    }

    public function hapus()
    {
        $user_model = $this->user_model;
        if ($this->request->isAJAX()) {
            $id_user = $this->request->getVar('id_user');
            $hapus = $user_model->hapus($id_user);
            if ($hapus) {
                $this->output['sukses'] = true;
                $this->output['pesan']  = 'Data telah dihapus';
            }

            echo json_encode($this->output);
        }
    }

    public function dt_users()
    {
        $user_model = $this->user_model;
        $where = ['id_user !=' => 0];
        $column_order   = array('', 'nama_user', 'alamat');
        $column_search  = array('nama_user', 'alamat');
        $order = array('nama_user' => 'ASC');
        $list = $user_model->get_datatables('users', $column_order, $column_search, $order, $where);
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $lists) {
            $no++;
            $row    = array();
            $row[]  = $no;
            $row[]  = $lists->nama_user;
            $row[]  = $lists->alamat;
            $row[]  = " . $lists->id_user . '"' . ")'>EDIT  . $lists->id_user . '"' . ")'>HAPUS";

            $data[] = $row;
        }

        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $user_model->count_all('users', $where),
            "recordsFiltered" => $user_model->count_filtered('users', $column_order, $column_search, $order, $where),
            "data" => $data,
        );

        echo json_encode($output);
    }
}

 

Tahap#4 - Buat Model User_model.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class User_model extends Model
{
    public $db;
    public $builder;
    protected $table = 'users';

    public function __construct()
    {
        parent::__construct();
        $this->db = \Config\Database::connect();
    }

    public function tambah($data)
    {
        $this->builder = $this->db->table($this->table);

        return $this->builder->insert($data);
    }

    public function edit($id_user)
    {
        $this->builder = $this->db->table($this->table);
        $query = $this->builder->getWhere(['id_user' => $id_user]);
        return $query->getRow();
    }

    public function ubah($data, $id_user)
    {
        $this->builder = $this->db->table($this->table);

        $this->builder->where('id_user', $id_user);
        return $this->builder->update($data);
    }

    public function hapus($id_user)
    {
        $this->builder = $this->db->table($this->table);
        $this->builder->where('id_user', $id_user);
        return $this->builder->delete();
    }

    protected function _get_datatables_query($table, $column_order, $column_search, $order)
    {
        $this->builder = $this->db->table($table);

        $i = 0;

        foreach ($column_search as $item) {
            if ($_POST['search']['value']) {

                if ($i === 0) {
                    $this->builder->groupStart();
                    $this->builder->like($item, $_POST['search']['value']);
                } else {
                    $this->builder->orLike($item, $_POST['search']['value']);
                }

                if (count($column_search) - 1 == $i)
                    $this->builder->groupEnd();
            }
            $i++;
        }

        if (isset($_POST['order'])) {
            $this->builder->orderBy($column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
        } else if (isset($order)) {
            $order = $order;
            $this->builder->orderBy(key($order), $order[key($order)]);
        }
    }

    public function get_datatables($table, $column_order, $column_search, $order, $data = '')
    {
        $this->_get_datatables_query($table, $column_order, $column_search, $order);
        if ($_POST['length'] != -1)
            $this->builder->limit($_POST['length'], $_POST['start']);
        if ($data) {
            $this->builder->where($data);
        }
        $query = $this->builder->get();
        return $query->getResult();
    }

    public function count_filtered($table, $column_order, $column_search, $order, $data = '')
    {
        $this->_get_datatables_query($table, $column_order, $column_search, $order);
        if ($data) {
            $this->builder->where($data);
        }
        $this->builder->get();
        return $this->builder->countAll();
    }

    public function count_all($table, $data = '')
    {
        if ($data) {
            $this->builder->where($data);
        }
        $this->builder->from($table);
        return $this->builder->countAll();
    }
}

 

Tahap#5 - Buat View home.php

<!doctype html>
<html lang="en">

<head>
    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">

    <title>CRUD Datatable Server Side Codeigniter 4title>
</head>

<body>
    <div class="container">
        <h1>CRUD Datatable Server Side Codeigniter 4h1>
        <hr>
        <button class="btn btn-primary" onclick="tambah()">Tambah Userbutton>
        <hr>
        <table id="example" class="display" style="width:100%">
            <thead>
                <tr>
                    <th width="1%">Noth>
                    <th>Nama Userth>
                    <th>Alamatth>
                    <th>Actionth>
                tr>
            thead>
        table>
    div>
    
    <div class="modal fade" id="exampleModal" 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">Modal titleh5>
                    <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-users">
                        <div class="form-group">
                            <label for="nama_user">Nama Userlabel>
                            <input type="hidden" name="id_user" id="id_user">
                            <input type="text" class="form-control" id="nama_user" name="nama_user">
                        div>
                        <div class="form-group">
                            <label for="alamat">Alamatlabel>
                            <input type="text" class="form-control" id="alamat" name="alamat">
                        div>
                    form>
                div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Closebutton>
                    <button type="button" class="btn btn-primary" onclick="proses()">Save changesbutton>
                div>
            div>
        div>
    div>

    
    
    <script src="https://code.jquery.com/jquery-3.5.1.js">script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous">script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous">script>
    
    <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js">script>
    <script>
        let url;
        let status = 'tambah';
        $(document).ready(function() {
            tampil_table_users();
        });

        function tambah() {
            status = 'tambah';
            $('#exampleModal').modal('show');
            $('#form-users')[0].reset();
        }

        function edit(id_user) {
            status = 'edit';
            $('#exampleModal').modal('show');
            $('#id_user').val(id_user);
            $.ajax({
                url: " echo base_url('home/edit'); ?>",
                type: 'POST',
                dataType: 'JSON',
                data: $('#form-users').serialize(),
                success: function(x) {
                    if (x.sukses == true) {
                        $('#nama_user').val(x.data.nama_user);
                        $('#alamat').val(x.data.alamat);
                    }
                }
            });
        }

        function hapus(id_user) {
            $.ajax({
                url: " echo base_url('home/hapus'); ?>",
                type: 'POST',
                dataType: 'JSON',
                data: {
                    id_user: id_user
                },
                success: function(x) {
                    if (x.sukses == true) {
                        tampil_table_users();
                    }
                }
            });
        }

        function proses() {
            if (status == 'tambah') {
                url = " echo base_url('home/tambah'); ?>";
            } else if (status == 'edit') {
                url = " echo base_url('home/update'); ?>";
            } else {
                url = " echo base_url('home/hapus'); ?>";
            }

            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'JSON',
                data: $('#form-users').serialize(),
                success: function(x) {
                    if (x.sukses == true) {
                        $('#exampleModal').modal('hide');
                        tampil_table_users();
                    }
                }
            });
        }

        function tampil_table_users() {
            $('#example').DataTable({
                processing: true,
                serverSide: true,
                bDestroy: true,
                responsive: true,
                ajax: {
                    url: " echo base_url('home/dt_users'); ?>",
                    type: "POST",
                    data: {},
                },
                columnDefs: [{
                        targets: [0, -1],
                        orderable: false,
                    },
                    {
                        width: "1%",
                        targets: [0, -1],
                    },
                    {
                        className: "dt-nowrap",
                        targets: [-1],
                    }
                ],

            });
        }
    </script>
</body>

</html>

 

Tahap#6 - Eksekusi

Jalankan server dengan perintah sebagai berikut
php spark serve
dan jalankan di browser dengan alamat http://localhost:8080

Sekian tutorial dari saya, mudah-mudahan bermanfaat.

Let's coding..

 

Saya adalah seorang Fullstack Web Developer. Saya sangat menyukai hal-hal baru di dunia teknologi

Traktir Saya
profile
ALFIKRI
Fullstack Web Developer