CodeIgniter 4 provides a library for server-side processing of data tables. The library is called DataTables and it is available in the CodeIgniter 4 application/libraries folder.
To use the library, you need to include the library in your controller.
// Load the DataTables library
$this->load->library(‘datatables’);
Once the library is loaded, you can use the library to process the data table. The library provides several methods to process the data table.
// Get the data from the database
$data = $this->datatables->get_data();
// Process the data
$processed_data = $this->datatables->process_data($data);
// Output the data
$this->datatables->output_data($processed_data);
The library also provides several configuration options to customize the data table.
// Set the table configuration
$config = array(
‘columns’ => array(‘name’, ’email’, ‘phone’),
‘order_by’ => array(‘name’ => ‘asc’)
);
// Set the table configuration
$this->datatables->set_config($config);
Once the configuration is set, you can use the library to output the data table.
// Output the data
$this->datatables->output_data($processed_data);
CodeIgniter 4 server-side processing DataTable using jQuery ajax example; In this tutorial, you will learn how to create server side processing datatable in codeigniter 4 app using ajax with sorting, searching, filtering and pagination.
Note that, DataTables is a jQuery (Javascript library) based table advancement plug-in, It brings coherence in the data analysis process, ideally offers adding, sorting, pagination, and filtering abilities to plain HTML tables with minimal effort.
This tutorial will cover the following topics:
- Integrate Datatables in codeigniter 4 app
- Integrate jQuery and Bootstrap in codeigniter 4 app
- Read data into MySQL DB
- Display data in list using ajax
- Server side datatable with sorting, searching and pagination
This tutorial will create a user list web application using server-side processing dataTables in CodeIgniter 4 example, as well as use Bootstrap 4 and dataTable js.
Datatables server side CodeIgniter 4 using Ajax
By using the following steps, you can setup and use server-side rendering in DataTable with CodeIgniter 4 projects:
- Step 1 – Setup Codeigniter Project
- Step 2 – Basic Configurations
- Step 3 – Create Database With Table
- Step 4 – Setup Database Credentials
- Step 5 – Installing CodeIgniter4-DataTables Library
- Step 6 – Create Model and Controller
- Step 7 – Create Views
- Step 8 – tart Development server
Step 1 – Setup Codeigniter Project
In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”
Step 2 – Basic Configurations
Next, you will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
Step 3 – Create Database With Table
In this step, you need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.
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', '[email protected]'),
(2, 'Vanya', '[email protected]'),
(3, 'Luther', '[email protected]'),
(4, 'John Doe', '[email protected]'),
(5, 'Paul Bettany', '[email protected]'),
(6, 'Vanya', '[email protected]'),
(7, 'Luther', '[email protected]'),
(8, 'Wayne Barrett', '[email protected]'),
(9, 'Vincent Ramos', '[email protected]'),
(10, 'Susan Warren', '[email protected]'),
(11, 'Jason Evans', '[email protected]'),
(12, 'Madison Simpson', '[email protected]'),
(13, 'Marvin Ortiz', '[email protected]'),
(14, 'Felecia Phillips', '[email protected]'),
(15, 'Tommy Hernandez', '[email protected]');
Step 4 – Setup Database Credentials
In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like 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
So go to app/Models/ and create here one model. And you need to create one model name UserModel.php and update the following code into your UserModel.php file:
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email'];
}
Create Controller
Now Go to app/Controllers and create a controller name UsersController.php. In this controller add the follwoing 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
Now you need to create one view files name list.php and update the following code into your file:
<!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></title>
<!-- Bootstrap CSS CDN -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/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/[email protected]/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 route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:
// CRUD RESTful Routes
$routes->setDefaultController('UsersController');
$routes->get('list', 'UsersController::index');
$routes->get('ajax-datatable', 'UsersController::ajaxDataTables');
Step 8 – Start Development server
Execute the following command into command prompt or terminal to start the codeigniter 4 application:
php spark serve
Then visit your web browser and hit the following url on it:
http://localhost/demo/ OR http://localhost:8080/
Conclusion
CodeIgniter 4 server side datatable example; In this tutorial, you have learned how to implement server side datatable in codeigniter 4 app.
Recommended Codeigniter Posts
If you have any questions or thoughts to share, use the comment form below to reach us.
Discover more from Jassweb
Subscribe to get the latest posts sent to your email.
