How to implement YADCF into a server side DataTable

4.1k views Asked by At

I am trying to add column filters to a server side DataTables.js request (the database its using is huge). When I add the lines from YADCF, I have no functionality of the text boxes. What is the proper way to add column filters to my php file? Currently I have: index.php

<head>
    <link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">


    <script type="text/javascript" language="javascript" src="js/jquery.js"></script>
    <script type="text/javascript" language="javascript" src="js/jquery.dataTables.yadcf.js"></script>      
    <script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
    <script type="text/javascript" language="javascript" >
        $(document).ready(function() {
            'use strict';
            var dataTable = $('#employee-grid').DataTable( {
                "processing": false,
                "serverSide": true,
                "ajax":{
                    url :"employee-grid-data.php", // json datasource
                    type: "post",  // method  , by default get
                    error: function(){  // error handling
                        $(".employee-grid-error").html("");
                        $("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
                        $("#employee-grid_processing").css("display","none");

                    }
                }
            } );

        } );
    </script>
    <style>
        div.container {
            margin: 0 auto;
            max-width:760px;
        }
        div.header {
            margin: 100px auto;
            line-height:30px;
            max-width:760px;
        }
        body {
            background: #f7f7f7;
            color: #333;
            font: 90%/1.45em "Helvetica Neue",HelveticaNeue,Verdana,Arial,Helvetica,sans-serif;
        }
    </style>
</head>
<body>
    <div class="header"></h1></div>
    <div class="container">
        <table id="employee-grid"  cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
                <thead>
                    <tr>
                        <th>Employee name</th>
                        <th>Salary</th>
                        <th>Age</th>
                    </tr>
</thead>        </table>    </div></body></html>

and my sql request file: employee-grid-data.php

 <?php
 /* Database connection start */
 $servername = "localhost";
 $username = "root";
 $password = "";
 $dbname = "";

 $conn = mysqli_connect($servername, $username, $password, $dbname) or      die("Connection failed: " . mysqli_connect_error());

 /* Database connection end */


 // storing  request (ie, get/post) global array to a variable  
 $requestData= $_REQUEST;


 $columns = array( 
 // datatable column index  => database column name
0 =>'employee_name', 
1 => 'employee_salary',
2=> 'employee_age'
 );

 // getting total number records without any search
 $sql = "SELECT employee_name, employee_salary, employee_age ";
 $sql.=" FROM employee";
 $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get      employees");
 $totalData = mysqli_num_rows($query);
 $totalFiltered = $totalData;  // when there is no search parameter then      total number rows = total number filtered rows.


 $sql = "SELECT employee_name, employee_salary, employee_age ";
 $sql.=" FROM employee WHERE 1=1";
 if( !empty($requestData['search']['value']) ) {   // if there is a search      parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( employee_name LIKE '".$requestData['search']['value']."%' ";    
$sql.=" OR employee_salary LIKE '".$requestData['search']['value']."%' ";

$sql.=" OR employee_age LIKE '".$requestData['search']['value']."%' )";
 }
 $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get      employees");
 $totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result. 
 $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."        ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']."      ,".$requestData['length']."   ";
 /* $requestData['order'][0]['column'] contains colmun index,      $requestData['order'][0]['dir'] contains order such as asc/desc  */  
 $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");

 $data = array();
 while( $row=mysqli_fetch_array($query) ) {  // preparing an array
$nestedData=array(); 

$nestedData[] = $row["employee_name"];
$nestedData[] = $row["employee_salary"];
$nestedData[] = $row["employee_age"];

$data[] = $nestedData;
 }



 $json_data = array(
        "draw"            => intval( $requestData['draw'] ),   // for every      request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. 
        "recordsTotal"    => intval( $totalData ),  // total number of records
        "recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered =      totalData
        "data"            => $data   // total data array
        );

 echo json_encode($json_data);  // send data as json format

 ?>

I tried to combine my datatable function with the YADCF function found at; http://yadcf-showcase.appspot.com/DOM_Ajax_Multiple_1.10.html . However, I could not get the column filters to work. What is the proper syntax for a YADCF server side request? Or are there changes to the jquery.datatables.js or jquery.datatables.yadcf.js that I must make?

I tried to create the variable oTable but still could not the yadcf.init(oTable) to make the text boxes functional. What am I missing?

Thank you for the help.

2

There are 2 answers

2
Gyrocode.com On

Please see YADCF - Server side source example. Each column filter sends entered value as columns[X][search][value], where X is zero-based column index.

So in your example with three columns in the server-side script you will have column filters in the following variables:

  • $requestData['columns'][0]['search']['value']
  • $requestData['columns'][1]['search']['value']
  • $requestData['columns'][2]['search']['value']

You would need to adjust your PHP to take into the account these filters if their content is not an empty string.

0
ozdemir On

There is a php library on https://datatables.ozdemir.be/custom-filter2

here is the way how it can be applied to yadcf. The library has the ability to create custom filters as you need.

<?php
require_once 'vendor/autoload.php';

use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\SQLite;

$path = dirname(__DIR__).'/database/Chinook_Sqlite_AutoIncrementPKs.sqlite';
$dt = new Datatables(new SQLite($path));

$dt->query('Select TrackId, Name from Track ');

$dt->filter('TrackId', function () {
    if ($this->searchValue() === '-yadcf_delim-') {
        return '';
    }
    $val = explode('-yadcf_delim-', $this->searchValue());
    return $this->between($val[0], $val[1] ?? null);
});

echo $dt->generate();