Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables: Cannot read property 'length' of undefined

I understand this a popular issue, and I have read all the similar questions here on Stack Overflow and other sites (including the datatables website).

To clarify, I am using

  • PHP Codeigniter
  • Materliazecss

I have also made sure that I received the JSON array correctly:

[{"name_en":"hello","phone":"55555555"},{"name_en":"hi","phone":"00000000"}] 

My HTML table looks like this:

<table id="customer_table">      <thead>          <tr>             <th>Name</th>             <th>Phone</th>          </tr>      </thead> </table> 

And here is my document.ready function:

  $(document).ready(function(){             //$('#customer_table').DataTable();             $('#customer_table').DataTable( {                 "ajax": 'json',                 "dataSrc": "",                  "columns": [                     { "data": "email" },                     { "data": "name_en" }                 ]             });   }); 

The error I am getting is

Uncaught TypeError: Cannot read property 'length' of undefined

like image 931
Abdelrahman Shoman Avatar asked Dec 15 '15 10:12

Abdelrahman Shoman


People also ask

Can't access property length d is undefined?

The "Cannot read property 'length' of undefined" error occurs when accessing the length property on an undefined value. To solve the error, make sure to only access the length property on data types that support it - arrays or strings.

Can't access property length f is undefined?

Hi, As mentioned by Ankur, "Cannot read property length from undefined" error occurs when a variable is defined but it does not have any value and you call in a method/property like "length" on it. An easy fix would be check for variable on which you are using length and debug why it does not have any value on it.

What is dataSrc Datatable?

dataSrc( data ) Description: As a function dataSrc provides the ability to manipulate the data returned from the server from one form into another. For example, if your data is split over multiple arrays you might combine it into a single array to return for processing and display by DataTables.


1 Answers

It's even simpler: just use dataSrc:'' option in the ajax defintion so dataTable knows to expect an array instead of an object:

    $('#pos-table2').DataTable({                   processing: true,                   serverSide: true,                   ajax:{url:"pos.json",dataSrc:""}             }     ); 

See ajax options

like image 191
tomsoft Avatar answered Sep 19 '22 21:09

tomsoft