131

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 Commented Feb 11, 2015 at 12:53
  • You are not providing the source that actually call "aDataSort". Commented 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. Commented Feb 11, 2015 at 12:59
  • 2
    related (newer) question with answer Commented 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 . Commented Jan 18, 2017 at 14:14

16 Answers 16

172

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>
Sign up to request clarification or add additional context in comments.

4 Comments

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?
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).
the <thead> must contain a <tr> , then <th>s
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
98

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

order: [1, 'asc'],

4 Comments

This one always gets me. Is there a way to default the array to 0, if the array is out of range?
@JGreasley You can set it as an empty array: order: []
Mine columns where 5 and i was specifying 7 here ! Thanks
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
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 Comment

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

Comments

6

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!

Comments

4

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

2 Comments

it's not relevant with the OP's question but it works on my case (using html 5 data attributes)
In my case this solved my issue as well; using single quotes threw the OPs message
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 Comment

There are already other answers saying basically the same thing. Please try to avoid redundant answers on questions that are years-old.
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.

Comments

3

My Solution

add this :

order: 1 ,

Comments

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

Comments

2

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 Comment

For me I commented out the code to generate a hidden table column which had another table embedded in it and ran it - I am still getting that error. I upgraded JQuery and JQuery UI to latest versions and I still get this problem. My code did NOT have jquery code to run DataTable on it - I was going to display it as a child table but not as a DataTable, that is why I never called .DataTable() on it.
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" ]]].

Comments

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 .

Comments

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.

Comments

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

Comments

0

I was getting from DataTables.min.js this error: "Uncaught TypeError: Cannot read properties of undefined (reading 'call')" when I did (modified from what I did):

$(document).ready(function () {
            var table = $('#MySelector').DataTable({
                columnDefs: [{ target: 0, width: "55%", type: "string", className: "dt-left" },
                             { target: 1, width: "10%", type: "datetime-moment", className: "dt-left" },
                             { target: 2, width: "10%", type: 
                             { target: 3, width: "0", className: "dt-left", visible: false } ],
                order: [[0, 'asc']], autoWidth: false, bFilter: true, scrollCollapse: false, paging: false, bInfo: true, ordering: true 
                /*,stateSave: false*/
            });

           table.rows().every(function (e) { });
}

But for me the problem got fixed when I instead did this:

table.rows().every(function (rowIdx, tableLoop, rowLoop) {

});

Now according to DataTables.net both are supposed to be valid - but only the second example for me doesn't blow up: https://datatables.net/reference/api/rows().every()

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.