DataTables - Uncaught TypeError: cannot read property length undefined

I saw several examples of this problem, but still could not find a solution.

The error says that it breaks into jquery.dataTables.js (version 1.10.4) in line 3287 shown below

// Got the data - add it to the table
    for ( i=0 ; i<aData.length ; i++ ) {
        _fnAddData( settings, aData[i] );
    }

This is my controller. The controller is like this because there is no db connection right now, but JSON will be returned in the same format as $ data. I tried several steps to fix the error, but I continue to work in other problems. JSON is valid.

public function test()
{
  $data = '{"persons": [{"branch": "CORP","phone_numbers": [{"desk": "5223422117"},{"mobile": "5022319224"},{"branch": "422-922-2291"}],"email": "twilliams@test.com","preferred_name": "Thomas","person_id": 368,"department": "IT","first_name": "Thomas","title": "Programming Manager","last_name": "Williams"}]}';

  $data = json_encode($data);
  echo $data;

}

My javascript

$(document).ready(function() {
     $('#directory_table').dataTable( {
         "ajax": {
             "url": "test",
             "type": "JSON"
         },
         "aoColumns": [
             { "persons": "preferred_name" },
             { "persons": "last_name" },
             { "persons": "phone_numbers.0" },
             { "persons": "phone_numbers.1" },
             { "persons": "phone_numbers.2" },
             { "persons": "email" },
             { "persons": "department" },
             { "persons": "title" }
         ]
     } );
 } );

My html

<table id='directory_table' class="display">
    <thead>
        <tr style='background: #186A9F; color: white;'>
            <th>First Name </th>
            <th>Last Name</th>
            <th>Desk Number</th>
            <th>Mobile</th>
            <th>Branch</th>
            <th>Email</th>
            <th>Department</th>
            <th>Title</th>
        </tr>
    <thead>
</table>
+4
source share
1 answer

CAUSE

DataTables , JSON , . .

:

{
    "data": [
        [ "value1", "value2" ],
        ...
    ]
}

:

{
    "data": [
        {
           "attr1": "value1",
           "attr2": "value2"
        },
        ...
    ]
}

- , , , (persons) (data).

ajax.dataSrc, ( , Ajax) .

$('#directory_table').dataTable( {
   "ajax": {
      "url": "test",
      "dataSrc": "persons"
   },
   "columns": [
      { "data": "preferred_name" },
      { "data": "last_name" },
      { "data": "phone_numbers.0.desk" },
      { "data": "phone_numbers.1.mobile" },
      { "data": "phone_numbers.2.branch" },
      { "data": "email" },
      { "data": "department" },
      { "data": "title" }
   ]
});

, JSON persons data, "dataSrc": "persons" .

DEMO

jsFiddle .

. jQuery DataTables: JavaScript .

+8

All Articles