1

new to building web apps. please advise on some resources to read up if you have any good ones!

Problem: I have created a call API on AWS - https://tnmw5vn267.execute-api.us-east-1.amazonaws.com/dev the output is a JSON object.

However, I have no clue how to put this into a HTML page (i.e. How to get the JSON object into the HTML and then subsequently show it as a table), only:

`function CreateTableFromJSON() { var myEmployees = [ { "FirstName": "Benjamin", "LastName": "Tan" } ]

    // EXTRACT VALUE FOR HTML HEADER. 
    // ('Book ID', 'Book Name', 'Category' and 'Price')
    var col = [];
    for (var i = 0; i < myEmployees.length; i++) {
        for (var key in myEmployees[i]) {
            if (col.indexOf(key) === -1) {
                col.push(key);
            }
        }
    }

    // CREATE DYNAMIC TABLE.
    var table = document.createElement("table");

    // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

    var tr = table.insertRow(-1);                   // TABLE ROW.

    for (var i = 0; i < col.length; i++) {
        var th = document.createElement("th");      // TABLE HEADER.
        th.innerHTML = col[i];
        tr.appendChild(th);
    }

    // ADD JSON DATA TO THE TABLE AS ROWS.
    for (var i = 0; i < myEmployees.length; i++) {

        tr = table.insertRow(-1);

        for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            tabCell.innerHTML = myBooks[i][col[j]];
        }
    }

    // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
    var divContainer = document.getElementById("showData");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);
}`

The above only generates a static table that doesn't update based on my API output. Am not sure how to do it?

eurytix
  • 33
  • 5
  • What do you mean when you say "how to put this into a HTML page"? Please be more descriptive. Also, please post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your attempt – Melvin Abraham Jun 19 '21 at 17:55
  • you should use a fetch api, please go through the documentation of fetch API for more info https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – leox Jun 19 '21 at 17:57

2 Answers2

1

Here's how I might approach it using plain JS.

  1. Use fetch to get the data from the API.

  2. Use template literals to build up a sequence of HTML strings using map and join.

  3. Add the final string to the page.

const json = '[{"LatestGreetingTime":"2021-06-19T15:47:10.539Z","ID":"Hello from Lambda, Benjamin Tan","FirstName":"Benjamin","LastName":"Tan"},{"LatestGreetingTime":"2021-06-19T13:44:33.761Z","ID":"Hello from Lambda, ichal shodin","FirstName":"ichal","LastName":"shodin"},{"LatestGreetingTime":"2021-06-19T13:44:33.761Z","ID":"Hello from Lambda, victoria Lovelace","FirstName":"victoria","LastName":"Lovelace"}]';


// This simulates a call to your API
function mockFetch() {
  return new Promise((res, rej) => {
    setTimeout(() => res(json), 1000);
  });
}

// Grab the button, and a div where you can place the table
const button = document.querySelector('button');
const div = document.querySelector('div');

// Add an event listener to your button that
// callApi when it's clicked
button.addEventListener('click', callApi, false);

// As mentioned the comments you should be using
// the fetch API here, and it would look like
// fetch(url).then(res => res.json).then(buildTable)
function callApi() {
  mockFetch()
    .then(res => JSON.parse(res))
    .then(buildTable);
}

// This function takes the data, extracts the headings
// from the first object, and then builds the row data.
// It finally puts everything together as a template literal
// and adds it to the div
function buildTable(data) {
  const headings = buildHeadings(Object.keys(data[0]));
  const rows = buildRows(data);
  div.innerHTML = `<table><thead>${headings}</thead><tbody>${rows}</tbody></table>`;
}

// Iterate over the headings array and return heading HTML
function buildHeadings(headings) {
  return headings.map(heading => `<th>${heading}</th>`).join('');
}

// Iterate over the data return row HTML
function buildRows(data) {
  return data.map(row => `<tr>${buildCells(row)}</tr>`).join('');
}

// Iterate over the row data and return cell HTML
function buildCells(row) {
  return Object.values(row).map(cell => `<td>${cell}</td>`).join('');
}
table { border-collapse: collapse; padding 0.2em; }
td { padding: 0.5em }
<button>Call API</button>
<div />
Andy
  • 61,948
  • 13
  • 68
  • 95
0

Let me show you the solution. Firstly you need to fetch JSON from API by fetch function. After that, you need to put it to a particular HTML element by .innerHTML

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
</head>
<body>
<script>
  async function fetchDataAndRenderTable() {
    const serverURL = 'https://tnmw5vn267.execute-api.us-east-1.amazonaws.com/dev'
    const dataFromTheServer = await fetch(serverURL).then(res => res.json())
    const tableHTMLElement = document.createElement('table')

    tableHTMLElement.innerHTML = `
      <table style="width:100%">
        <tr>
          <th>FirstName</th>
          <th>LastName</th>
        </tr>

        ${
          dataFromTheServer.map(item => {
            return `
              <tr>
                <td>${item.FirstName}</td>
                <td>${item.LastName}</td>
              </tr>
            `
          })
        }
      </table>
    `

    document.body.appendChild(tableHTMLElement)
  }

  fetchDataAndRenderTable()
</script>
</body>
</html>

PS. But your API needs to allow CORS, otherwise you will be not able to fetch it from the browser