Uncaught TypeError: Can't read property 'length' from undefined when trying to populate responsive datatable with PHP?

I'm trying to populate a response 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'm 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 );            
}

      

+3


source to share


4 answers


If you want to insert an array datasource i.e. not literal objects, 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);            
}

      




This is also true if you use Jonathans offer json_encode( array(data => $list))

- you will still each element will need to wrap the array, otherwise you will get a

, d

, g

and so on, because dataTables as an array, which it expects each character is treated as an array element , data for the 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"
});

      

+2


source


When using only a string value , at least the DataTables parameter ajax

expects the response to be wrapped in another object:

Note that DataTables expects the table data to be an array of elements in an data

object parameter ...

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

      



To get this you can wrap $list

in another one array()

before encoding:

echo json_encode( array( data => $list ) );

      

+1


source


install Json Header

header('Content-type: application/json');
echo json_encode( $list ); 

      

0


source


You must also define the variable $list

before the loop while

. If not specified, it only returns the last name.

$list = []

      

0


source







All Articles