CodeIgniter 4 Server Side DataTable Example

In this tutorial, you’ll learn how to make a server-side processing datatable in CodeIgniter 4 app using ajax. DataTables is a jQuery (Javascript library) that helps you add, sort, paginate, and filter data in HTML tables with ease.

This tutorial covers the following topics:

  • Adding Datatables to a CodeIgniter 4 app
  • Adding jQuery and Bootstrap to a CodeIgniter 4 app
  • Reading data from a MySQL database
  • Displaying data using ajax
  • Creating a server-side datatable with sorting, searching, and pagination

You’ll create a user list web application using server-side processing datatables in CodeIgniter 4, and use Bootstrap 4 and dataTable js to style and enhance the display.

Datatables server side CodeIgniter 4 using Ajax

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Installing CodeIgniter4-DataTables Library
  • Create Model and Controller
  • Create Views
  • Start Development server

Download Codeigniter Latest

Let’s begin by downloading the latest version of CodeIgniter 4 from the official website. You can download it from this link: https://codeigniter.com/download. Once downloaded, extract the files and save them in your local system’s xampp/htdocs/ directory.

Now, change the folder name to “demo” to make it easy to remember and work with. This step is important as we will be using the CodeIgniter 4 framework for our image file upload example.

Step 2 – Basic Configurations

In the next step, we need to make some basic configurations to the app/config/app.php we will go to the application/config/ directory and open the config.php file in a text editor.

Set Base URL Like This

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database With Table

To proceed, you’ll need to create a database called “demo” by opening PHPMyAdmin and creating it. Once you’ve created the database, use the SQL query below to create a table within it.

CREATE DATABASE demo;
 
CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo database' AUTO_INCREMENT=1;
 
INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'Paul Bettany', 'paul@gmail.com'),
(2, 'Vanya', 'vanya@gmail.com'),
(3, 'Luther', 'luther@gmail.com'),
(4, 'John Doe', 'john@gmail.com'),
(5, 'Paul Bettany', 'paul@gmail.com'),
(6, 'Vanya', 'vanya@gmail.com'),
(7, 'Luther', 'luther@gmail.com'),
(8, 'Wayne Barrett', 'wayne@gmail.com'),
(9, 'Vincent Ramos', 'ramos@gmail.com'),
(10, 'Susan Warren', 'sussan@gmail.com'),
(11, 'Jason Evans', 'jason@gmail.com'),
(12, 'Madison Simpson', 'madison@gmail.com'),
(13, 'Marvin Ortiz', 'paul@gmail.com'),
(14, 'Felecia Phillips', 'felecia@gmail.com'),
(15, 'Tommy Hernandez', 'hernandez@gmail.com');

Step 4 – Setup Database Credentials

Now it’s time to connect our project to the database. To do this, go to the “app/Config/Database.php” file and open it in a text editor. Once you have the file open, you’ll need to enter your database credentials as shown below.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];

Step 5 – Installing CodeIgniter4-DataTables Library

To install datatable pluing by executing the following comamnd on terminal:

composer require hermawan/codeigniter4-datatables

then open app/Config/autoload.php. add namespace to $psr4 array. see the code below:

public $psr4 = [
    APP_NAMESPACE => APPPATH, // For custom app namespace
    'Config'      => APPPATH . 'Config',
    'PHPSQLParser'          => APPPATH .'ThirdParty/php-sql-parser/src/PHPSQLParser',
    'Hermawan\DataTables'   => APPPATH .'ThirdParty/CodeIgniter4-DataTables/src'
];

Step 6 – Create Model and Controller

To proceed, navigate to the “app/Models/” directory and create a new model. Name this model “UserModel.php” and copy the following code into it:

<?php 
namespace App\Models;
use CodeIgniter\Model;
 
class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email'];
}

Create Controller

Next, navigate to the “app/Controllers” directory and create a new controller named “UsersController.php”. Inside this controller, add the following code:

<?php namespace App\Controllers;
  
use \CodeIgniter\Controller;
 
use \Hermawan\DataTables\DataTable;
  
class UsersController extends Controller
{
    public function index()
    {
        helper('url');
        return view('list');
    }
  
    public function ajaxDataTables()
    {
        $db = db_connect();
        $builder = $db->table('users')->select('name, email, id');
          
        return DataTable::of($builder)
               ->addNumbering() //it will return data output with numbering on first column
               ->toJson();
    }
}
  
?>

Step 7 – Create Views

To continue, create a new view file named “list.php”. In this file, copy and paste the following code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>CodeIgniter 4 Server Side DataTable Example - torqueprogramming.co.in</title>

        <!-- Bootstrap CSS CDN -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />
        <!-- DataTables CSS CDN -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css" />
        <link href="https://cdn.datatables.net/1.10.24/css/dataTables.bootstrap4.min.css" />
    </head>
    <body>
        <div class="container">
            <h1 style="font-size: 20pt;"></h1>
            <h3>Customers Data</h3>
            <table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody></tbody>
                <tfoot>
                    <tr>
                        <th>No</th>
                        <th>Name</th>
                        <th>Email</th>
                    </tr>
                </tfoot>
            </table>
        </div>
        <!-- jQuery CDN -->
        <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
        <!-- Bootstrap 4.5 CDN  -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
        <!-- DataTable CDN js -->
        <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>

        <script src="https://cdn.datatables.net/1.10.24/js/dataTables.bootstrap4.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#table").DataTable({
                    processing: true,
                    serverSide: true,
                    order: [], //init datatable not ordering
                    ajax: "<?php echo site_url('ajax-datatable')?>",
                    columnDefs: [
                        { targets: 0, orderable: false }, //first column is not orderable.
                    ],
                });
            });
        </script>
    </body>
</html>

To define a new route, navigate to the “app/Config/” directory and open the “Routes.php” file. Once you have the file open, add the following routes to it:

// CRUD RESTful Routes
$routes->setDefaultController('UsersController');
$routes->get('list', 'UsersController::index');
$routes->get('ajax-datatable', 'UsersController::ajaxDataTables');

Step 8 – Start Development server

To start your CodeIgniter 4 application, execute the following command in your command prompt or terminal:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

This tutorial has shown you how to implement a server-side datatable in a CodeIgniter 4 app.

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *