Trying to populate an HTML table with data from an external JSON file is proving to be a challenge. Despite making an AJAX request using pure JavaScript, nothing happens when the "Test" button is clicked. Take a look at the JSON data:
{ "row":[
{
"ID" : "2",
"FirstName" : "John",
"LastName" : "Test",
"DOB": "03-12-1959",
"Gender":"M"
},
{
"ID" : "3",
"FirstName" : "Helen",
"LastName" : "Test",
"DOB": "03-12-1959",
"Gender":"M"
}
]
}
An excerpt from the HTML code:
<button onclick="loadJSON()">Test</button>
<table class="test-table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="data">
<tr>
<td><label for="row1"></label>123</td>
<td>John</td>
<td>Doe</td>
<td>02-15-1982</td>
<td>M</td>
</tr>
</tbody>
</table>
The JavaScript part of the code:
function loadJSON(){
var data_file = "test.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
var jsonObj = JSON.parse(http_request.responseText);
var tr, td;
var tbody = document.getElementById("data");
// loop through data source
for (var i=0; i<jsonObj.row.length; i++) {
tr = tbody.insertRow(tbody.rows.length);
td = tr.insertCell(tr.cells.length);
td.setAttribute("align", "center");
td.innerHTML = jsonObj.row[i].ID;
td = tr.insertCell(tr.cells.length);
td.innerHTML = jsonObj.row[i].FirstName;
td = tr.insertCell(tr.cells.length);
td.innerHTML = jsonObj.row[i].LastName;
td = tr.insertCell(tr.cells.length);
td.innerHTML = jsonObj.row[i].DOB;
td = tr.insertCell(tr.cells.length);
td.innerHTML = jsonObj.row[i].Gender;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
If you have any insights on what could be going wrong or how to fix it, your help would be greatly appreciated.