简体   繁体   中英

How to display JSON data in a datatable using JavaScript - PHP code working but not sure how to convert to JavaScript

JSON Data not displaying as a header with column titles ColTitle, row for "Beginning Balance" and then row with ColData.

PHP code is working fine but its a new JavaScript based app I am working on.

This is the JavaScript code where I tried to get the table to appear

Mycontacts is actually a live JSON response but for the purpose of testing I put it on here.

<script type="text/javascript">
var myContacts = [
{
  "Header": {
    "Time": "2019-05-10T10:38:08-07:00",
    "ReportName": "GeneralLedger",
    "ReportBasis": "Accrual",
    "StartPeriod": "2019-02-01",
    "EndPeriod": "2019-02-01",
    "Currency": "GBP",
    "Option": [
      {
        "Name": "NoReportData",
        "Value": "false"
      }
    ]
  },
  "Columns": {
    "Column": [
      {
        "ColTitle": "Date",
        "ColType": "Date",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "tx_date"
          }
        ]
      },
      {
        "ColTitle": "Transaction Type",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "txn_type"
          }
        ]
      },
      {
        "ColTitle": "No.",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "doc_num"
          }
        ]
      },
      {
        "ColTitle": "Name",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "name"
          }
        ]
      },
      {
        "ColTitle": "Customer",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "cust_name"
          }
        ]
      },
      {
        "ColTitle": "Supplier",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "vend_name"
          }
        ]
      },
      {
        "ColTitle": "Employee",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "emp_name"
          }
        ]
      },
      {
        "ColTitle": "Class",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "klass_name"
          }
        ]
      },
      {
        "ColTitle": "Product/Service",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "item_name"
          }
        ]
      },
      {
        "ColTitle": "Memo/Description",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "memo"
          }
        ]
      },
      {
        "ColTitle": "Account",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "account_name"
          }
        ]
      },
      {
        "ColTitle": "Debit",
        "ColType": "Money",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "debt_home_amt"
          }
        ]
      },
      {
        "ColTitle": "Credit",
        "ColType": "Money",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "credit_home_amt"
          }
        ]
      },
      {
        "ColTitle": "Amount",
        "ColType": "Money",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "subt_nat_home_amount"
          }
        ]
      }
    ]
  },
  "Rows": {
    "Row": [
      {
        "Header": {
          "ColData": [
            {
              "value": "1000 Bootcamp AMEX Acc",
              "id": "134"
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            }
          ]
        },
        "Rows": {
          "Row": [
            {
              "ColData": [
                {
                  "value": "Beginning Balance"
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                }
              ],
              "type": "Data"
            }
          ]
        },
        "Summary": {
          "ColData": [
            {
              "value": "Total for 1000 Bootcamp AMEX Acc"
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            }
          ]
        },
        "type": "Section"
      },
      }
    ]
  }

    ];

function generateDynamicTable(){

        var noOfContacts = myContacts.length;

        if(noOfContacts>0){


            // CREATE DYNAMIC TABLE.
            var table = document.createElement("table");
            table.style.width = '50%';
            table.setAttribute('border', '1');
            table.setAttribute('cellspacing', '0');
            table.setAttribute('cellpadding', '5');

            // retrieve column header ('Name', 'Email', and 'Mobile')

            var col = []; // define an empty array
            for (var i = 0; i < noOfContacts; i++) {
                for (var key in myContacts[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }

            // CREATE TABLE HEAD .
            var tHead = document.createElement("thead");    


            // CREATE ROW FOR TABLE HEAD .
            var hRow = document.createElement("tr");

            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < col.length; i++) {
                    var th = document.createElement("th");
                    th.innerHTML = col[i];
                    hRow.appendChild(th);
            }
            tHead.appendChild(hRow);
            table.appendChild(tHead);

            // CREATE TABLE BODY .
            var tBody = document.createElement("tbody");    

            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < noOfContacts; i++) {

                    var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD .


                    for (var j = 0; j < col.length; j++) {
                        var td = document.createElement("td");
                        td.innerHTML = myContacts[i][col[j]];
                        bRow.appendChild(td);
                    }
                    tBody.appendChild(bRow)

            }
            table.appendChild(tBody);   


            // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
            var divContainer = document.getElementById("myContacts");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);

        }   
    }

</script>

So in the above example I expected the first row of the table to have column headings, then a row for ColData - "value": "1000 Bootcamp AMEX Acc", then a row for ColData - "value": "Beginning Balance", then finally a row for ColData - "value": "Total for 1000 Bootcamp AMEX Acc".

This is just a sample - my live data is much larger than this so needed a loop for each of the Columns, Rows, Rows, Summary.

The below PHP coding seemed to work fine when using an SDK

