Requesting JSON data from url and inserting into html tables

I am trying to write code that receives JSON data from a URL and inserts it into an html table. I can only change things in the “processResponse” function. Currently it says undefined in each table. Codepen link:

https://codepen.io/mauro-scheltens/pen/OJWQwXY

Here is my code:

const requestUrl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';

function requestJSON(url) {
  let request = new XMLHttpRequest();
  request.open('GET', url);
  request.send();
  request.onload = function() {
    let response = request.response;
    processResponse(response);
  }
}

function sendRequest() {
  requestJSON(requestUrl);
}

function processResponse(response) {
  document.querySelector("#squadName").innerHTML = response.squadName;
  document.querySelector("#homeTown").innerHTML = response.homeTown;
  document.querySelector("#formed").innerHTML = response.formed;
  document.querySelector("#secretBase").innerHTML = response.secretBase;
  document.querySelector("#active").innerHTML = response.active;
}

sendRequest();
td {
  border: 2px solid black;
  border-spacing: 0;
}
<h1>Requesting data and inserting</h1>

<table id='overview-table'>
  <tr>
    <th>squadName</th>
    <th>homeTown</th>
    <th>formed</th>
    <th>secretBase</th>
    <th>active</th>
  </tr>
  <tr>
    <td id='squadName'></td>
    <td id='homeTown'></td>
    <td id='formed'></td>
    <td id='secretBase'></td>
    <td id='active'></td>
  </tr>
</table>

This is what it has to look like:

enter image description here

Can someone help me with this?

Answer

Instead of using the old XMLHttpRequest you can also use the newer fetch().

Also why have a sendRequest function whose sole purpose is to call requestJSON? Just call requestJSON directly.

Also elmements with an ID (id=”foo”) are directly available in JS code : foo.innerHTML = "something".

const requestUrl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';

const requestJSON = async url => {

  const response = await (await fetch(url)).json();
  squadName.innerHTML = response.squadName;
  homeTown.innerHTML = response.homeTown;
  formed.innerHTML = response.formed;
  secretBase.innerHTML = response.secretBase;
  active.innerHTML = response.active;
}

requestJSON(requestUrl);
td {
  border: 2px solid black;
  border-spacing: 0;
}
<h1>Requesting data and inserting</h1>

<table id='overview-table'>
  <tr>
    <th>squadName</th>
    <th>homeTown</th>
    <th>formed</th>
    <th>secretBase</th>
    <th>active</th>
  </tr>
  <tr>
    <td id='squadName'></td>
    <td id='homeTown'></td>
    <td id='formed'></td>
    <td id='secretBase'></td>
    <td id='active'></td>
  </tr>
</table>