I have successfully initialized a jQuery DataTable in an iframe, however if I try to run a function in the iframe on the same domain it reinitializes the DataTable instead of using the existing one. How can I fix this?
My code in the JS file of the Iframe:
$(document).ready(function(){
listTable.initDataTables();
});
var listTable = {
initDataTables: function() {
$.each($('.dataTable'), function(){
var jqTable = $(this);
// Define the columns
var columns = [];
var columnHeadings = jqTable.find('thead > tr:eq(1) > th');
$.each(columnHeadings, function(){
var code = $(this).attr('data-code');
var column = { data: code, defaultContent: '' };
columns.push(column);
});
// Initiate the table
var dataTable = jqTable.DataTable({
'ajax': {
'url': '/get-data',
'type' : 'GET'
},
'columns': columns,
'responsive': true,
'scroller': false,
'select': true,
'bLengthChange': false,
'bFilter': true,
'bInfo': true,
});
});
}
};
When I run the following code in a window without an iframe, all works well:
$('table').DataTable().ajax.url();
// returns '/get-data'
But when I run the following code from a parent window that contains an iframe, NULL gets returned:
$('iframe').contents().find('table').DataTable().ajax.url()
// returns NULL
I also notice that when I run the code from a parent window, navigation bars get added a second time. So it looks like the DataTable() function is creating a new instance on the same table.
I made a change in the selector of your headings (eq(0) instead of eq(1)) in order to make datatables to load properly the table.
Here is the code i made locally: main.html:
iframe.html:
With an empty file "get-data.json".
When you click on the button, it alerts you with "get-data.json".