I can populate a data table just fine with static data... But when I retrieve data from an AJAX and want to implement it into the table, I cannot seem to figure it out/get it to work and it has me on my last nerve. I want to put a 200+ bounty on it that is how bad it is bugging me, but I have to wait two days and I told myself I was going to solve this issue today.
Here is first my JSFiddle that works perfectly with static data, https://jsfiddle.net/L0287qeu/.
Here is my current code for my HTML table that works perfectly after making the call to retrieve/load the data I want to populate.
<html>
<head>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<title><strong>X, DAR-Q, & Z Deliverables</strong></title>
</head>
<body>
<div class="container">
<h4 class="text-center">X, DAR-Q, & Z Deliverables</h4>
<table class = "display">
<thead>
<tr>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script>
function loadData(source, url) {
return fetch(url, { headers: { accept: "application/json; odata=verbose" } }) // make request
.then((r) => {
if (!r.ok) throw new Error("Failed: " + url); // Check for errors
return r.json(); // parse JSON
})
.then((data) => data.d.results) // unwrap to get results array
.then((results) => {
results.forEach((r) => (r.source = source)); // add source to each item
return results;
});
}
window.addEventListener("load", function () {
Promise.all([
loadData("XDeliverables", "/_api/web/lists/getbytitle('XDeliverables')/items?$select=Program,To,Date,Approved,Notes"),
loadData("YDeliverables", "/_api/web/lists/getbytitle('YDeliverables')/items?$select=Program,To,Date,Approved,Notes"),
loadData("ZDeliverables", "/_api/web/lists/getbytitle('ZDeliverables')/items?$select=Program,To,Date,Approved,Notes"),
])
.then(([r1, r2, r3]) => {
const objItems = r1.concat(r2,r3);
var tableContent =
'<table id="deliverablesTable" style="width:100%" border="1 px"><thead><tr><td><strong>Program</strong></td>' +
"<td><strong>To</strong></td>" +
"<td><strong>Date Submitted</strong></td>" +
"<td><strong>Approved</strong></td>" +
"<td><strong>Notes</strong></td>" +
"</tr></thead><tbody>";
for (var i = 0; i < objItems.length; i++) {
tableContent += "<tr>";
tableContent += "<td>" + objItems[i].Program + "</td>";
tableContent += "<td>" + objItems[i].To + "</td>";
tableContent += "<td>" + objItems[i].Date + "</td>";
tableContent += "<td>" + objItems[i].Approved + "</td>";
tableContent += "<td>" + objItems[i].Notes + "</td>";
tableContent += "</tr>";
}
$(tableContent).appendTo("#deliverables").DataTable();
})
.catch((err) => {
alert("Error: " + err);
console.error(err);
});
});
</script>
</body>
</html>
from DataTables from AJAX Call
No comments:
Post a Comment