简体   繁体   中英

datatables + lengthMenu + All + serverside processing + handling -1/All

this is a basic datatables fiddle

this is a basic datatables fiddle with lengthMenu

What I want to do is get this working in my serverside processing example.

I can get the dropdown to appear right doing the following to my index.php file.

$(document).ready(function() {
  var dataTable = $('#employee-grid').DataTable({
    "lengthMenu": [
      [10, 25, 50, -1],
      [10, 25, 50, "All"]
    ],
    "processing": true,
    "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");

      }
    }
  });
});

So that works okay if I select 10 , 25 or 50 but if I select All I get No data found in the server . So my issue is in my employee-grid-data.php file,noted here , and this is where I am having my difficulty. I need to do an if statement to handle this All option or -1 as this is what I pass to the server when I select All in $requestData['length']

I have identified the 2 areas where I use $requestData['length'] and this I belive to be the issue.

$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 , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees"); // again run query with limit

So what I have to do is try and write such that:
if $requestData['length'] NOT equals -1
do this line
else
do this line without using $requestData['length'] as a parameter.

This is where I am having difficulty.

This is my attempt, but this could be a syntax issue or something else. I'm not very good at debugging this.

if ($requestData['length']!==-1){
    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."   LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
} else {
    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");

When I visit the page index.php I get No data found in the server and in the console I get 500 (Internal Server Error) .

Can anyone advise what my code should look like? Or how could I debug this?

I would ideally like to be able to add a basic if else statement just to see if I could get that bit right alone, but not sure how to do this in this setup. with Javasecript I would normally use console.log

Here is my entire employee-grid-data.php file for reference:

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

$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.


if( !empty($requestData['search']['value']) ) {
    // if there is a search parameter
    $sql = "SELECT employee_name, employee_salary, employee_age ";
    $sql.=" FROM employee";
    $sql.=" WHERE employee_name LIKE '".$requestData['search']['value']."%' ";    // $requestData['search']['value'] contains search parameter
    $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 without limit in the query 

    if ($requestData['length']!==-1){   
        $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 , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
    } else {
        $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']
    }
    $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees"); // again run query with limit

} else {    

    $sql = "SELECT employee_name, employee_salary, employee_age ";
    $sql.=" FROM employee";

    if ($requestData['length']!==-1){
        $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."   LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
    } else {
        $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']
    }
    $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

?>

edit1 good link for testing http://phpfiddle.org/

This is the code I had to add to handle the $requestData['length'] equaling -1. I had to add wherever I had $requestData['length'] . This is the best I could do.

if ($requestData['length'] > 0 ){
    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."   LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
} else {
    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."   ";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM