Multi Column Search not filtering data

Multi Column Search not filtering data

ScrScr Posts: 1Questions: 1Answers: 0

Hi All,
I am new to datatables, hence need help.
I have PHP page where Datatable is populated from MySQL Database. But when started to code for multi column search, for some reason it doe snot filter. I do get values from input controls but the Datatable is not re-drawn.
the code for same is is as follows
PHP

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "recruit";
$drawData = 1;

$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',
    3=> 'id'
);

// 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, id";
$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"];
    $nestedData[] = $row["id"];
    
    $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

the container HTML is

    <body>
        <div class="header"><h1>DataTable demo (Server side) in Php,Mysql and Ajax </h1></div>
        <table cellpadding="3" cellspacing="0" border="0" style="width: 67%; margin: 0 auto 2em auto;">
        <thead>
            <tr>
                <th>Target</th>
                <th>Search text</th>
                <th>Treat as regex</th>
                <th>Use smart search</th>
            </tr>
        </thead>
                            <tbody>
                        <tr id="filter_col1" data-column="0">
                            <td>Column - Name</td>
                            <td align="center"><input type="text" class="column_filter" id="col0_filter"></td>
                            <td align="center"><input type="checkbox" class="column_filter" id="col0_regex"></td>
                            <td align="center"><input type="checkbox" class="column_filter" id="col0_smart" checked="checked"></td>
                        </tr>
                        <tr id="filter_col2" data-column="1">
                            <td>Column - Salary</td>
                            <td align="center"><input type="text" class="column_filter" id="col1_filter"></td>
                            <td align="center"><input type="checkbox" class="column_filter" id="col1_regex"></td>
                            <td align="center"><input type="checkbox" class="column_filter" id="col1_smart" checked="checked"></td>
                        </tr>
                        <tr id="filter_col3" data-column="2">
                            <td>Column - Age</td>
                            <td align="center"><input type="text" class="column_filter" id="col2_filter"></td>
                            <td align="center"><input type="checkbox" class="column_filter" id="col2_regex"></td>
                            <td align="center"><input type="checkbox" class="column_filter" id="col2_smart" checked="checked"></td>
                        </tr>
                </tbody>
                </table>
        <div class="container">
            <table id="employee-grid" name="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>

JS is as

            function filterColumn ( i ) {
                $('#employee-grid').DataTable().column( i ).search(
                    $('#col'+i+'_filter').val(),
                    $('#col'+i+'_regex').prop('checked'),
                    $('#col'+i+'_smart').prop('checked')
                ).draw();
            }
            $(document).ready(function() {
                var dataTable = $('#employee-grid').DataTable( {
                    "processing": true,
                    "serverSide": true,
                    "ajax":{
                        url :"employee-grid-data-2.php", // json datasource
                        type: "post" ,   //,  // method  , by default get  ***SHIVANI*** uncomment the comma and remove semi colon to include error handling
                        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");
                            
                        }
                    },
                    "columnDefs": [
                    {
                        "targets": [ 3 ],
                        "visible": false,
                        "searchable": false
                    }],
                     "aoColumnDefs": [            
                     {
                       "aTargets": [ 0 ], // Column to target
                       "mRender": function ( data, type, full ) {
                         // 'full' is the row's data object, and 'data' is this column's data
                         // e.g. 'full[0]' is the comic id, and 'data' is the comic title
                         return '<a href="example_redirect.php?id=' + full[3] + '">' + data + '</a>';
                       }
                     }
                   ]
                } );
                // to fire multi column search 
                $('input.column_filter').on( 'keyup click', function () {
                filterColumn( $(this).parents('tr').attr('data-column') );
                } );
            } );

What am I missing. I am not able to make any progress now.

Answers

  • hattricknzhattricknz Posts: 10Questions: 6Answers: 0

    did you get anywhere with this?

  • demirdemir Posts: 4Questions: 1Answers: 0
    edited January 2017

    hi I need send the data on ajax url page. How do i do it.

    Example:

    $('#myTable').DataTable({  
            "processing": true,
            "serverSide": true,
            "ajax":{
              url : base_url+dataWay,
              type: "POST" ,  
              "data":{'id':id},   //i need sen the one id . 
              error: function(){  
                  $(".data-table-error").html("");
                  $("#data-table").append('');
                  $("#data-table_processing").css("display","none");  
              }
            },
           "language": turkish,
           "columns":columns,
           "columnDefs": [
            {
              "className":'none',
              "targets": 0
            }]
     });
    

    But this not working

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395

    I need send the data on ajax url page.

    This post does not logically belong in this thread. Please start your own thread and explain your problem in more detail.

This discussion has been closed.