code breakdown

html table:

  • < table > creates a TABLE
  • < tr > creates a ROW
  • < th > makes the text a column HEADER
  • < tbody id = "results" > defines an element id, to be used within JavaScript

This code creates two tables in html that display covid statistics.

<!-- HTML table fragment for page -->
<table>
  <thead>
  <tr>
    <th>Time</th>
    <th>All-time Cases</th>
    <th>Recorded Deaths</th>
    <th>Active Cases</th>
  </tr>
  </thead>
  <tbody>
    <td id="time"></td>
    <td id="total_cases"></td>
    <td id="total_deaths"></td>
    <td id="active_cases"></td>
  </tbody>
</table>

<table>
  <thead>
  <tr>
    <th>Country</th>
    <th>All-time Cases</th>
    <th>Recorded Deaths</th>
    <th>Active Cases</th>
  </tr>
  </thead>
  <tbody id="result">
    <!-- generated rows -->
  </tbody>
</table>

Constant variables

This code gathers data and stores them in variables with the "const" keyword, "const" means that you cannot change the variable beyond its declaration.

Key things to know:

  • The document object "result" represents table body in the HTML above.
  • If you want to access any element in an HTML page in JavaScript, you always start by accessing the document object. In this case, we are accessing "result" and defining a "resultContainer"
  • In the code, in following cells, document elements are created and organized for each Joke, each is added to the "resultContainer" as a row in the table body.
  • Accessing the api is done using the variables url and options, this is setup to fetch the Jokes from the backend
// prepare HTML result container for new output
const resultContainer = document.getElementById("result");

// prepare fetch options
const url = "https://flask.nighthawkcodingsociety.com/api/covid/";
const headers = {
  method: 'GET', // *GET, POST, PUT, DELETE, etc.
  mode: 'cors', // no-cors, *cors, same-origin
  cache: 'default', // *default, no-cache, reload, force-cache, only-if-cached
  credentials: 'omit', // include, *same-origin, omit
  headers: {
    'Content-Type': 'application/json'
    // 'Content-Type': 'application/x-www-form-urlencoded',
  },
};

Fetch

This code uses the "fetch" keyword to get API data and add that to the table

Key things to understand:

  • The "url" "response" is checked in case the site is down and returns an error
  • On successful fetch, the code places each Joke in the HTML table body using a "for" loop and creating document elements from each "row" of the fetched "data".
  • The creation of each Haha and Boohoo "onclick" "button" is also done in the same loop.
  • Updates to backend are setup to occur with each onclick, each click calls the "reaction" function
// fetch the API
fetch(url, headers)
// response is a RESTful "promise" on any successful fetch
.then(response => {
  // check for response errors
  if (response.status !== 200) {
      const errorMsg = 'Database response error: ' + response.status;
      console.log(errorMsg);
      const tr = document.createElement("tr");
      const td = document.createElement("td");
      td.innerHTML = errorMsg;
      tr.appendChild(td);
      resultContainer.appendChild(tr);
      return;
  }
  // valid response will have json data
  response.json().then(data => {
      console.log(data);
      console.log(data.world_total)

      // World Data
      document.getElementById("time").innerHTML = data.world_total.statistic_taken_at;
      document.getElementById("total_cases").innerHTML = data.world_total.total_cases;
      document.getElementById("total_deaths").innerHTML = data.world_total.total_deaths;
      document.getElementById("active_cases").innerHTML = data.world_total.active_cases;

      // Country data
      for (const row of data.countries_stat) {
        console.log(row);

        // tr for each row
        const tr = document.createElement("tr");
        // td for each column
        const name = document.createElement("td");
        const cases = document.createElement("td");
        const deaths = document.createElement("td");
        const active = document.createElement("td");

        // data is specific to the API
        name.innerHTML = row.country_name;
        cases.innerHTML = row.cases; 
        deaths.innerHTML = row.deaths; 
        active.innerHTML = row.active_cases; 

        // this builds td's into tr
        tr.appendChild(name);
        tr.appendChild(cases);
        tr.appendChild(deaths);
        tr.appendChild(active);

        // add HTML to container
        resultContainer.appendChild(tr);
      }
  })
})

catch errors

This code catches errors if access to the server is blocked

// catch fetch errors (ie ACCESS to server blocked)
.catch(err => {
  console.error(err);
  const tr = document.createElement("tr");
  const td = document.createElement("td");
  td.innerHTML = err;
  tr.appendChild(td);
  resultContainer.appendChild(tr);
});

full code

<!-- HTML table fragment for page -->
<table>
  <thead>
  <tr>
    <th>Time</th>
    <th>All-time Cases</th>
    <th>Recorded Deaths</th>
    <th>Active Cases</th>
  </tr>
  </thead>
  <tbody>
    <td id="time"></td>
    <td id="total_cases"></td>
    <td id="total_deaths"></td>
    <td id="active_cases"></td>
  </tbody>
</table>

<table>
  <thead>
  <tr>
    <th>Country</th>
    <th>All-time Cases</th>
    <th>Recorded Deaths</th>
    <th>Active Cases</th>
  </tr>
  </thead>
  <tbody id="result">
    <!-- generated rows -->
  </tbody>
</table>

<!-- Script is layed out in a sequence (no function) and will execute when page is loaded -->
<script>
  // prepare HTML result container for new output
  const resultContainer = document.getElementById("result");

  // prepare fetch options
  const url = "https://flask.nighthawkcodingsociety.com/api/covid/";
  const headers = {
    method: 'GET', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'default', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'omit', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
  };

  // fetch the API
  fetch(url, headers)
    // response is a RESTful "promise" on any successful fetch
    .then(response => {
      // check for response errors
      if (response.status !== 200) {
          const errorMsg = 'Database response error: ' + response.status;
          console.log(errorMsg);
          const tr = document.createElement("tr");
          const td = document.createElement("td");
          td.innerHTML = errorMsg;
          tr.appendChild(td);
          resultContainer.appendChild(tr);
          return;
      }
      // valid response will have json data
      response.json().then(data => {
          console.log(data);
          console.log(data.world_total)

          // World Data
          document.getElementById("time").innerHTML = data.world_total.statistic_taken_at;
          document.getElementById("total_cases").innerHTML = data.world_total.total_cases;
          document.getElementById("total_deaths").innerHTML = data.world_total.total_deaths;
          document.getElementById("active_cases").innerHTML = data.world_total.active_cases;

          // Country data
          for (const row of data.countries_stat) {
            console.log(row);

            // tr for each row
            const tr = document.createElement("tr");
            // td for each column
            const name = document.createElement("td");
            const cases = document.createElement("td");
            const deaths = document.createElement("td");
            const active = document.createElement("td");

            // data is specific to the API
            name.innerHTML = row.country_name;
            cases.innerHTML = row.cases; 
            deaths.innerHTML = row.deaths; 
            active.innerHTML = row.active_cases; 

            // this builds td's into tr
            tr.appendChild(name);
            tr.appendChild(cases);
            tr.appendChild(deaths);
            tr.appendChild(active);

            // add HTML to container
            resultContainer.appendChild(tr);
          }
      })
  })
  // catch fetch errors (ie ACCESS to server blocked)
  .catch(err => {
    console.error(err);
    const tr = document.createElement("tr");
    const td = document.createElement("td");
    td.innerHTML = err;
    tr.appendChild(td);
    resultContainer.appendChild(tr);
  });
</script>