“Uncaught TypeError: Cannot read property 'length' of undefined” after destroying and reinitializing
“Uncaught TypeError: Cannot read property 'length' of undefined” after destroying and reinitializing
My initial initialization of DataTables() loads the table with serverSide datatables.
Data.columns = [];
$('th').each(function(item,i){
Data.columns.push({'data': $(this).text().trim()})
});
$('#searchtable').DataTable({
'serverSide': true,
'ajax': '/api/v1/reports/?format=datatables',
'columns': Data.columns
});
When a user performs a custom (non-datatables) search, I make an ajax request to a non-datatables api function. The api function sends a response back, I do $('#searchtable').DataTables({ destroy : true })
, the table is cleared and reloaded with new data, and I reinitialize the table.
Here is the function that loads the new (search-generated table):
Template = {
fill_search_table : function(data){
Data.table = $('#searchtable');
Data.table.html('');
var $thead = $('<thead/>', {});
var $tbody = $('<tbody/>', {});
var header_values = Object.keys(data[0])
var $thead_tr = $('<tr/>');
$thead.append($thead_tr);
$(header_values).each(function(i, item){
var $th = $('<th/>', {
text: item
})
$thead_tr.append($th);
});
Data.table.append($thead);
cells = new Array(header_values.length).fill(0);
$(data).each(function(i, item){
var $tr = $('<tr/>', {});
$tbody.append($tr);
for(cell in item){
cell_header_index = header_values.indexOf(cell);
var $td = $('<td/>', {
text: item[cell]
})
cells[cell_header_index] = $td;
}
$(cells).each(function(j, cell){
$tbody.append(cell)
})
})
Data.table.append($tbody);
Data.table.DataTable({destroy: true})
Data.table.DataTable({
bPaginate: false,
bFilter: false,
bInfo: false,
});
},
}
When reinitializing the table, I get: "Uncaught TypeError: Cannot read property 'length' of undefined"
What is going wrong?
Answers
We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.
Cheers,
Colin
dev.campaignfinances.org/data
The initial load of the datatable is fine. The error occurs after searching. @colin
You may need to create a new account to access the page. Takes a few seconds
My problem was that I was appending <td> to <tbody> insteaf of <tr>
Yep, that'll do it. Glad you got it sorted,
Colin