I'm trying to fetch data using XMLHttpRequest from a URL (GET API) in JSON form and then display that data in a HTML table.
I have been able to fetch the data, but not display it correctly.
My table displays as:
Name ID Generation Type Region
Name ID Generation Type Region
Instead of:
Name ID Generation Type Region
Bulabasaur 1 First Grass Kanto
My JSON data returns as:
[{
ability: "Overgrow",
category: "Seed"
description: "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger.",
gender: "M",
generation: "First",
height: "2' 04''",
id: 1,
name: "Bulbasaur",
picture: "bulbasaur.jpg",
region: "Kanto",
type: "Grass, Poison",
weakness: "Fire, Flying, Ice, Psychic",
weight: "15.2"
}]
This is my JavaScript code:
var rootURL = "http://localhost:8080/WorksheetPokemon/rest/pokemon";
var xhttp = new XMLHttpRequest();
function pokemonTable(){
xhttp.open('GET', rootURL, true);
xhttp.onreadystatechange = function() {
//console.log(this.responseText);
if (xhttp.readyState === XMLHttpRequest.DONE) {
var status = xhttp.status;
if (status === 0 || (status >= 200 && status < 400)) {
var json = JSON.parse(xhttp.responseText);
createTable(json);
} else {
console.log("Error");
}
}
};
xhttp.send();
}
function createTable(json) {
console.log(json);
var tableBody = document.getElementById("table_body");
// Populate table
json.forEach((row) => {
var tr = document.createElement("tr");
Object.keys(row).forEach((cell) => {
var td = document.createElement("td");
td.textContent = cell;
tr.appendChild(td);
});
tableBody.appendChild(tr);
});
}
document.addEventListener("DOMContentLoaded", pokemonTable());
Object.keys()
will return all the keys from the object in an array.
What you need is the values, which you can get with Object.values()
.
function createTable(json) {
var tableBody = document.getElementById("table_body");
// Populate table
json.forEach((row) => {
var tr = document.createElement("tr");
Object.values(row).forEach((cell) => {
var td = document.createElement("td");
td.textContent = cell;
tr.appendChild(td);
});
tableBody.appendChild(tr);
});
}