skip to Main Content
<!DOCTYPE html>
<html>
  <head>
    <title>Fetch data from API and display in table using AJAX</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <h1>Data</h1>
    <table id="table" border="1"></table>

    <script>
      function load(){
        fetch("https://gorest.co.in/public/v2/users")
          .then(result => result.json)
          .then(json => show(json)) }
      function show(data){
      let table = document.getElementById('table');
      for(let i=0; i< data.length; i++){
        let obj = data[i];
        console.log(obj);
        let row = document.createElement('tr');
        let name = document. createElement('td');
        id.innerHTML = obj.
        row.appendChild(name)
        table.appendChild(row)
  }


}
    </script>
  </body>
</html>

I need to fetch data from a url. I have to present it in a table. First I only need to display username with a button "view more". When view more will be clicked I have to fetch data from another api related to that particular username .I have written few line of code but they are not working. Any suggestionns? your text

3

Answers


  1. it might be better to use $.append instead of appenChild

    <!DOCTYPE html>
    <html>
      <head>
        <title>Fetch data from API and display in table using AJAX</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      </head>
      <body>
        <h1>Data</h1>
        <table id="table">
           <tbody></tbody>
        </table>
    
        <script>
          async function load(){
            let json = await(
            await fetch("https://gorest.co.in/public/v2/users")
            ).json()
            show(json) 
              }
          function show(data){
          for(let i=0; i< data.length; i++){
            let obj = data[i];
            $('#table tbody').append(`
              <tr>
                <td> ${obj.name} </td>
                <td> ${obj.email} </td>
              </tr>
            `)
           }
         };load()
        </script>
      </body>
    </html>
    Login or Signup to reply.
  2. Here is a simpler plain JavaScript version

    You need to call .json() to get the object

    I am only guessing what you meant with "show more" but here is a working script

    let table;
    const show = (data) => {
      table.innerHTML = data
        .map(({id,name,email, gender,status}) => `<tr>
          <td>${name} <button class="more" data-id="${id}">view more...</button></td>
          <td hidden>${email}</td>
          <td hidden>${gender}</td>
          <td hidden>${status}</td>
          </tr>`)
        .join("");
    };
    const load = () => {
      fetch("https://gorest.co.in/public/v2/users")
        .then(result => result.json())
        .then(show);
    };
    window.addEventListener("DOMContentLoaded", () => {
      table = document.getElementById('table');
      table.addEventListener("click", (e) => {
        const tgt = e.target.closest("button");
        if (!tgt) return;
        tgt.closest("tr").querySelectorAll("td").forEach(td => td.hidden = false);
      })
      load();
    });
    .more { float:right; margin-left: 5px; }
    <h1>Data</h1>
    <table border="1">
      <tbody id="table"></tbody>
    </table>
    Login or Signup to reply.
  3. As per your request i fetched the data from api in the load() fucntion and then displayed it in table form using show() function.

    I have kept a global boolean variable isMore to show more details fetched from api when clicked on Show More button.

    There i added a dynamic button and when it is clicked then showMore() function is called.

    This function changes the value of boolean variable isMore to true and then calls the load() function again.
    This load() function inturn calls the show() function by passing the data and there i check the condition for boolean isMore if it is true then i show more details as per your need..

    isMore = false
    async function load() {
      let response = await fetch("https://gorest.co.in/public/v2/users")
      let data = await response.text()
      show(JSON.parse(data))
    }
    
    function show(data) {
      let table = document.getElementById('table');
      table.innerHTML = '';
      for (let i = 0; i < data.length; i++) {
        let obj = data[i];
        let row = document.createElement('tr');
        let name = document.createElement('td');
        let email = document.createElement('td');
        let gender = document.createElement('td');
        let status = document.createElement('td');
        let btn = document.createElement('td');
        let id = document.createElement('td');
        btn.innerHTML = `<button id='viewMoreBtn' onclick="showMore()"> View More</button>`;
        name.innerText = `${data[i]['name']}`
        email.innerText = `${data[i]['email']}`
        gender.innerText = `${data[i]['gender']}`
        status.innerText = `${data[i]['status']}`
        id.innerText = `${data[i]['id']}`
        row.appendChild(name)
        row.appendChild(btn)
        if (isMore) {
          if (row.hasChildNodes) {
            row.removeChild(row.lastElementChild)
          }
          row.appendChild(email)
          row.appendChild(id)
          row.appendChild(gender)
          row.appendChild(status)
    
    
        }
        table.appendChild(row)
      }
    
    
    }
    
    
    load()
    async function showMore() {
      console.log("Hello");
      isMore = true;
      load()
    }
    <title>Fetch data from API and display in table using AJAX</title>
    <h1>Data</h1>
    <table id="table" border="1"></table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search