How to add Custom Filter in DataTable – AJAX and PHP

When DataTable is initialized on the HTML table then it generates pagination which has sorting, searching on all columns, change the number of records display features.

The default search control mainly uses to finds value on all columns and display filter list. But it can be customized.

Sometimes it requires to add some custom search filters based on the records available like – date filtering, single field search, etc.

In this tutorial, I show how you can add the custom filter to the DataTable and use it with AJAX.

How to add Custom Filter in DataTable – AJAX and PHP


  1. Table structure
  2. Configuration
  3. Download & Include
  4. HTML
  5. Script
  6. PHP
  7. Demo
  8. Conclusion

1. Table structure

Create employee table and added some records.

CREATE TABLE `employee` (
  `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. Configuration

Create a config.php for the database configuration.

Completed Code


$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

  • Download Datatables from here.
  • 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='' rel='stylesheet' type='text/css'>

<!-- jQuery Library -->
<script src=""></script>

<!-- Datatable JS -->
<script src=""></script>


Create two <table> elements –

  • The first <table > element is used to add a custom filter element. I have added one input box for name searching and <select > element for gender filtering.
  • The second <table > is used to initialize dataTable.

Completed Code

<!-- Datatable CSS -->
<link href='' rel='stylesheet' type='text/css'>

<!-- jQuery Library -->
<script src=""></script>

<!-- Datatable JS -->
<script src=""></script>

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

   <!-- Table -->
   <table id='empTable' class='display dataTable'>
         <th>Employee name</th>


5. PHP

Create ajaxfile.php file.

Read DataTables $_POST values and store in variables.

Here, also read custom POST values – searchByName and searchByGender.

Prepare search query –

  • If $searchByName is not empty then add emp_name search.
  • If $searchByGender is not empty then add gender search.
  • If $searchByValue is not empty then search value on emp_name, email, and city fields.

Count total record with or without filter from employee table and assign to the variable.

Loop on the fetched records and initialize $data Array with associative Array which has a similar key as defined in columns option in dataTable() method.

Initialize $response Array with draw, iTotalRecords, iTotalDisplayRecords, and aaData keys.

Return $response Array in JSON format.

Completed Code

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(

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

echo json_encode($response);

6. Script

Initialize dataTable on #empTable and assign to dataTable variable.

For sending AJAX request add processing: true, serverSide: true, serverMethod: post, ajax.

Set AJAX url and with data option read custom search fields values – #searchByGender, #searchByName and append in the data object.

In the columns options specify field name which gets read on successful callback.

Define keyup and change event on #searchByName and #searchByGender. Call dataTable.draw() method wherever these events trigger to redraw the DataTable.

Completed Code

  var dataTable = $('#empTable').DataTable({
    'processing': true,
    'serverSide': true,
    'serverMethod': 'post',
    //'searching': false, // Remove default Search Control
    'ajax': {
       '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' },



7. Demo

View Demo

8. Conclusion

If you only want to display custom search control and remove default search control then add 'searching': false option.

You can also create a single search button for searching instead of defining separate events on search controls.

Make sure to call draw() method to redraw the DataTable when an event trigger.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

41 thoughts on “How to add Custom Filter in DataTable – AJAX and PHP”

    • Add a new column the table and specify in DataTable columns option e.g. {data: ‘action’},. In the ajaxfile.php specify you action controls in the ‘action’ key in the $data[] Array.

  1. Hi thanks for your article, is there any way to filter only rows with empty value for a specific column? Maybe when a checkbox is ticked

  2. Hi,

    Nice tutorial. How I can do this if the data is divided in multiple rows in the database?

    Added imgur link with screenshot of the data divided in multiple rows.

    • Hi David,
      Are you trying to make the following query –

      SELECT p.ID,
      MAX(CASE WHEN pm.meta_key = ‘__wpdm_acf_Contratos_DUNS’ then pm.meta_value ELSE NULL END) as __wpdm_acf_Contratos_DUNS,
      MAX(CASE WHEN pm.meta_key = ‘__wpdm_acf_Contratos_Ejecucion’ then pm.meta_value ELSE NULL END) as __wpdm_acf_Contratos_Ejecucion

      FROM wp_posts p LEFT JOIN wp_postmeta pm ON ( pm.post_id = p.ID)
      WHERE p.post_status=’publish’
      GROUP BY

  3. I am very much appreciated for your great tutorial, is it possible to migrate the ‘ Delete Multiple Selected Records’ functions? many thanks

  4. Hi guys can you help with Date Range filtering using ,ajax and date picker.

    “processing” : true,
    “serverSide” : true,
    “order” : [],
    “ajax” : {
    url: sHostRoot +”/Daaggregate”,
    FunctionDate:sPosOrderDateFrom, sPOsOrderDateTo
    dataType: “json”,
    success: function (data) {
    alert(“shooos -” + data);
    $.each(data, function (index, order) {
    alert(“boom” + order.OrderNo);
    var row1 = [order.OrderNo, order.SalesPerson,order.FunctionDate,order.CollectionDate,

    “scrollY”: “290px”,
    // “dom”: ‘rt’,
    //”scrollY”: true,
    “scrollX”: true,
    “autoWidth”: true,
    “”: ‘single’,
    “rowCallback”: function( row, data ) {

    “data”: dataSet,
    pageResize: true,
    // “title”: “Button”,
    “className”: ‘details-control’,
    “orderable”: false,
    “data”: null,
    “defaultContent”: “+”
    {‘data’: ‘OrderNo’, “className”: “tblFormDetailsHeader”},
    //{‘data’: ‘orderId’, “className”: “tblFormDetailsHeader”},
    //{‘data’: ‘orderName’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘SalesPerson’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘FunctionDate’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘CollectionDate’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘ActualCollectionDate’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘CollectedBy’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘ReturnDate’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘ActualReturnDate’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘ReturnedBy’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘CompletedDate’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘CompletedBy’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘HireTotal’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘RefundableDeposit’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘Discount’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘OrderTotal’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘TotalPaid’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘BalanceDue’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘InvoiceText’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘OrderItems’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘PaymentHistory’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘Customer’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘Status’, “className”: “tblFormDetailsHeader”},
    {‘data’: ‘Created’, “className”: “tblFormDetailsHeader”}


    Nothing happens.i got the data as Objects,
    But My dataTable does not Populate the data.

  5. Thanks for taking the time, it was a breeze to adapt to my Codeigniter 3 development environment. In my environment the task is divide in the parts: 1) Datatables library compatible with CI, 2) Some controller under controllers/api/Datatables/[Object]/Lists that handles the Datatables / Database / Json enconding and 3) The javascript. Here are example for anybody that may be using CI.

    function index($object_name = NULL)


    function Lists()

    // Filters
    $aFilters = array();
    $searchByName = $this->input->post(‘searchByNombreItem’);
    $searchByEstadoCredito = $this->input->post(‘searchByEstadoCredito’);

    if(null !== $searchByName && ” !== $searchByName) {
    ‘fColumn’ => ‘nombre_item’,
    ‘fValue’ => strtolower($searchByName),
    ‘fType’ => ‘where’,
    ‘fEscape’ => TRUE,

    if(null !== $searchByEstadoCredito && ” !== $searchByEstadoCredito) {
    ‘fColumn’ => ‘estado_credito’,
    ‘fValue’ => strtolower($searchByEstadoCredito),
    ‘fType’ => ‘where’,
    ‘fEscape’ => TRUE,

    $aTable = ‘ci_vw_creditos’;
    $aColumns = array(‘DT_RowId’,’id’,’codigo_identificacion’,’nombre_completo’,
    $json = $this->datatables->get_json($aTable, $aColumns, $aFilters);
    echo $json;


    — Escoja un concepto —
    Servicios Legales
    Servicio Mantenimiento
    Poliza compra terreno

    — Escoja un estado —

    Pago Mensual

    JavaScript (implement through a footer inclusion after loading the view)

    $(document).ready(function() {
    var dtCredits = $(“#credits”).DataTable({
    “ajax”: {
    “url”: ‘api/DataTables/Credits/Lists’,
    “dataSrc”: ‘data’,
    “type”: ‘POST’,
    “data”: function(data){
    var nombre_item = $(“#searchByNombreItem”).val();
    var estado_credito = $(“#searchByEstadoCredito”).val();

    data.searchByNombreItem = nombre_item;
    data.searchByEstadoCredito = estado_credito;
    “columns”: [
    {data: ‘codigo_identificacion’},
    {data: ‘nombre_completo’},
    {data: ‘lote_codigo’},
    {data: ‘nombre_item’},
    {data: ‘estado_credito’},
    {data: ‘termino_pago’},
    {data: ‘saldo’},
    {data: ‘pago_mensual’},
    /* Actions */ { mRender: function(data, type, row) {
    return ”
    +’ ‘
    +’ ‘
    +’ ‘;
    “columnDefs”: [
    {“targets”: [7,8], “orderable”: false},
    {“targets”: [0,1,2], “searchable”: true},
    {“targets”: [6], className: ‘dt-body-right’},
    {“targets”: [7], className: ‘dt-body-right’},
    {“targets”: [6], render: $.fn.dataTable.render.number(‘,’, ‘.’, 0)},
    {“targets”: [7], render: $.fn.dataTable.render.number(‘,’, ‘.’, 0)}
    “bJqueryUI”: true,
    “bLengthChange”: false,
    “iDisplayLength”: 10,
    “initComplete”: function(settings, json) {
    “language”: {
    “url”: “//”,
    “processing”: true,
    “serverSide”: true,
    “order”: [[0, “asc”]],



    • You can do that in an actions column ie:

      add an action column to your columns

      “columns”: [
      { data: “qID” },
      { data: “addedDate” },
      { data: “qty” },
      { data: “item” },
      { data: “description” },
      { data: “cost” },
      { data: “total” },
      { data: “action” }

      Add actions in your php to the last item, I’ve set the first column as its value.

      $columns = array(
      0 => PREFIX.’quotes.qID’,
      1 => PREFIX.’quotes.addedDate’,
      2 => PREFIX.’quote_items.qty’,
      3 => PREFIX.’quote_items.item’,
      4 => PREFIX.’quote_items.description’,
      5 => PREFIX.’quote_items.cost’,
      6 => PREFIX.’’,
      7 => PREFIX.’quote_items.qID’

      then when your creating your data array add your links to action

      foreach($filterd_results_paginated as $row) {
      $data[] = [
      ‘qID’ => $row->qID,
      ‘addedDate’ => date(‘jS M Y H:i A’, strtotime($row->addedDate)),
      ‘qty’ => $row->qty,
      ‘item’ => $row->item,
      ‘description’ => $row->description,
      ‘cost’ => $row->cost,
      ‘total’ => $row->total,
      ‘action’ => “Edit

  6. Hi,
    Thank you very much for your sharing.

    I want your help on something. I want to make DESC according to customers_id, but I couldn’t. How should I do the code below?

    select * from customers
    WHERE 1 “.$searchQuery.” and company_id=”.$company.” and customers_id=”.$customers_id.” order by “.$columnName.” “.$columnSortOrder.”, customers_id DESC limit “.$row.”,”.$rowperpage;

    • Hi Jansi,
      The JSON generating for Datatable is invalid. Navigate to the browser network tab and select the datatable AJAX file. It will show if there is any error on the page. Use this for debugging.

  7. Thank you very much for your tutorial .

    What should I do if i would like to have a search button instead of live searching? Thank you 🙂

  8. Thanks for the article, but i wanna ask you something. Can we make datatabales default SEARCH BOX, search the data that’s already in the table. When we type something in the default SEARCH BOX, it does not trigger server side processing again. Only when we using the Custom Filter. Thanks before, and sorry for my English.

  9. Is there a way to implement this when creating the table using external JSON-file data ?
    I’ve a column named ‘category’ which contains multiple values of a data and I want to create a filter based on that column. I would need to use sub-string method to search for the string element in the column I think ?

  10. Hi Sir. By the way, I am very much appreciated your great tutorial.
    Can I ask if possible, how to add an update button in the last column?
    Thank you for your response.

  11. what about if i have a column that contains (id) for another table?
    i need this tutorial code but mysql table contains column join to another table
    what should i do in this column ?
    please send the same code to me with 2 tables mysql example as soon as possible
    it’s very important to me


Leave a Comment