CodeIgniter 4 Server Side DataTable Tutorial

Share this Article

Listing huge data of any application is generally recommended to use Server side data listing. It will list data in per page wise request. With this concept we will see the usage of DataTable to load data.

As we are covering in CodeIgniter 4, so inside this article we will focus on CodeIgniter 4 Server Side DataTable using Ajax.

Implement server side datatable using SSP library (a 3rd party library) in CodeIgniter 4 – Click here.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

We will see concept from the installation of CodeIgniter 4 setup. Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Table in Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE tbl_students (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(120) DEFAULT NULL,
    email varchar(120) DEFAULT NULL,
    mobile varchar(45) DEFAULT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table. Let’s dump test data into it.

--
-- Dumping data for table `tbl_students`
--

INSERT INTO `tbl_students` (`id`, `name`, `email`, `mobile`) VALUES
(1, 'Sanjay Kumar', 'sanjay@gmail.com', '9632587410'),
(2, 'Vijay Kumar', 'vijay@gmail.com', '7418529630'),
(3, 'Rakesh Kumar', 'rakesh@gmail.com', '8527410963'),
(4, 'Kavita Singh', 'kavita@gmail.com', '8529647130'),
(5, 'Ashish Kumar', 'ashish@gmail.com', '7410852963'),
(6, 'Dhananjay Negi', 'dhananjay_negi@gmail.com', '7896541230'),
(7, 'Pradeep Goyal', 'pradeep_kumar@gmail.com', '1234567890'),
(8, 'Nilu Singh', 'nilu@gmail.com', '7026358941');

Run this query to created database, it will insert these dummy data into tbl_students table.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Create Routes

To configure application routes, we need to open up the file Routes.php from /app/Config. This is the main routes config file where we will do all routes of application.

//.. Other routes

$routes->get("list-student", "Student::listStudent");
$routes->post("ajax-load-data", "Student::ajaxLoadData");

To remove /public/index.php from URL, you can find it’s complete resource here at this link.

Let’s create Controller.


Application Controller Settings

Controller is the functional file. Firstly let’s load a helper at Parent Controller i.e BaseController.php. This file is in /app/Controllers folder.

Search helpers in BaseController and load “url” into helpers.

protected $helpers = [‘url’];

After loading this url helper, we will able to use site_url() and base_url() in Controllers & Views else we should have some error.

We will create application controller at /app/Controllers. Let’s create Student.php inside the given folder. Open project into terminal and type this spark command.

$ php spark make:controller Student

Write the following code into /app/Controllers/Student.php

<?php

namespace App\Controllers;

class Student extends BaseController
{
    public $db;

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

    public function listStudent()
    {
        return view('list-student');
    }

    public function ajaxLoadData()
    {
        $params['draw'] = $_REQUEST['draw'];
        $start = $_REQUEST['start'];
        $length = $_REQUEST['length'];
        /* If we pass any extra data in request from ajax */
        //$value1 = isset($_REQUEST['key1'])?$_REQUEST['key1']:"";

        /* Value we will get from typing in search */
        $search_value = $_REQUEST['search']['value'];

        if(!empty($search_value)){
            // If we have value in search, searching by id, name, email, mobile

            // count all data
            $total_count = $this->db->query("SELECT * from tbl_students WHERE id like '%".$search_value."%' OR name like '%".$search_value."%' OR email like '%".$search_value."%' OR mobile like '%".$search_value."%'")->getResult();

            $data = $this->db->query("SELECT * from tbl_students WHERE id like '%".$search_value."%' OR name like '%".$search_value."%' OR email like '%".$search_value."%' OR mobile like '%".$search_value."%' limit $start, $length")->getResult();
        }else{
            // count all data
            $total_count = $this->db->query("SELECT * from tbl_students")->getResult();

            // get per page data
            $data = $this->db->query("SELECT * from tbl_students limit $start, $length")->getResult();
        }
        
        $json_data = array(
            "draw" => intval($params['draw']),
            "recordsTotal" => count($total_count),
            "recordsFiltered" => count($total_count),
            "data" => $data   // total data array
        );

        echo json_encode($json_data);
    }
}

View File Settings

View file will be created at /app/Views/list-student.php

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

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Codeigniter 4 Server Side DataTable Tutorial - Online Web Tutor</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"/>
</head>

<body>
  <div class="container">

    <br/>
    <h2>Codeigniter 4 Server Side DataTable Tutorial</h2>
    <br/>
    <table class="table table-striped" id="tbl-students-data">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Email</th>
          <th>Mobile</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
  
  <script>

    var site_url = "<?php echo site_url(); ?>";

    $(document).ready( function () {

        $('#tbl-students-data').DataTable({
          lengthMenu: [[ 10, 30, -1], [ 10, 30, "All"]], // page length options
          bProcessing: true,
          serverSide: true,
          scrollY: "400px",
          scrollCollapse: true,
          ajax: {
            url: site_url + "/ajax-load-data", // json datasource
            type: "post",
            data: {
              // key1: value1 - in case if we want send data with request
            }
          },
          columns: [
            { data: "id" },
            { data: "name" },
            { data: "email" },
            { data: "mobile" }
          ],
          columnDefs: [
            { orderable: false, targets: [0, 1, 2, 3] }
          ],
          bFilter: true, // to display datatable search
        });
    });
  </script>
</body>

</html>

Application Testing

Open project into terminal and start development server.

$ php spark serve

Back to browser and open the URL http://localhost:8080/list-student

We hope this article helped you to learn CodeIgniter 4 Server side datatable listing in a very detailed way. Also you can find Server Side DataTable in CodeIgniter 4 using SSP Library here.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment