98

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

Abdelrahman Shoman
  • 2,882
  • 7
  • 36
  • 61

12 Answers12

134

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

Rowan Richards
  • 401
  • 8
  • 20
tomsoft
  • 4,448
  • 5
  • 28
  • 35
  • 3
    I'd like to highlight that the `dataSrc` attribute has to go inside the `ajax` object, not as a sibling. This had me spinning my wheels for a while. – Alex R Jan 17 '21 at 19:57
  • if anyone tries this and it doesn't work, I found that this property was undefined no matter what I set it to - I had to change the `sAjaxDataProp: '',` property (top level property) in order to make mine work – Pete Apr 22 '22 at 15:13
79

CAUSE

This errors TypeError: Cannot read property 'length' of undefined usually means that jQuery DataTables cannot find the data in the response to the Ajax request.

By default jQuery DataTables expects the data to be in one of the formats shown below. Error occurs because data is returned in the format other than default.

Array of arrays

{ 
   "data": [
      [
         "Tiger Nixon",
         "System Architect",
         "$320,800",
         "2011/04/25",
         "Edinburgh",
         "5421"
      ]
   ]
}

Array of objects

{ 
   "data": [
      {
         "name": "Tiger Nixon",
         "position": "System Architect",
         "salary": "$320,800",
         "start_date": "2011/04/25",
         "office": "Edinburgh",
         "extn": "5421"
      }
   ]
}

SOLUTION

Use default format or use ajax.dataSrc option to define data property containing table data in Ajax response (data by default).

See Data array location for more information.

LINKS

See jQuery DataTables: Common JavaScript console errors for more details.

Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
47

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"
  }, ...]
}
h3nr1ke
  • 363
  • 6
  • 19
Abdelrahman Shoman
  • 2,882
  • 7
  • 36
  • 61
16

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
      }
      },
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
  • 1
    Thanks a million, been searching for a needle in a haystack all day. What does that code do? Specifically the part starting at `error` to `return d`? I was getting same error as above, but couldn't find the typo or whatever, this solved my issue. – Sum None Jun 27 '18 at 00:26
4

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}
            ));
    }
})
gvivetapl
  • 445
  • 1
  • 5
  • 15
2

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"
                        }]
            });
        });
chrki
  • 6,143
  • 6
  • 35
  • 55
chetan
  • 249
  • 3
  • 6
1

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.

Haris ur Rehman
  • 2,593
  • 30
  • 41
1

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

dead_webdev
  • 164
  • 2
  • 9
0

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.

Roman Susi
  • 4,135
  • 2
  • 32
  • 47
0

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

Adam Hey
  • 1,512
  • 1
  • 20
  • 24
0

In my HTML code the table had two tags opening. I fixed this and it worked perfectly. I wasn't using ajax on that table.

Check table structure with few values to validate.

-2

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

$.ajax({
  url: "url",
  type: 'GET',
  success: function(data) {
    var new_data = {
      "data": data
    };
    console.log(new_data);
  }
});
Pingolin
  • 3,161
  • 6
  • 25
  • 40
HamzaMushtaq
  • 1,660
  • 13
  • 13