124

I created this fiddle to and it works well as per my requirements: Fiddle

However, when I use the same in my application I get an error in the browser console saying Cannot read property 'aDataSort' of undefined

In my application, the javascript reads something like as below: I have checked the controller output...it works well and is printed on the console too.

$(document).ready(function() {

    $.getJSON("three.htm", function(data) {
             // console.log("loadDataTable >>  "+JSON.stringify(data));
             })
             .fail(function( jqxhr, textStatus, error ) {
             var err = textStatus + ', ' + error;
             alert(err);
             console.log( "Request Failed: " + err);
             })
             .success(function(data){
                 loadDataTable(data);
             });

    function loadDataTable(data){
         $("#recentSubscribers").dataTable().fnDestroy();    
         var oTable = $('#recentSubscribers').dataTable({
             "aaData" : JSON.parse(data.subscribers),
             "processing": true,
            "bPaginate": false,
            "bFilter": false,
            "bSort": false,
            "bInfo": false,
            "aoColumnDefs": [{
            "sTitle": "Subscriber ID",
            "aTargets": [0]
        }, {
            "sTitle": "Install Location",
            "aTargets": [1]
        }, {
            "sTitle": "Subscriber Name",
            "aTargets": [2]
        }, {
            "aTargets": [0], 
            "mRender": function (data, type, full) {
                return '<a style="text-decoration:none;" href="#" class="abc">' + data + '</a>';
            }
        }],
            "aoColumns": [{
            "mData": "code"
        }, {
            "mData": "acctNum"
        }, {
            "mData": "name"
        }]
            });

    }       

})
Leandro Carracedo
  • 7,233
  • 2
  • 44
  • 50
