Converting JSON response from API into HTML table format not working

I’m having trouble displaying data from an API response in an HTML table. The console shows the JSON data correctly, but nothing appears in my table on the webpage.

// API configuration
const apiConfig = {
    "async": true,
    "crossDomain": true,
    "url": "api_endpoint_url",
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "host_name",
        "x-rapidapi-key": "api_key_here"
    }
};

// Fetch and display data
$.getJSON(apiConfig, function(result){
    $.each(result.statistics, function(index, item){
        console.log(index);
        console.log(item);
        
        var tableRow = "<tr>" + "<td>" + item.location + "</td>" + "<td>" + item.confirmed + "</td>" + "<td>" + item.fatalities + "</td>" + "<td>" + item.area + "</td>" + "<td>" + item.recovered_total + "</td>" + "<td>" + item.recent_deaths + "</td>" + "<td>" + item.recent_cases + "</td>" + "<td>" + item.critical_cases + "</td>" + "<td>" + item.cases_per_million + "</td>" + "</tr>";
        $(tableRow).appendTo("#dataTable tbody");
    });
});

The console.log shows the data perfectly but the HTML table remains empty. What could be wrong with my approach?

wrap ur code in $(document).ready() - ur script’s probably running b4 the table loads. also, make sure ur table has id=‘dataTable’ and there’s a tbody in the HTML.

The problem’s likely with $.getJSON - it doesn’t handle configuration objects with headers properly. Switch to $.ajax instead:

$.ajax(apiConfig).done(function(result) {
    $.each(result.statistics, function(index, item) {
        var tableRow = "<tr><td>" + item.location + "</td><td>" + item.confirmed + "</td><td>" + item.fatalities + "</td><td>" + item.area + "</td><td>" + item.recovered_total + "</td><td>" + item.recent_deaths + "</td><td>" + item.recent_cases + "</td><td>" + item.critical_cases + "</td><td>" + item.cases_per_million + "</td></tr>";
        $("#dataTable tbody").append(tableRow);
    });
});

Also watch out for undefined or null properties in your items - they’ll break the string concatenation. Throw in some error handling to make sure your AJAX request actually works.

Check your HTML structure first - I had the same problem when my table wasn’t formed right. You need opening and closing tbody tags, not just a self-closing one. CORS errors also bit me since they fail silently. Open your network tab and make sure the API request actually returns 200. Sometimes console shows cached data while the real request bombs. Try logging the whole result object before you access result.statistics - the API might’ve changed format or added wrapper objects you’re missing.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.