0

Error Message: Notice: Undefined index: draw.

Also, my JSON response comes out wrong: {"draw":0,"recordsTotal":23,"recordsFiltered":23,"data":[]}

....draw (above) is supposed to be 1 not 0.

Code:

$(document).ready(function() {
var asc = true;
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "server.php",
"type": "POST",
},


columnDefs: [{
targets: -1,
defaultContent: '<button type="button">Delete</button>'
}],
rowGroup: {
dataSrc: 1
}
});
});
 </script>
   <body>

 <table id="example" class="display" style="width:100%" class="table table-striped table-bordered table-hover table-condensed">
  <thead class="thead-inverse">
 <tr>
 <th> ID </th>
 <th>First Name </th>
 <th>Last Name </th>
 <th>Position </th>
 <th>Date </th>
<th>Updated </th>
 <th>Action</th>
 </thead> 
 </tr>
         <tbody>

         </tbody>
     </table>
     </div>         
 <?php

 $data=array();
 $requestData= $_REQUEST;

 $count=mysqli_query($con, "SELECT * FROM employees");
 $totalData= $count->num_rows;
 $totalFiltered=$totalData;

 $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 ),  
            "recordsFiltered" => intval( $totalFiltered ), 
            "data"            => $data   // total data array
            );

 echo json_encode($json_data);
 ?>
 </script>
   <body>

 <?php
 $data=array();
 $requestData= $_REQUEST;
 $query=mysqli_query($con, "SELECT * FROM employees");
 $totalData= $count->num_rows;
 $totalFiltered=$totalData;

 if( !empty($requestData['search']['value']) ) {
    // if there is a search parameter
    $sql = "SELECT first_name, last_name, position, date, updated";
    $sql.=" FROM employees";
    $sql.=" WHERE first_name LIKE '".$requestData['search']['value']."%' ";
    // $requestData['search']['value'] contains search parameter
    $sql.=" OR last_name LIKE '".$requestData['search']['value']."%' ";
     $sql.=" OR position LIKE '".$requestData['search']['value']."%' ";
      $sql.=" OR date LIKE '".$requestData['search']['value']."%' ";
       $sql.=" OR updated LIKE '".$requestData['search']['value']."%' ";

    $query=mysqli_query($con, $sql);
    $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

    $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($con, $sql); // again run query with limit

} else {   

    $sql = "SELECT first_name, last_name, position, date, updated";
    $sql.=" FROM employees";
    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."   LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
    $query=mysqli_query($con, $sql);

}

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

    $nestedData[] = $row["titulo"];
    $nestedData[] = $row["descripcion"];

    $data[] = $nestedData;
}

 ?>

Good chance I will not get an answer. But figured it is worth a try. I am still waiting back a response from datatables.net. Thanks.

Server.php File:

 <?php
    $table = 'employees';
    $primaryKey = 'id'; // Table's primary key

    $columns = array(
        array( 'db' => 'id', 'dt' => 0 ),
        array( 'db' => 'first_name', 'dt' => 1 ),
        array( 'db' => 'last_name',  'dt' => 2 ),
        array( 'db' => 'position',   'dt' => 3 ),
        array( 'db' => 'date',     'dt' => 4 ),
         array( 'db' => 'updated',     'dt' => 5 ),
    );

    $sql_details = array(
        'user' => 'username',
        'pass' => 'password',
        'db'   => 'database',
        'host' => 'localhost'
    );

    require( 'ssp.class.php' );

    echo json_encode(
        SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
    );
    ?>
  • those are just warnings you can silent them visit this answer https://stackoverflow.com/questions/19938003/how-to-turn-off-notice-reporting-in-xampp but question why are you not passing any $_GET data? when your code required that – Beginner Aug 17 '18 at 02:15
  • Are you referring to this? "draw" => intval( $requestData['draw'] ) It should be a requestData not get. I was trying both ways. I removed the get['draw']. –  Aug 17 '18 at 02:28
  • Yes the error seemed very minor because the whole datatables still worked. I was just curious if I missed something which triggered draw to be 0 instead of 1. –  Aug 17 '18 at 02:30
  • That's a PHP notice, and Datatables is just passing it along. It's saying that your `draw` array element doesn't exist. You can use `isset()` or `array_key_exists()` to check whether it exists or not, and handle it there, but that doesn't really solve your problem (I suspect that you're getting a zero value because the index doesn't exist). Have you gone into PHP and dumped the record there to see what's actually in it? – BobRodes Aug 17 '18 at 02:38
  • Ok. Someone posted an answer with one similar to your comment. I am brainstorming a few ways to fix the issue.. –  Aug 17 '18 at 04:30

3 Answers3

0

One of your issues, is that the variables you're trying to access aren't defined. You're trying to access your 'draw' variable, but in no place do you actually define it.

I see you attempt to access it at $requestData= $_REQUEST; in conjunction with "draw" => intval( $requestData['draw'] ) but $_REQUEST only gets the $_GET and $_POST variables of the current page. Read more here: http://php.net/manual/en/reserved.variables.request.php

You would need to do a separate request to server.php to get those values.

The reason why your draw is 0 is because intval(null) is 0. (An undefined variable is null)

Funce
  • 50
  • 6
  • Ok. I was somewhat suspicious of the REQEST. I tried putting $_REQEST = 1; just to see what would happen. Nothing much changed. The solution is probably in this link: https://datatables.net/manual/server-side –  Aug 17 '18 at 04:35
  • ""The draw counter that this object is a response to - from the draw parameter sent as part of the data request. Note that it is strongly recommended for security reasons that you cast this parameter to an integer, rather than simply echoing back to the client what it sent in the draw parameter, in order to prevent Cross Site Scripting (XSS) attacks." –  Aug 17 '18 at 04:38
  • Looks like I need to put the integer (1?) in somehow? –  Aug 17 '18 at 04:38
  • The result from Draw, is generated from server.php. Do you have that file? – Funce Aug 17 '18 at 04:52
  • just edited in my server.php on bottom. I do not have anything related to draw in my server.php I noticed.... do you need to see the ssp.class file too? –  Aug 17 '18 at 05:04
  • $recordsTotal = $resTotalLength[0][0]; /* * Output */ return array( "draw" => isset ( $request['draw'] ) ? intval( $request['draw'] ) : 0, "recordsTotal" => intval( $recordsTotal ), "recordsFiltered" => intval( $recordsFiltered ), "data" => self::data_output( $columns, $data ) ); } –  Aug 17 '18 at 05:19
  • The above is my ssp.class.php. Not sure if you need that but it does have draw in it. I noticed the 0 I changed it to 1 but nothing seemed to happen. –  Aug 17 '18 at 05:19
  • My server-script looks the same (to me at least) like the given example: https://datatables.net/examples/data_sources/server_side.html. Did you get a chance to look at it? Thanks. –  Aug 19 '18 at 01:09
0

Answer: Change $_get to $_post in the server.php file.

This is the response I got from datatables.net. The post above is related to this response too:

"Your server script is returning the draw value. The SSP doc indicates what your script should be doing with this parameter: https://datatables.net/manual/server-side#Returned-data

The draw parameter increments for each draw request. This portion of the doc explains its use: https://datatables.net/manual/server-side#Sent-parameters

The dataSrc option does not affect the draw value."

I will edit in the full answer once as we solve this completely. But this is the general answer for now...

0

use isset();

like below

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

Notice: Undefined index: draw. will be solved

Vivek Kumar
  • 81
  • 1
  • 5