Server Side DataTable in CodeIgniter 4 | How to Implement jQuery Datatable in CodeIgniter 4

 

CodeIgniter 4 - Server Side DataTable Example Tutorial


Hii Guys/Learners,

In this post, we will learn codeigniter 4 server side datatable tutorial. In this article/blog, we will implement a how to implement and use datatables in codeigniter 4. let’s discuss about codeigniter 4 datatables tutorial. you will learn CodeWithTanveer datatables codeigniter 4 example. follow bellow step for how to implement and use datatables in codeigniter 4.


Step:- 1

first of all i have install codeigniter4 application with Run Command using composer package manager.

composer create-project codeigniter4/appstarter

You can also manually download the Codeigniter application.

Step:- 2

Configure Database Condition

in this step i have configure datbase Include your database name, username and password in application/config/database.php file and make the database connection to handle data dynamically.



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




Step:- 3

Create the product table and insert some random data into it, these records will be used through pagination component in Codeigniter application.



    CREATE TABLE product (
        id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
        category varchar(100) NOT NULL COMMENT 'Category',
        product_name varchar(255) NOT NULL COMMENT 'Product Name',
        design varchar(255) NOT NULL COMMENT 'Product Design',
        PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
    INSERT INTO `product` (`id`, `category`, `product_name`,`design`) VALUES
    (1, 'Men', 'Denim Shirt','Black Check Shirt','Check Line'),
    (2, 'Men', 'Campus','Berry Shoes','Zetabzork'),
    (3, 'Women', 'Watch','Titanic Watch','IND-987'),
    (4, 'Women', 'Jeans','Blue Jeans Narrow','Blue Jeans'),
    (5, 'Women', 'Bra','Fancy Bra','Cut Pile'),
    (6, 'Kids', 'T-shirt','Kids T-Shirts','Black'),



Step:- 4


If anyhow you get the Codeigniter – cannot connect to MySQL database error, then change the hostname value based on your local server e.g MAMPP or XAMPP.

   
# MAMPP
    public $default = [
      ...
        'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
      ...
    ]
    # XAMPP
    public $default = [
      ...
        'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
      ...
    ]


Step:- 5

Create Model

Model manifests the particular data and business logic in MVC architecture. It manages the data of the application.

So, we have first create a app/Models/UserModel.php file, thereafter place the following codes.

   
namespace App\Models;
    use CodeIgniter\Model;
    class ProductModel extends Model
    {
        protected $table = 'product';
        protected $primaryKey = 'id';
        protected $allowedFields = ['categoy', 'product_name', 'design'];
    }



Step:- 6


Setting Up Controller

Create app/Controllers/ProductController.php and insert the following code inside of it.


Import ProductModel at the top section of the User controller, create the new ProductModel instance. Make the query fetch the records from the database, load the records in the Codeigniter view.



    namespace App\Controllers;
    use App\Models\ProductModel;
    use CodeIgniter\Controller;
    class ProductController extends Controller
    {

        public function productlist(){
          $data['title'] = 'Product List';
          $data['heading'] = 'Product List';
          return view('product_view', $data);
        }

        public function getAll() {
          $ProductModel = new ProductModel();

          $request = service('request');
          $postData = $request->getPost();
          $dtpostData = $postData['data'];
          $response = array();

          ## Read value
          $draw = $dtpostData['draw'];
          $start = $dtpostData['start'];
          $rowperpage = $dtpostData['length']; // Rows display per page
          $columnIndex = $dtpostData['order'][0]['column']; // Column index
          $columnName = $dtpostData['columns'][$columnIndex]['data']; // Column name
          $columnSortOrder = $dtpostData['order'][0]['dir']; // asc or desc
          $searchValue = $dtpostData['search']['value']; // Search value

          ## Total number of records without filtering
          $totalRecords = $ProductModel->select('id')->countAllResults();

          ## Total number of records with filtering
          $totalRecordwithFilter = $ProductModel->select('id')
          ->orLike('category', $searchValue)
          ->orLike('product_name', $searchValue)
          ->orLike('design', $searchValue)
          ->countAllResults();

          ## Fetch records
          $records = $ProductModel->select('*')
          ->orLike('category', $searchValue)
          ->orLike('product_name', $searchValue)
          ->orLike('design', $searchValue)
          ->orderBy($columnName,$columnSortOrder)
          ->findAll($rowperpage, $start);

          $data = array();
          $sn=1;
          foreach($records as $record ){
            $data[] = array(
              "serial"=>$sn,
              "category"=>$record['category'],
              "product"=>$record['product_name'],
              "design"=>$record['design'],
            );
            $sn++;
          }
          ## Response
          $response = array(
            "draw" => intval($draw),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalRecordwithFilter,
            "aaData" => $data,
            "token" => csrf_hash() // New token hash
          );
          return $this->response->setJSON($response);
           
        }
   
    }


Step:- 7


Define Routes

Create the route, It will be used to display the records in tabular form where we can implement pagination. Place the following code in app/Config/Routes.php.



 
$routes->get('products', 'ProductController::productlist');



Step:- 8


Display Pagination

Here the compendium of code describes, we have to display the data using Bootstrap 4 Table with Pagination.


Create app/Views/user_view.php file and insert the following code in it.


      <!doctype html>
      <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Codeigniter 4 DataTable Pagination Example - codewithtanveer</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
      </head>
      <body>
        <div class="container mt-5">
          <div class="mt-3">
            <table class="table table-bordered" id="products_list">
              <thead>
                <tr>
                  <th>SN</th>
                  <th>Category</th>
                  <th>Product</th>
                  <th>Design</th>
                </tr>
              </thead>
              <tbody>
              </tbody>
            </table>
          </div>
        </div>
        <script src="./assest/js/jquery.min.js"></script>
        <script src="./assest/datatables.net/js/jquery.dataTables.min.js"></script>
        <script src="./assest/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
      </body>
      </html>


 Step:-9 

 Here i have configure jQuery for dataTable show list with table id e.g. id="products_list"



      <script>
        $(document).ready(function(){
          $('#products_list').DataTable({
            'processing': true,
            'serverSide': true,
            "order": [[0, "desc" ]], //Initial no order.
            'serverMethod': 'post',
            "iDisplayLength" : 100,
            'ajax': {
              'url':"localhost:8080/product/productlist",
              'data': function(data){
              // CSRF Hash
              ///var csrfName = $('.txt_csrfname').attr('name'); // CSRF Token name
              //var csrfHash = $('.txt_csrfname').val(); // CSRF hash

              return {
                data: data,
                //[csrfName]: csrfHash // CSRF Token
              };
              },
              dataSrc: function(data){

              // Update token hash
              //$('.txt_csrfname').val(data.token);

              // Datatable data
              return data.aaData;
              }
              },
              'columns': [
              { data: 'serial' },
              { data: 'category' },
              { data: 'product' },
              { data: 'design' },
              ]
          });
        });
      </script>




#Codeigniter 4


✌️ Like this article? Follow me on Youtube and Instagram. You can also subscribe to GitHub Feed.









0 Comments