Datatables When Html Table Is Created Through Import Of Xml
Solution 1:
Beside the obvious problem with asynchronicity - the dataTable is initialised before your AJAX has finished - it generally is a bad idea to build such table layouts programmatically, especially when dealing with dataTables. It is hard to maintain and hard to read, but also produces an overhead since dataTables will regenerate the <tbody>
structure anyway. If you have many records it can have an unnessecary negative impact on performance. I would suggest that you parse the XML into a valid data array and pass that array
to dataTables as data
. Example :
functionloadData(rocol) {
var data = [];
$(rocol).find('row').each(function(){
data.push([
$(this).find("Col0").text(),
$(this).find("Col1").text(),
$(this).find("Col2").text()
])
})
return data;
}
$("#chart").DataTable({
data : loadData(rocol)
})
demo -> http://jsfiddle.net/mond9ret/
The final code when loading via AJAX would be
$.ajax({
url: "rocol.xml",
success: function(xml) {
$("#chart").DataTable({
data: loadData(xml)
})
}
})
This ensures
- Things happends in the right order
- Easier to maintain
- You let dataTables itself build the table.
Solution 2:
Since AJAX calls work on a differen thread than the main, the datatable gets loaded before the data from de AJAX is in the table. If you do changes to the tabel after datatables has loaded, you need to call the draw function.
https://datatables.net/reference/api/draw()
Do this in your ajax success handler after the inserting.
Also: you could init datatables after the insertions in the table;
$(document).ready(function(){
$.ajax({
type: "GET",
url: "rocol.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('row').each(function(){
varCl0 = $(this).find("Col0").text();
varCl1 = $(this).find("Col1").text();
varCl2 = $(this).find("Col2").text();
$('<tr></tr>').html('<td>'+Cl0+'</td><td>'+Cl1+'</td><td>'+Cl2+'</td>').appendTo('#chart');
$('#chart').DataTable();
});
}
});
});
Post a Comment for "Datatables When Html Table Is Created Through Import Of Xml"