[jquery] 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

This question is related to jquery json codeigniter datatables html-table

The answer is


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


you can try checking out your fields as you are rendering email field which is not available in your ajax

_x000D_
_x000D_
$.ajax({_x000D_
  url: "url",_x000D_
  type: 'GET',_x000D_
  success: function(data) {_x000D_
    var new_data = {_x000D_
      "data": data_x000D_
    };_x000D_
    console.log(new_data);_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_


OK, thanks all for the help.

However the problem was much easier than that.

All I need to do is to fix my JSON to assign the array, to an attribute called data, as following.

{
  "data": [{
    "name_en": "hello",
    "phone": "55555555",
    "email": "a.shouman",
    "facebook": "https:\/\/www.facebook.com"
  }, ...]
}

If you are using ajax as a function remember it expects JSON data to be returned to it, with the parameters set.

$('#example').dataTable({
    "ajax" : function (data, callback, settings) {
        callback({
            data: [...],
            recordsTotal: 40,
            recordsFiltered: 40}
            ));
    }
})

Try as follows the return must be d, not d.data

 ajax: {
      "url": "xx/xxx/xxx",
      "type": "GET",
      "error": function (e) {
      },
      "dataSrc": function (d) {
         return d
      }
      },

It can happen when your view property name and name inside column section of data table is not matching . Make sure that property name and column data name are matching


While the above answers describe the situation well, while troubleshooting the issue check also that browser really gets the format DataTables expects. There maybe other reasons not to get the data. For example, if the user does not have access to the data URL and gets some HTML instead. Or the remote system has some unfortunate "fix-ups" in place. Network tab in the browser's Debug tools helps.


This is really late to the party, but none of the solutions above worked for me. I didn't want the "Found total xxx records" so I added info:false to the config. When I removed that everything worked.

I should note that the first page loaded fine. When I hit next, the second page loaded, but immediately threw the above console error


When you have JSON data then the following error appears enter image description here

A better solution is to assign a var data for the local json array object, details see: https://datatables.net/manual/tech-notes/4

This is helps you to display table contents.

 $(document).ready(function(){   

        $('#customer_table').DataTable( {
         "aaData": data,

           "aoColumns": [{
                            "mDataProp": "name_en"
                        }, {
                            "mDataProp": "phone"
                        }, {
                            "mDataProp": "email"
                        }, {
                            "mDataProp": "facebook"
                        }]
            });
        });

In my case, i had to assign my json to an attribute called aaData just like in Datatables ajax example which data looked like this.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to codeigniter

DataTables: Cannot read property 'length' of undefined How to set time zone in codeigniter? php codeigniter count rows CodeIgniter: 404 Page Not Found on Live Server Only variable references should be returned by reference - Codeigniter How to pass a parameter like title, summary and image in a Facebook sharer URL How to JOIN three tables in Codeigniter how to get the base url in javascript How to get id from URL in codeigniter? How to disable PHP Error reporting in CodeIgniter?

Examples related to datatables

Datatables Select All Checkbox DataTables: Cannot read property style of undefined How do I filter date range in DataTables? DataTables: Cannot read property 'length' of undefined TypeError: $(...).DataTable is not a function jQuery DataTables Getting selected row values How to manually update datatables table with new JSON data DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined How to redraw DataTable with new data Datatables: Cannot read property 'mData' of undefined

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?