DataTables: Cannot read property 'length' of undefined

Abdelrahman Shoman picture Abdelrahman Shoman · Dec 15, 2015 · Viewed 126.6k times · Source

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

Answer

tomsoft picture tomsoft · Nov 4, 2016

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