echo "Report Name - " . $report['Header']['ReportName'];
            echo "<br>";
            echo "For Date: " . $report['Header']['DateMacro'] . " (".$report['Header']['StartPeriod']." - ".$report['Header']['EndPeriod'].")";
            echo "<br>";            
            echo "Currency: " . $report['Header']['Currency'];
            echo "<br>";
            echo "<hr>";
            echo '<table><thead>';

            $NumberColumns = array();
            echo '<th></th>';
            // echo '<th>Account Name</th>';
            $NumberColumns[]= ''; // get a foreach for number of cols if we need it
            foreach ($report['Columns']['Column'] as $HeadKey => $columns) {
                $NumberColumns[]= '';
                echo '<th>';
                echo $columns['ColTitle'];
                if($columns['ColTitle'] == 'Credit') {
                    $CreditKey = $HeadKey;
                }
                echo '</th>';
            }
            echo '</thead><tbody>';


            foreach($report['Rows']['Row'] as $MainRow) {
                echo '<tr style="background-color:lightgrey">';
                echo '<td><h3>' . $MainRow['Header']['ColData']['0']['value'] . '</h3></td>'; // SPLITTER ROW - SUMMARY
                foreach ($MainRow['Summary']['ColData'] as $MainRowData) {
                    if ($counter++ == 0) continue;
                    echo '<td>' . $MainRowData['value'] . '</td>';
                }
                unset($counter);
                echo '</tr>';
                foreach($MainRow['Rows']['Row'] as $DetailRow) {
                    echo '<td></td>';
                    echo '</td>';
                    foreach($DetailRow['ColData'] as $DetailKey => $CellDetail) {
                        $CellContents = $CellDetail['value'];
                        if($DetailKey == $CreditKey) {
                            $CellContents = abs($CellDetail['value']) * -1;
                        }
                        echo '<td>' . $CellContents . '</td>';
                    }
                    echo '</tr>';
                }
            } // Main ROW
            echo '</tbody></table>';

  1. Some brackets got mixed up or were missing in myContacts Rows object. See comments in code sample.

  2. The div with the id "myContacts" where you want to render your table, was not defined in your html markup. Here is the part where you call it:

var divContainer = document.getElementById("myContacts");
  1. you defined your rendering function but forgot to call it initially:
generateDynamicTable() // TODO: call was missing at the end of your script

ADDITIONAL: So you can use something like this for debugging purpose to get the right value :)

td.innerHTML = myContacts[i][col[j]]; // instead of this
td.innerHTML = JSON.stringify(myContacts[ i ][ col[ j ] ]); // use this

Hope I could help :)

Fiddle: https://jsfiddle.net/0xsf8qmg/

Here the Code:

 var myContacts = [ { "Header": { "Time": "2019-05-10T10:38:08-07:00", "ReportName": "GeneralLedger", "ReportBasis": "Accrual", "StartPeriod": "2019-02-01", "EndPeriod": "2019-02-01", "Currency": "GBP", "Option": [ { "Name": "NoReportData", "Value": "false" } ] }, "Columns": { "Column": [ { "ColTitle": "Date", "ColType": "Date", "MetaData": [ { "Name": "ColKey", "Value": "tx_date" } ] }, { "ColTitle": "Transaction Type", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "txn_type" } ] }, { "ColTitle": "No.", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "doc_num" } ] }, { "ColTitle": "Name", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "name" } ] }, { "ColTitle": "Customer", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "cust_name" } ] }, { "ColTitle": "Supplier", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "vend_name" } ] }, { "ColTitle": "Employee", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "emp_name" } ] }, { "ColTitle": "Class", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "klass_name" } ] }, { "ColTitle": "Product/Service", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "item_name" } ] }, { "ColTitle": "Memo/Description", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "memo" } ] }, { "ColTitle": "Account", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "account_name" } ] }, { "ColTitle": "Debit", "ColType": "Money", "MetaData": [ { "Name": "ColKey", "Value": "debt_home_amt" } ] }, { "ColTitle": "Credit", "ColType": "Money", "MetaData": [ { "Name": "ColKey", "Value": "credit_home_amt" } ] }, { "ColTitle": "Amount", "ColType": "Money", "MetaData": [ { "Name": "ColKey", "Value": "subt_nat_home_amount" } ] } ] }, "Rows": { "Row": [ { "Header": { "ColData": [ { "value": "1000 Bootcamp AMEX Acc", "id": "134" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" } ] }, "Rows": { "Row": [ { "ColData": [ { "value": "Beginning Balance" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" } ], "type": "Data" } ] }, "Summary": { "ColData": [ { "value": "Total for 1000 Bootcamp AMEX Acc" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" } ] }, "type": "Section" }, ] // TODO: this one was missing } // ] TODO: this one is accidentally } ]; function generateDynamicTable(){ var noOfContacts = myContacts.length; if(noOfContacts>0){ // CREATE DYNAMIC TABLE. var table = document.createElement("table"); table.style.width = '50%'; table.setAttribute('border', '1'); table.setAttribute('cellspacing', '0'); table.setAttribute('cellpadding', '5'); // retrieve column header ('Name', 'Email', and 'Mobile') var col = []; // define an empty array for (var i = 0; i < noOfContacts; i++) { for (var key in myContacts[i]) { if (col.indexOf(key) === -1) { col.push(key); } } } // CREATE TABLE HEAD . var tHead = document.createElement("thead"); // CREATE ROW FOR TABLE HEAD . var hRow = document.createElement("tr"); // ADD COLUMN HEADER TO ROW OF TABLE HEAD. for (var i = 0; i < col.length; i++) { var th = document.createElement("th"); th.innerHTML = col[i]; hRow.appendChild(th); } tHead.appendChild(hRow); table.appendChild(tHead); // CREATE TABLE BODY . var tBody = document.createElement("tbody"); // ADD COLUMN HEADER TO ROW OF TABLE HEAD. for (var i = 0; i < noOfContacts; i++) { var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD . for (var j = 0; j < col.length; j++) { var td = document.createElement("td"); // td.innerHTML = JSON.stringify(myContacts[ i ][ col[ j ] ]); // TODO: for debugging purpose instead of the following line td.innerHTML = myContacts[i][col[j]]; bRow.appendChild(td); } tBody.appendChild(bRow) } table.appendChild(tBody); // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER. var divContainer = document.getElementById("myContacts"); divContainer.innerHTML = ""; divContainer.appendChild(table); } } generateDynamicTable() // TODO: call was missing 
 <div id="myContacts"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM