After incorporating Bootstrap into my HTML file, I designed a basic table. To populate this table with data from an external JSON file upon clicking a button, I utilized XMLHttpRequest and JSON.parse successfully. However, I encountered difficulties when trying to insert the parsed data into the table using my append_json function in the script below.
Any assistance would be greatly appreciated :)
Below is the structure of my table:
<table class="table table-bordered table-hover" id="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Quantity</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th scope="row">2</th>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th scope="row">3</th>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
This is the current status of my JavaScript:
<script>
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
btn1.addEventListener("click", function (){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = request.response;
var data = JSON.parse(json);
append_json(data);
}
};
request.open("GET", "products.json", true);
request.send();
})
function append_json(data) {}
</script>
Here is the excerpt from the JSON file:
{
"products": [
{
"id": "1",
"name": "Apples",
"hasQuantity": "100",
"price": "3.10"
},
{
"id": "2",
"name": "Pears",
"hasQuantity": "50",
"price": "2.50"
},
{
"id": "3",
"name": "Bananas",
"hasQuantity": "100",
"price": "2.01"
},
{
"id": "4",
"name": "Tangerines",
"hasQuantity": "150",
"price": "3.41"
},
{
"id": "5",
"name": "Plums",
"hasQuantity": "50",
"price": "4.11"
},
{
"id": "6",
"name": "Straberries",
"hasQuantity": "50",
"price": "3.07"
}
,
{
"id": "7",
"name": "Watermelon",
"hasQuantity": "20",
"price": "2.19"
}
]
}