Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'length' of undefined when trying to populate responsive datatable using PHP?

I am trying to fill a responsive datatable with an AJAX request to a PHP script, the response is returned in JSON_encode format, I can see the response in the XHR requests:

["abc","def","ght","jkl"]

Here is the code I am using:

<table class="table table-striped table-bordered table-hover" id="dataTables-example">
  <thead>
    <tr>
      <th>Name</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Name</th>
    </tr>
  </tfoot>
</table>
$('#dataTables-example').DataTable({
  responsive: true,
  "ajax": "search_autocomplete.php",
});

Here is the PHP script:

if ($result->num_rows >0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    $list[] =$row['name'];
  }     
  echo json_encode( $list );            
}
like image 508
njwin07 Avatar asked Dec 04 '25 10:12

njwin07


2 Answers

When you want to insert an array datasource, i.e not object literals, the source must be an array of arrays :

[["abc"],["def"],["ght"],["jkl"]]
$('#dataTables-example').DataTable({
  "ajax": {
    url: "search_autocomplete.php",
    dataSrc: ''
  }
});
if ($result->num_rows >0) {
  while($row = $result->fetch_assoc()) {
    $list[] = array($row['name']); //<----
  }     
  echo json_encode($list);            
}

That is also the case if you use Jonathans suggestion, json_encode( array(data => $list)) - you would still need to wrap each item into an array, otherwise you get the a, d, g etc because dataTables access each string as the array it expects, each character is treated as an array item, data for a column.

if ($result->num_rows >0) {
  while($row = $result->fetch_assoc()) {
    $list[] = array($row['name']); //<----
  }     
  echo json_encode(array('data' => $list));
}
$('#dataTables-example').DataTable({
  "ajax": "search_autocomplete.php"
});
like image 193
davidkonrad Avatar answered Dec 07 '25 00:12

davidkonrad


When using just a string value, at least, DataTables's ajax option expects the response to be wrapped in another object:

Note that DataTables expects the table data to be an array of items in the data parameter of the object ...

{
    "data": [
        // row 1 data source,
        // row 2 data source,
        // etc
    ]
}

To get this, you can wrap the $list in another array() before encoding:

echo json_encode( array( data => $list ) );
like image 35
Jonathan Lonowski Avatar answered Dec 06 '25 23:12

Jonathan Lonowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!