Create HTML table from JavaScript object

jo15765
 
on Jul 07, 2022 07:46 AM
Sample_553799.zip
466 Views

I am attempting to create a table with JSON data, and my code runs error free, but when the code completes, no table is created on the page.

 api Data returns data in this format

{"Product":"RST-9042","Quantity":121}{"Product":"LMN-1017-KN","Quantity":"0"}{"Product":"YZH-2117","Quantity":13}

What piece am I missing here?

btnSubmit.onclick = async function() {
    const customerSelect = document.getElementById('customers');
    const selectedCustomer = customerSelect.selectedOptions[0].value;
    const intCustomer = parseInt(selectedCustomer);
    if ([1, 2, 3].includes(Number(intCustomer))) {
         await fetch(‘Ce.php?customer=' + intCustomer)
            .then(async (result) => {
                const apiData = result;
                //console.log(wooData);
                await generateTable(apiData);
                if (result.status != 200) {
                    throw new Error("Bad Server Response");
                }
                return result.text();
            })
            .then((response) => {
                console.log(response);
            })
            .catch((error) => {
                console.log(error);
            });
}
async function generateTable(apiData) {
    //Create a HTML Table element.
    const table = document.createElement("TABLE");
    table.border = "1";

    //Get the count of columns.
    const columnCount = apiData;

    //Add the header row.
    let row = table.insertRow(-1);
    for (const i = 0; i < columnCount; i++) {
        const headerCell = document.createElement("TH");
        headerCell.innerHTML = apiData[i];
        row.appendChild(headerCell);
    }

    //Add the data rows.
    for (const i = 1; i < apiData.length; i++) {
        row = table.insertRow(-1);
        for (const j = 0; j < columnCount; j++) {
            const cell = row.insertCell(-1);
            cell.innerHTML = apiData[i][j];
        }
    }

    const dvTable = document.getElementById("dvData");
    dvTable.innerHTML = "";
    dvTable.appendChild(table);
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 07, 2022 11:31 PM

Hi jo15765,

Your apiData doesn't returns Array. It returns json data with improper format.

So you need to first format the string to proper Json string and the process the Json string to create the table.

Refer below code.

<input type="button" value="Generate Table" onclick="GenerateTable()" />
<hr />
<div id="dvTable"></div>
<script type="text/javascript">
    function GenerateTable() {
        var jsonString = '{"Product":"RST-9042","Quantity":121}{"Product":"LMN-1017-KN","Quantity":"0"}{"Product":"YZH-2117","Quantity":13}';
        var products = JSON.parse('[' + jsonString.replace(/}{/g, '},{') + ']');

        //Create a HTML Table element.
        var table = document.createElement("TABLE");
        table.border = "1";

        var columns = [];
        for (var i = 0; i < products.length; i++) {
            for (var key in products[i]) {
                if (columns.indexOf(key) == -1) {
                    columns.push(key);
                }
            }
        }

        //Add the header row.
        var row = table.insertRow(-1);
        for (var i = 0; i < columns.length; i++) {
            var headerCell = document.createElement("TH");
            headerCell.innerHTML = columns[i];
            row.appendChild(headerCell);
        }

        //Add the data rows.
        for (var i = 0; i < products.length; i++) {
            row = table.insertRow(-1);
            for (var j = 0; j < columns.length; j++) {
                var cell = row.insertCell(-1);
                cell.innerHTML = products[i][columns[j]];
            }
        }

        var dvTable = document.getElementById("dvTable");
        dvTable.innerHTML = "";
        dvTable.appendChild(table);
    }
</script>

Demo