Home > Back-end >  Error - No Data in Table (using JavaScript Fetch)
Error - No Data in Table (using JavaScript Fetch)

Time:01-08

I am using Fetch API to get jsonified data from Flask app to show in Bootstrap5 table. I am also using Bootstrap5 code to initialize the table.

When I open the page, I see response HTML Page

Why am seeing "No data available in Table" in response?

I tried this:

<table id="dataTable"  >
<thead>
  <tr>
    <th>ID</th>
    <th>Name</th>
  </tr>
</thead>
</table>

<script>
  const table = document.getElementById('dataTable');
  fetch('employees')
    .then(response => response.json())
    .then(data => {
      data.forEach(employee => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${employee.id}</td>
          <td>${employee.name}</td>
        `;
        table.appendChild(row);
      });
    });
</script>

CodePudding user response:

You need to remove the element with the "No data available" before adding new elements to the table.

Assuming that the "No data available" is an tr you can do like this

<script>
  const table = document.getElementById('dataTable');
  var noDataElement = table.getElementsByTagName('tr')[0];
  noDataElement.remove();

  fetch('employees')
    .then(response => response.json())
    .then(data => {
      data.forEach(employee => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${employee.id}</td>
          <td>${employee.name}</td>
        `;
        table.appendChild(row);
      });
    });
</script>

CodePudding user response:

This code works perfectly:

<script>
  $(document).ready(function () {
$('#dataTable').DataTable()
  const table = document.getElementById('dataTable');
  var noDataElement = table.getElementsByTagName('td')[0];
  noDataElement.remove();
  fetch('employees')
    .then(response => response.json())
    .then(data => {
      data.forEach(employee => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${employee.id}</td>
          <td>${employee.name}</td>
        `;
        table.appendChild(row);
      });
    })
    });
</script>
  • Related