CodeIgniter 4 Server Side DataTable Tutorial

Share this Article
Reading Time: 7 minutes
10,926 Views

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.

Learn More –

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


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

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

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

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 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 Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
database.default.DBPrefix =
   

Now, database successfully connected with the application.


Add Routes

Open Routes.php file from /app/Config folder. Add these routes into it.

//...

$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

Next we need to create application controller.

Loading url Helper

Open BaseController.php from /app/Controllers folder. Search for $helpers, inside this helpers array simply add this url helper.

protected $helpers = [‘url’];

This url helper will load base_url() and site_url() functions.

Also we have the option to load any helper directly to any controller using helper() function.

$ php spark make:controller Student

It will creates Student.php file inside /app/Controllers folder.

Open Student.php and write this complete code into it.

<?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);
    }
}

Create Layout File

Go to /app/Views folder.

Create a file list-student.php inside it.

Open list-student.php file and write this complete code into it.

<!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 terminal and start development server via command:

$ php spark serve

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.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5