125

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"
        }]
            });

    }       

})
7
  • 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: jsfiddle.net/gL0p0t42 Feb 11, 2015 at 12:53
  • You are not providing the source that actually call "aDataSort".
    – Daniel
    Feb 11, 2015 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, 2015 at 12:59
  • 2
    related (newer) question with answer
    – Nikos M.
    May 20, 2015 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, 2017 at 14:14

15 Answers 15

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>
4
  • 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, 2016 at 5: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). Dec 14, 2016 at 12:12
  • 3
    the <thead> must contain a <tr> , then <th>s
    – Siempay
    Nov 9, 2018 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 <thead> but you must define the columns in your DataTable() initiation like this: datatables.net/reference/option/columns.data Jul 25, 2020 at 8:49
92

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

order: [1, 'asc'],
4
  • 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, 2017 at 14:43
  • 7
    @JGreasley You can set it as an empty array: order: []
    – hogarth45
    Jul 31, 2017 at 18:20
  • 3
    Mine columns where 5 and i was specifying 7 here ! Thanks
    – aiffin
    Dec 13, 2017 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 Jun 15, 2020 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;
1
  • Thank you for your elaboration on this issue; @hogarth45 above 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. Jun 15, 2020 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.

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" ]],
1
  • 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, 2020 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"]]'

1
  • it's not relevant with the OP's question but it works on my case (using html 5 data attributes)
    – blackbiron
    Aug 26, 2020 at 17:50
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.

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 ...
2

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" ]]].

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();
1

My Solution

add this :

order: 1 ,
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 .

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.

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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.