I have a variable from php in js like:
var myData = <?php echo json_encode($json_array) ?>;
and I am trying to pass this obj's keys and values to a table generated by javascript. myData format in console is pasted below. and when I pass it to the table, I get a error saying it can not read myData. I know I can pass the data as an object but somehow this is different since I brought in from php and is not reading it like a regular json file. Error I get is: Uncaught TypeError: Cannot read property 'insertRow' of null at generateTable?
what myData outputs in the console:
0:
Carat: "0.70"
Clarity: "VVS2"
Color: "D"
Cut: "Very Good"
Polish: "Fair"
Price: "2806"
Product ID: "17"
Product Name: "0.7 Carat Cushion Diamond"
Report: "IGI"
Shape: "Cushion"
Symmetry: "Ideal"
purl: "http://klaussongs.com/product/0-7-carat-cushion-diamond/"
__proto__: Object
1: {Product ID: "19", Product Name: "0.9 Carat Round Diamond", Carat: "0.90", Clarity: "VS2", Shape: "Round", …}
2: {Product ID: "21", Product Name: "1 Carat Radiant Diamond", Carat: "1.00", Clarity: "SI1", Shape: "Radiant", …}
3: {Product ID: "23", Product Name: "1.15 Carat Princess Diamond", Carat: "1.15", Clarity: "IF", Shape: "Princess", …}
functions to generate the table from myData:
function generateTableHead(table, data) {
let thead = table.createTHead();
let row = thead.insertRow();
for (let key of data) {
let th = document.createElement("th");
let text = document.createTextNode(key);
th.appendChild(text);
row.appendChild(th);
}
}
function generateTable(table, data) {
for (let element of data) {
let row = table.insertRow();
for (key in element) {
let cell = row.insertCell();
let text = document.createTextNode(element[key]);
cell.appendChild(text);
}
}
}
let table = document.querySelector("table");
let data = Object.keys(myData);
// generate cells from values
generateTable(table, myData);
// create heading from keys
generateTableHead(table, data);