Search code examples
javascriptjsonfetch

Fetch JSON and display HTML table


Here is what I am trying to do.

I created an HTML page with a table. I have all tags defined except for the body tags.

I have a javascript that fetches data from the web in JSON format, parses it, and writes elements to table body with tags using innerHTML. It works perfectly if you let it run. But if I put this "fetch" code in a function and execute this function from "onclick" of "submit" button, the logic stops working. I placed an alert at the beginning of the function and I can see it, but the fetch part is not working. I tried to use a regular function and async (await). Neither is working.

Here is my code (starting at the form). Please let me know what I'm doing wrong.

Thanks.


<form enctype="multipart/form-data" action="" method="post">
    <button type="submit" name="submit" id="Submit" value="click" onClick = getEarnings()>Click </button>
</form>

<table>
  <thead>
    <tr">
        <th>Reported Date</th>
        <th>Reported EPS</th>
        <th>Estimated EPS</th>
        <th>Surprise</th>
    </tr>
  </thead>
  <tbody id="myData"><tbody>
</table>

<script>
/* function getEarnings() { */
    fetch('https://www.alphavantage.co/query?function=EARNINGS&symbol=IBM&apikey=demo')
      .then(res => res.text())
      .then((out) =>
         {
            alert("I am here"); // I can't see it if from function
            let jsonData = JSON.parse(out);
            for (let i = 0; i < jsonData.quarterlyEarnings.length; i++)
             {
                let earnings = jsonData.quarterlyEarnings[i];
                document.getElementById("myData").innerHTML +=
                "<tr><td>" + earnings.reportedDate + "</td>" +
                "<td align='right'>" + earnings.reportedEPS + "</td>" +
                "<td align='right'>" + earnings.estimatedEPS + "</td>" +
                "<td align='right'>" + earnings.surprise + "</td></tr>";
             };
         })
      .catch(err => console.error(err));
/* } */
</script>

Solution

  • You don't need a form to fetch data. My suggestion:

    getData.onclick = () => {
      fetch('https://www.alphavantage.co/query?function=EARNINGS&symbol=IBM&apikey=demo')
        .then(res => res.text())
        .then((out) => {
          let jsonData = JSON.parse(out);
          for (let i = 0; i < jsonData.quarterlyEarnings.length; i++) {
            let earnings = jsonData.quarterlyEarnings[i];
            myData.innerHTML +=
              "<tr><td>" + earnings.reportedDate + "</td>" +
              "<td align='right'>" + earnings.reportedEPS + "</td>" +
              "<td align='right'>" + earnings.estimatedEPS + "</td>" +
              "<td align='right'>" + earnings.surprise + "</td></tr>";
          };
        })
        .catch(err => console.error(err));
    }
    <button type="button" id="getData">Get data</button>
    <table>
      <thead>
        <tr>
          <th>Reported Date</th>
          <th>Reported EPS</th>
          <th>Estimated EPS</th>
          <th>Surprise</th>
        </tr>
      </thead>
      <tbody id="myData">
        <tbody>
    </table>