Reputation: 911
My code
<div id = "showData" class="box-body"></div>
<script>
$(document).ready(function(){
$.ajax({
url: "http://127.0.0.1:4220/pipeline/v1/bpwi/",
success: function (data) {
var col = [];
var _data = JSON.parse(data)
for (var i = 0; i < _data.length; i++) {
for (var key in _data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < _data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = _data[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
//var divContainer = $("#showData").dataTable();
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
})
})
</script>
This code will get me a nice table with header and data dynamically inserted but without a pagination. I would love to add a pagination and for that I already tried
var divContainer = document.getElementById("showData").dataTable();
but nothing happen. There was no table at all. I read the example for dataTable here and it looks like I have to manually write the header first in the div
and table
section.
Is there a way that I can use dataTable with my current code?
Thank you for your help
Upvotes: 0
Views: 2426
Reputation: 1511
Here's a working datatables with ajax call, you just need to allow cross-origin so before running, install this plugin and here to undestand why
$(document).ready(function() {
$('#example').DataTable({
"ajax": "https://datatables.net/examples/ajax/data/arrays.txt"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<html>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</body>
</html>
Upvotes: 1