swateek
  • 6,735
  • 8
  • 34
  • 48
  • Please be sure that the code you included it's the same as the fiddle (it's not) and the one that you are running. Also in the fiddle you have two aTargets[0], check: http://jsfiddle.net/gL0p0t42/ – Leandro Carracedo Feb 11 '15 at 12:53
  • You are not providing the source that actually call "aDataSort". – Daniel Feb 11 '15 at 12:58
  • Do you mean the id of the html table? I have taken care of that. Let me try with having one target. – swateek Feb 11 '15 at 12:59
  • @Daniel the source is the parameter to the loadDataTable() function. – swateek Feb 11 '15 at 13:38
  • @PatrickLC this isn't working what you suggested. I put the aTargets[0] in one place..but the error still persists. – swateek Feb 11 '15 at 13:43
  • 2
    [related (newer) question](http://stackoverflow.com/questions/30348028/uncaught-typeerror-cannot-read-property-adatasort-of-undefined) with answer – Nikos M. May 20 '15 at 12:39
  • 1
    I had the same problem , and i find that i order by a column number which is not exist.. i had only 3 cols but i ordered by the fifth . – mercury Jan 18 '17 at 14:14

15 Answers15

164

It's important that your THEAD not be empty in table.As dataTable requires you to specify the number of columns of the expected data . As per your data it should be

<table id="datatable">
    <thead>
        <tr>
            <th>Subscriber ID</th>
            <th>Install Location</th>
            <th>Subscriber Name</th>
            <th>some data</th>
        </tr>
    </thead>
</table>
Peter V. Mørch
  • 13,830
  • 8
  • 69
  • 103
Gkrish
  • 1,811
  • 1
  • 14
  • 18
  • 33
    What if I have a requirement that involves configuring columns and the number of said columns at Runtime? How can I implement code for the aforementioned requirement? – CS Lewis Jan 18 '16 at 05:42
  • This helped me to cure my problem of data not printed. Well it also helped me to cure one more problem of mine for datatable where i wrote `"Sort":false`, then it was able to view the list in descending order that came from controller as `Model.OrderByDescending(x=>x.Action==0).ThenBy(x=>x.Action)`. – Sorangwala Abbasali Dec 14 '16 at 12:12
  • 3
    the `` must contain a `` , then ``s – Siempay Nov 09 '18 at 10:58
  • This is true for a standard DataTable (and solve my issue). RE: @CSLewis : I'm not sure with static tables, but if you are configuring columns at runtime alongside an ajax request it is not required to have anything in `` but you must define the columns in your DataTable() initiation like this: https://datatables.net/reference/option/columns.data – Harvey Dobson Jul 25 '20 at 08:49
91

Also had this issue, This array was out of range:

order: [1, 'asc'],
hogarth45
  • 3,387
  • 1
  • 22
  • 27
  • 3
    This one always gets me. Is there a way to default the array to 0, if the array is out of range? – JGreasley Jul 31 '17 at 14:43
  • 7
    @JGreasley You can set it as an empty array: order: [] – hogarth45 Jul 31 '17 at 18:20
  • 3
    Mine columns where 5 and i was specifying 7 here ! Thanks – aiffin Dec 13 '17 at 12:29
  • 3
    One! Week! One full week! And that's a 7-day week! And I'm pretty sure that I was _not_ working 9-to-5, more like 9-to-midnight... all of that lost _because I didn't know about this bug_!! Arrrrrrrrrrrgh!! ... So much time wasted, I feel deeply ashamed, I searched the Internet over and over again and experimented with all possible solutions — none would come even close to 'fix' this. And then... by mere chance and already despairing... I came across your answer, and ta-da! In five minutes, _everything was fixed_. If I were rich, I'd send you a cheque for €10K — lol – Gwyneth Llewelyn Jun 15 '20 at 22:24
15

For me, the bug was in DataTables itself; The code for sorting in DataTables 1.10.9 will not check for bounds; thus if you use something like

order: [[1, 'asc']]

with an empty table, there is no row idx 1 -> this exception ensures. This happened as the data for the table was being fetched asynchronously. Initially, on page loading the dataTable gets initialized without data. It should be updated later as soon as the result data is fetched.

My solution:

// add within function _fnStringToCss( s ) in datatables.js
// directly after this line
// srcCol = nestedSort[i][0];

if(srcCol >= aoColumns.length) {
    continue;
}

// this line follows:
// aDataSort = aoColumns[ srcCol ].aDataSort;
Oliver Zendel
  • 2,695
  • 34
  • 29
  • Thank you for your elaboration on this issue; @hogarth45 [above](https://stackoverflow.com/a/44137826/1035977) identified the problem/bug correctly, but was not so clear about _why_ this was, in fact, _a_ problem. I'm answering you two years later... and apparently this hasn't been corrected, not even mentioned in the official documentation, at least, as far as I know. – Gwyneth Llewelyn Jun 15 '20 at 22:26
8

I faced the same problem, the following changes solved my problem.

$(document).ready(function() {
     $('.datatable').dataTable( {
            bSort: false,
            aoColumns: [ { sWidth: "45%" }, { sWidth: "45%" }, { sWidth: "10%", bSearchable: false, bSortable: false } ],
        "scrollY":        "200px",
        "scrollCollapse": true,
        "info":           true,
        "paging":         true
    } );
} );

the aoColumns array describes the width of each column and its sortable properties.

Another thing to mention this error will also appear when you order by a column number that does not exist.

Abdul Manan
  • 2,255
  • 3
  • 27
  • 51
4

In my case I had

$(`#my_table`).empty();

Where it should have been

$(`#my_table tbody`).empty();

Note: in my case I had to empty the table since i had data that I wanted gone before inserting new data.

Just thought of sharing where it "might" help someone in the future!

4

In my case I solved the problem by establishing a valid column number when applying the order property inside the script where you configure the data table.

var table = $('#mytable').DataTable({
     .
     .
     .
     order: [[ 1, "desc" ]],
E_net4
  • 27,810
  • 13
  • 101
  • 139
  • There are already other answers saying basically the same thing. Please try to avoid redundant answers on questions that are years-old. – thelr Jun 16 '20 at 12:30
3

You need to switch single quotes ['] to double quotes ["] because of parse

if you are using data-order attribute on the table then use it like this data-order='[[1, "asc"]]'

MohitGhodasara
  • 2,342
  • 1
  • 22
  • 29
3

Most of the time it occurs when something is undefined. I copied the code and removed few columns which disturbed the order by index. Carefully make changes and every variable after it. "order": [[1, "desc"]], fixed my issues previous i was using "order": [[24, "desc"]], and that index was not avaialble.

WaqarTahir
  • 109
  • 1
  • 1
2

I had this problem and it was because another script was deleting all of the tables and recreating them, but my table wasn't being recreated. I spent ages on this issue before I noticed that my table wasn't even visible on the page. Can you see your table before you initialize DataTables?

Essentially, the other script was doing:

let tables = $("table");
for (let i = 0; i < tables.length; i++) {
  const table = tables[i];
  if ($.fn.DataTable.isDataTable(table)) {
    $(table).DataTable().destroy(remove);
    $(table).empty();
  }
}

And it should have been doing:

let tables = $("table.some-class-only");
... the rest ...
Ryan Shillington
  • 23,006
  • 14
  • 93
  • 108
1

I got the error by having multiple tables on the page and trying to initialize them all at once like this:

$('table').DataTable();

After a lot of trial and error, I initialized them separately and the error went away:

$("#table1-id").DataTable();
$("#table2-id").DataTable();
Marston
  • 101
  • 1
  • 4
1

My Solution

add this :

order: 1 ,
Joukhar
  • 724
  • 1
  • 3
  • 18
1

For me adding columns in this format

columns: [
    { data: 'name' },
    { data: 'position' },
    { data: 'salary' },
    { data: 'state_date' },
    { data: 'office' },
    { data: 'extn' }
]

and ajax at this format

 ajax: {
  url: '/api/foo',
  dataSrc: ''
},

solved for me .

mercury
  • 2,390
  • 3
  • 30
  • 39
0

Old question, but in my case I was passing an unrelated order= in the URL that would sometimes be empty. Once I changed the url variable to "sortorder" or anything other than "order" the plugin began working normally.

Jason Holden
  • 168
  • 3
  • 10
0

I got the same error, In my case one of the columns was not receiving proper data. some of the columns had strings in place of Integers. after i fixed it it started working properly. In most of the cases the issue is "table not receiveing proper data".

Vishal
  • 11
  • 4
0

Just my two cents regarding order: [...]; It won't check items type, and in my case I was passing [arrOrders] as opposed to just arrOrders or [...arrOrders], resulting in [[[ 1, "desc" ], [ 2, "desc" ]]].

Juanjo Martinez
  • 679
  • 7
  • 18