SquigglyBoy
SquigglyBoy

Reputation: 1

Trying to Display API Data in HTML

I am trying to make an API call and display that data on my HTML page. Currently no data is displayed when the button is clicked, but the API call is made successfully as I can track my usage on another page. My code is below:

<!DOCTYPE html>
<html>
<body>

<h1>API Data</h1>

<div id="container">
    <div id="api">Nothing Yet</div>
</div>

<br>

<button type="button" onclick="loadAPI()">Change Content</button>

<script>
function loadAPI() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "API URL with Token here", false);
  xhttp.addEventListener("load", loadData);
  xhttp.send();
}

function loadData() {
  document.getElementById('api').innerText = JSON.parse(this.responseText);
}
</script>

</body>
</html>

Upvotes: 0

Views: 4798

Answers (1)

Pei Qi Tea
Pei Qi Tea

Reputation: 304

No data is displayed because you're not putting the data into the target element.

To insert data into #api, you need to do something like

document.getElementById('api').innerHTML = apiResponse; // no underscore
// or
document.getElementById('api').innerText = apiResponse;

I'll leave it for you to read up on security. https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Also, XMLHttpRequest is asynchronous unless specified otherwise (in a param). So the most reliable way is to display the data in the load event listener. Your final code should be something like:

// Making a XMLHttpRequest
function loadAPI() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "API URL with Token Here", false);
  xhttp.addEventListener("load", loadData);
  xhttp.send();
}

// Displaying the data
function loadData() {
  document.getElementById('api').innerText = this.responseText;
}

Note if your response is in JSON, you need to JSON.parse(this.responseText) to access the array/objects.

Upvotes: 1

Related Questions