How to add Custom Filter in DataTable – AJAX and PHP

DataTables plugin brings enhanced functionality and interactivity to HTML tables, offering features like pagination, sorting, and searching across all columns. By default, DataTables provides a search control that allows users to find values across the entire table and presents a filter list for easy data filtering.

However, the beauty of DataTables lies in its customizability, empowering developers to create tailor-made search filters based on specific record requirements, such as date filtering or single field search.

In this tutorial, we will delve into the process of adding custom filters to DataTables and utilizing AJAX for seamless data retrieval. Let’s get started and elevate the power of DataTables with personalized filtering capabilities.

How to add Custom Filter in DataTable – AJAX and PHP


Table of Content

  1. Create a Table
  2. Create Database Connection file
  3. Download & Include DataTable library
  4. HTML Structure for DataTable Custom Filter
  5. PHP Code for Fetching DataTable Data and Applying Filters
  6. jQuery Initialization and Custom Filter Handling for DataTables
  7. Demo
  8. Conclusion

1. Create a Table

Create employee table and added some records.

CREATE TABLE `employee` (
    `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `emp_name` varchar(80) NOT NULL, 
    `salary` varchar(20) NOT NULL,
    `gender` varchar(10) NOT NULL,
    `city` varchar(80) NOT NULL,
    `email` varchar(80) NOT NULL
)

2. Create Database Connection file

Create a config.php for the database configuration.

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. Download & Include DataTable library

  • Download Datatables from the Official website.
  • Include datatables.min.css and datatables.min.js in <head> section and also include the jQuery Library.
  • You can also use CDN –
<!-- Datatable CSS -->
<link href='https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css' rel='stylesheet' type='text/css'>

<!-- jQuery Library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<!-- Datatable JS -->
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>

4. HTML Structure for DataTable Custom Filter

Create two <table> elements:

  1. The first <table> element is used to add a DataTable custom filter element. It includes an input box for name searching and a <select> element for gender filtering.
  2. The second <table> is used to initialize the DataTable, setting up the structure for displaying the employee data with columns for Employee name, Email, Gender, Salary, and City.
<!-- Datatable CSS -->
<link href='https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css' rel='stylesheet' type='text/css'>

<!-- jQuery Library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<!-- Datatable JS -->
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>

<!-- HTML -->
<div >
    <!-- DataTable Custom Filter -->
    <table>
        <tr>
            <td>
                <input type='text' id='searchByName' placeholder='Enter name'>
            </td>
            <td>
                <select id='searchByGender'>
                     <option value=''>-- Select Gender--</option>
                     <option value='male'>Male</option>
                     <option value='female'>Female</option>
                </select>
            </td>
        </tr>
    </table>

    <!-- Table -->
    <table id='empTable' class='display dataTable'>
        <thead>
            <tr>
                <th>Employee name</th>
                <th>Email</th>
                <th>Gender</th>
                <th>Salary</th>
                <th>City</th>
            </tr>
        </thead>

    </table>
</div>

5. PHP Code for Fetching DataTable Data and Applying Filters

This PHP code responsible for fetching data from the DataTable and applying various filters to the results.

Create ajaxfile.php file, which handles the AJAX requests from the DataTable on the client-side. Steps in the PHP Code:

Reading DataTables $_POST Values:

Obtain the necessary $_POST values from DataTables, such as draw, start, length, order, search, etc., and store them in variables.

Handling Custom POST Values:

Read additional custom POST values (searchByName and searchByGender) from the custom filter elements in the DataTable.

Preparing the Search Query:

Construct the search query based on the custom filter values.

  • If searchByName is not empty, add a search condition for the emp_name field.
  • If searchByGender is not empty, include a search condition for the gender field.
  • If searchValue (the global search) is not empty, search for the value in the emp_name, email, and city fields.

Counting Total Records:

Execute SQL queries to calculate the total number of records in the employee table, both with and without filtering, and store the counts in variables.

Fetching Records and Building Data Array:

Fetch records from the employee table based on the search query, sorting, and pagination parameters.
Use a loop to populate the $data array with associative arrays containing the key-value pairs corresponding to the columns defined in the dataTable() method in jQuery.

Initializing Response Array:

Create the $response array and assign values for keys such as draw, iTotalRecords, iTotalDisplayRecords, and aaData.

Returning Response in JSON Format:

Encode the $response array into JSON format and send it as the response to the DataTable.

<?php
include 'config.php';

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

## Custom Field value
$searchByName = $_POST['searchByName'];
$searchByGender = $_POST['searchByGender'];

## Search 
$searchQuery = " ";
if($searchByName != ''){
      $searchQuery .= " and (emp_name like '%".$searchByName."%' ) ";
}
if($searchByGender != ''){
      $searchQuery .= " and (gender='".$searchByGender."') ";
}
if($searchValue != ''){
      $searchQuery .= " and (emp_name like '%".$searchValue."%' or 
           email like '%".$searchValue."%' or 
           city like'%".$searchValue."%' ) ";
}

## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];

## Total number of records with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];

## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();

while ($row = mysqli_fetch_assoc($empRecords)) {
     $data[] = array(
         "emp_name"=>$row['emp_name'],
         "email"=>$row['email'],
         "gender"=>$row['gender'],
         "salary"=>$row['salary'],
         "city"=>$row['city']
     );
}

## Response
$response = array(
     "draw" => intval($draw),
     "iTotalRecords" => $totalRecords,
     "iTotalDisplayRecords" => $totalRecordwithFilter,
     "aaData" => $data
);

echo json_encode($response);

6. jQuery Initialization and Custom Filter Handling for DataTables

This jQuery code responsible for initializing DataTables on the #empTable element and handling the custom filter functionality.

Steps in the jQuery Code:

Initializing DataTables:

Initialize the DataTable on the #empTable element and assign it to the dataTable variable.

  • Set the options for server-side processing with ‘processing’: true and ‘serverSide’: true.
  • Specify the server request method as POST using ‘serverMethod’: ‘post’.
  • Set the AJAX URL to ajaxfile.php to fetch data from the server.

Custom Filter Handling with AJAX:

  • Utilize the data option in the AJAX settings to read the values of the custom search fields – #searchByGender and #searchByName.
  • Read the values from these fields and append them to the data object, which will be sent as part of the AJAX request.

Defining DataTable Columns:

  • In the columns option, define the names of the fields that will be read from the successful callback response and displayed in the DataTable.

Handling Custom Filter Events:

  • Attach keyup and change events to the #searchByName and #searchByGender elements, respectively.
  • Call the dataTable.draw() method whenever these events trigger to redraw the DataTable and apply the custom filtering.
$(document).ready(function(){
    var dataTable = $('#empTable').DataTable({
         'processing': true,
         'serverSide': true,
         'serverMethod': 'post',
         //'searching': false, // Remove default Search Control
         'ajax': {
              'url':'ajaxfile.php',
              'data': function(data){
                    // Read values
                    var gender = $('#searchByGender').val();
                    var name = $('#searchByName').val();

                    // Append to data
                    data.searchByGender = gender;
                    data.searchByName = name;
              }
         },
         'columns': [
              { data: 'emp_name' }, 
              { data: 'email' },
              { data: 'gender' },
              { data: 'salary' },
              { data: 'city' },
         ]
    });

    $('#searchByName').keyup(function(){
         dataTable.draw();
    });

    $('#searchByGender').change(function(){
         dataTable.draw();
    });
});

7. Demo

View Demo


8. Conclusion

Utilize custom filters to enhance DataTables and improve data presentation. Remove the default search control with 'searching': false if desired. Consider using a single search button for efficiency.

Always call draw() to update the DataTable when events trigger. Create dynamic and user-friendly tables with DataTables to leave a lasting impression on users.

Happy coding!

If you found this tutorial helpful then don't forget to share.