Working on Datatables with Ajax in PHP Codeigniter 3 Example

Working on Datatables with Ajax in PHP Codeigniter 3 Example

In this Codeigniter tutorial, I will let you know how to work with Datatables using ajax request with example.

DataTables is a jQuery plugin to display data in tabular format with ajax search, sort and pagination.

It's very easy to integrate datatables into your CodeIgniter project.

Create products table

In this first step, we will create products table in the database.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `price` double NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Create Routes

In this step, we need to add routes to handle the request.

application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

$route['product'] = "product/index";
$route['get_products'] = "product/get_products";
Create Product Controller

In this step, I will create a controller "Product.php".

In this controller file, we will have two method. First "index" method will load the view and second "get_products" method will return the products list in json format.

application/controllers/Product.php
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Product extends CI_Controller {

   public function __construct() {
      parent::__construct();
      $this->load->database();
   }

   public function index()
   {
      $this->load->view('product_list');
   }

   public function get_products()
   {
      $draw = intval($this->input->get("draw"));
      $start = intval($this->input->get("start"));
      $length = intval($this->input->get("length"));

      $query = $this->db->get("products");
      $data = [];
      foreach($query->result() as $r) {
           $data[] = array(
                $r->id,
                $r->name,
                $r->price
           );
      }

      $result = array(
               "draw" => $draw,
                 "recordsTotal" => $query->num_rows(),
                 "recordsFiltered" => $query->num_rows(),
                 "data" => $data
            );
      echo json_encode($result);
      exit();
   }
}
Create view file

In this step, I will create "product_list.php" view file.

application/views/product_list.php
<html>
<head>
  <title>Working with Datatables ajax in Codeigniter 3 with example</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
</head>
<body>

<div class="container">
  <h2>Working with Datatables ajax in Codeigniter 3 with example</h2>
  <table id="product-list" class="table table-bordered table-striped table-hover">
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Price</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> 
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="http://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
<script>

    $('#product-list').DataTable({
        "ajax": {
            url : "<?php echo base_url(); ?>index.php/get_products",
            type : 'GET'
        },
    });

</script>

</body>

</html>

There is also a tutorial on jQuery DataTable server side processing in PHP.

Server side processing will solve the issue of loading whole data at once. Datatable is highly flexible, customizable and open source Javascript plugin.

Phone: (+91) 8800417876
Noida, 201301