1

In my code, I want to fetch data from api and view in html table using javascript.

fetch("http://dummy.restapiexample.com/api/v1/employees").then(
  res => {
    res.json().then(
      data => {
        console.log(data);
        if (data.length > 0) {

          var temp = "";
          data.forEach((itemData) => {
            temp += "<tr>";
            temp += "<td>" + itemData.id + "</td>";
            temp += "<td>" + itemData.employee_name + "</td>";
            temp += "<td>" + itemData.employee_salary + "</td>";
          });
          document.getElementById('data').innerHTML = temp;
        }
      }
    )
  }
)
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th>ID</th>
        <th>Employee Name</th>
        <th>Salary</th>
      </tr>
    </thead>
    <tbody id="data">

    </tbody>
  </table>
</div>

The api data can view but when I want to view those data to html table is shows nothing. any idea how I show those fetched data into the html table.

1 Answer 1

5

You have been using the data object. But if you inspect the console your array is inside data.data. So you need to use data.data to iterate over the array.

fetch("http://dummy.restapiexample.com/api/v1/employees").then(
  res => {
    res.json().then(
      data => {
        console.log(data.data);
        if (data.data.length > 0) {

          var temp = "";
          data.data.forEach((itemData) => {
            temp += "<tr>";
            temp += "<td>" + itemData.id + "</td>";
            temp += "<td>" + itemData.employee_name + "</td>";
            temp += "<td>" + itemData.employee_salary + "</td></tr>";
          });
          document.getElementById('data').innerHTML = temp;
        }
      }
    )
  }
)
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th>ID</th>
        <th>Employee Name</th>
        <th>Salary</th>
      </tr>
    </thead>
    <tbody id="data">

    </tbody>
  </table>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.