0

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);

1 Answer 1

1

It seems like this let table = document.querySelector("table"); is returning null. Are you sure that the table element has been created at the time this query is run? Can you confirm that this returns null?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this answer helped me figured it out. I had to move script to make it work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.