skip to Main Content

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.

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, Y, & Z Deliverables</strong></title>
</head>
<body>
    <div class="container">
      <h4 class="text-center">X, Y, & 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>

4

Answers


  1. Here’s an example of populating Datatables with Ajax. In the HTML the table is defined as:

    <table ID=tblClients><thead><tr><th>Name</th><th>Intake Date</th><th>Counselor</th></tr></thead></table>
    

    Then in the document.ready function this code initializes the Datatable:

    dtClients = $('#tblClients').DataTable({
      ajax: 'nwcs.php?proc=get_clients',
      dom: 'iftp',
      paging: true,
      pageLength: 15,
      pagingType : 'full_numbers',
      select: {style: 'single'}
    });
    

    The data returned from PHP is JSON, which DataTables requires. It looks like this:

    {"data":[["Laura Jessup","02/22/2020","Michelle Putnam"],["Jackie McCord","02/24/2020","Paula Curran"],["Gary Shafer","02/25/2020","Paula Curran"]]}
    
    Login or Signup to reply.
  2. You almost had it. To render the datatable as such, the content has to be rendered by the browser first.

    The difference between your working JSFiddle and your non-working code is that in the non-working code, the table with id deliverablesTable is part of the string tableContent and not rendered at the time you call .DataTable() whereas in your working example with static data, the table example is already defined in the HTML part and therefore already rendered.

    Please find code sample below. I replaced your Ajax Calls with static data for demonstration purposes, but it will work the same way once you migrated the most important changes (commented as such)

    <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>
        <!-- RESERVE DIV FOR HOLDING THE DATA TABLE -->
        <div id="data" class="container">
        </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>
    
          const objItems = [
            {
              Program: 1,
              To: 2,
              Date: 3,
              Approved: 3,
              Notes: 5
            }
    
          ];
          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>";
          }
          // Insert tableContent into the div to make sure it gets rendered
          $("#data").html(tableContent);
          // Make it a datatable now
          $("#deliverablesTable").DataTable();
    </script>
    </body>
    </html>
    
    Login or Signup to reply.
  3. I used code from above example, Please find code sample below. Ajax link is working when I was testing . this is an online mocking link . you can create own mock request and test it if that ajax link is not working. I tested from above solution that it working fine .

    <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>
        <!-- RESERVE DIV FOR HOLDING THE DATA TABLE -->
        <div id="data" class="container">
        </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>
     var objItems=[];
                $( document ).ready(function() {
           $.ajax({
                type: "GET",
                dataType: "json",
                url: "https://run.mocky.io/v3/1ee61ecd-d1ab-4ad8-8976-f94bcd296264",
                complete: function(data) {
                  objItems=data.responseJSON.data;
                  renderTable();
                }
            });
        });
            
    function renderTable(){
         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>";
          }
          // Insert tableContent into the div to make sure it gets rendered
          $("#data").html(tableContent);
          // Make it a datatable now
          $("#deliverablesTable").DataTable();
    }
          
          
    </script>
    </body>
    </html>
    Login or Signup to reply.
  4. There is nothing wrong in your code just check ajax call is returning data.
    https://nightly.datatables.net/_api/web/lists/getbytitle('XDeliverables‘)/items?$select=Program,To,Date,Approved,Notes
    put a fully qualified url in browser and check get request.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search