I’m working on displaying API data from a third-party service in an HTML table but running into issues. The JSON response comes through fine when I log it to console, but nothing shows up in my table.
// This works and shows data in console
$.ajax(apiConfig).done(function(result){
console.log(result);
});
I can see the data in browser console but the table remains empty. Been stuck on this for a while now.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<table class="table" id="dataTable">
<thead>
<tr>
<th>Nation</th>
<th>Total Cases</th>
<th>Fatalities</th>
<th>Area</th>
<th>Recovered</th>
<th>Recent Deaths</th>
<th>Recent Cases</th>
<th>Critical</th>
<th>Per Million</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
$(document).ready(function(){
var apiConfig = {
"async": true,
"url": "api_endpoint",
"method": "GET",
"headers": {
"x-rapidapi-host": "host_name",
"x-rapidapi-key": "api_key_here"
}
};
$.getJSON(apiConfig, function(response){
$.each(response.statistics, function(index, item){
console.log(index);
console.log(item);
var row = "<tr>" + "<td>" + item.nation + "</td>" + "<td>" + item.total + "</td>" + "<td>" + item.fatalities + "</td>" + "<td>" + item.area + "</td>" + "<td>" + item.recovered_total + "</td>" + "<td>" + item.recent_deaths + "</td>" + "<td>" + item.recent_total + "</td>" + "<td>" + item.critical_cases + "</td>" + "<td>" + item.per_million + "</td>" + "</tr>";
$(row).appendTo("#dataTable tbody");
});
});
var row = "<tr>" + "<td>" + item.nation + "</td>" + "<td>" + item.total + "</td>" + "<td>" + item.fatalities + "</td>" + "<td>" + item.area + "</td>" + "<td>" + item.recovered_total + "</td>" + "<td>" + item.recent_deaths + "</td>" + "<td>" + item.recent_total + "</td>" + "<td>" + item.critical_cases + "</td>" + "<td>" + item.per_million + "</td>" + "</tr>";
$(row).appendTo("#dataTable tbody");
});
</script>
</body>
</html>
What could be preventing the table from populating with the API data?