Tillix76
Tillix76

Reputation: 29

Table data from api

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

Answers (3)

ajitksharma
ajitksharma

Reputation: 2019

Because the API is not returning any key named - name

Hit this URL on browser and see all the keys in response

https://api.github.com/users

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

Sami Ahmed Siddiqui
Sami Ahmed Siddiqui

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

aviya.developer
aviya.developer

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

Related Questions