DataTables: Cannot read property ‘length’ of undefined

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.

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

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

If using ASP.NET MVC, the URL can be build this way in JavaScript;

let url = '@Url.Action("Action", "Controller")';

See ajax options

LINKS

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

Reference

https://stackoverflow.com/questions/34287402/datatables-cannot-read-property-length-of-undefined

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect