Reputation: 29
I'm trying to get my data from the API into the table.
I've tried loops but it won't work
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "login", limit: 20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" +myObj[x].name+ "</tr></td>";
}
txt += "</table>"
document.getElementById("myData").innerHTML = txt;
console.log(JSON.parse(this.responseText));
}
};
xmlhttp.open("GET", "https://api.github.com/users", true);
xmlhttp.setRequestHeader("Content-type", "application//x-www-form-urlencoded");
xmlhttp.send("x="+dbParam);
I would like for the table to be filled with the API data
Upvotes: 1
Views: 63
Reputation: 2019
Because the API is not returning any key named - name
Hit this URL on browser and see all the keys in response
I am changing key name to id, you may use any key which is being returned in response:
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" +myObj[x].id+ "</td></tr>";
}
txt += "</table>"
Upvotes: 0
Reputation: 2386
Try this:
var obj, dbParam, xmlhttp, myObj, x = 0, objLen, txt = "";
obj = { table: "login", limit: 20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
objLen = myObj.length;
txt += "<table border='1'>";
while (x < objLen) {
txt += "<tr>";
for (let [key, value] of Object.entries(myObj[x])) {
txt += "<td>" + value + "</td>";
}
txt += "</tr>";
x++;
}
txt += "</table>";
document.getElementById("myData").innerHTML = txt;
// console.log(JSON.parse(this.responseText));
}
};
xmlhttp.open("GET", "https://api.github.com/users", true);
xmlhttp.setRequestHeader("Content-type", "application//x-www-form-urlencoded");
xmlhttp.send("x="+dbParam);
<div id="myData"></div>
It shows all the fetched data in the table. One login in one column. You may change the HTML and manipulate as per your need.
Upvotes: 0
Reputation: 3613
You are closing the <tr>
before the <td>
:
txt += "<tr><td>" +myObj[x].name+ "</tr></td>";
fix:
txt += "<tr><td>" +myObj[x].name+ "</td></tr>";
Upvotes: 1