Amina Amina - 4 days ago 5
Javascript Question

Unable to display a dynamic table with Javascript using json object

I have to retrieve data in Json , then display it in a table. I tried several methods but they didn't work. This is my code for this function, can someone help me to figure out what is wrong with this code, because i'm getting nothing displayed, and no errors. Thank you

Code updated.



<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>

<h1>display the menu</h1>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {

var obj = JSON.parse(this.responseText);

var html = "<table border='1|1'>";

for (var i = 0; i < obj.response.length; i++) {
html+="<tr>";
html+="<td>"+obj.response[i].id+"</td>";
html+="<td>"+obj.response[i].restaurant_id+"</td>";
html+="<td>"+obj.response[i].name+"</td>";
html+="</tr>";

}

html+="</table>";
$("div").html(html);
}

};
xhttp.open("GET", "http://deleted url sorry", true);
xhttp.send();

}
</script>

</body>
</html>





I have to retrieve data in Json , then display it in a table. I tried several methods but they didn't work. This is my code for this function, can someone help me to figure out what is wrong with this code. Thank



<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>

<h1>display the menu</h1>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
var obj = JSON.parse(this.responseText);
//document.getElementById("demo").innerHTML = obj.response[0].id + " " + obj.response[0].restaurant_id + " "+ obj.response[0].name;

}

var count = 0;
var html = "<table border='1|1'>";
for (var k in obj) {
if (obj.hasOwnProperty(k))
{ ++count; }
//document.getElementById("demo").innerHTML = obj.response[count].id + " " + obj.response[count].restaurant_id + " "+ obj.response[count].name;



html+="<tr>";
html+="<td>"+obj.response[count].id+"</td>";
html+="<td>"+obj.response[count].restaurant_id+"</td>";
html+="<td>"+obj.response[count].name+"</td>";
html+="</tr>";

}

html+="</table>";
$("div").html(html);
};
xhttp.open("GET", "the URL I deleted it when posting", true);
xhttp.send();


}
</script>

</body>
</html>





Thank you for helping.

Answer

When you do $('div').html() .... the div element doesn't exist in the page, so that nothing gets rendered

Comments