2

I wrote a tool, that creates an array from a database (when the site is loaded) in php and would now like to use js functions to change the way this array is displayed in a table (different ranges, columns etc.).

How can I pass the php array to js, so I can use it in the js functions.

already tried this in the "script" section

   <?php
        $js_data = json_encode($data);
        echo"var data = ".$js_data.";\n";
    ?>
    function loadCompleteTable(){

        table += '<table>';

        for(var row in data){
            table += '<tr>';
            for(var col in data[row]){
                table += '<td>';
                table += data[row][col];
                table += '</td>';
            }
            table += '</tr>';
        }

        table += '</table>';
        document.getElementById("tablePlaceholder").innerHTML = table;
    }
4
  • 1
    So you tried and what happened? Commented Jul 5, 2019 at 7:42
  • nothing at all ... Commented Jul 5, 2019 at 7:45
  • 1
    Open developers console, check errors. Commented Jul 5, 2019 at 7:46
  • @u_mulder found the first mistake, forgot "var table = ''; " Commented Jul 5, 2019 at 7:51

2 Answers 2

1

You can pass an array from PHP to javascript like this:

var js_array = JSON.parse('<?php echo json_encode($php_array); ?>');

Or if you prefer:

echo "var js_array = JSON.parse('".json_encode($php_array)."');";

I know you could just use:

var js_array = <?php echo json_encode($php_array); ?>;

But i find it less reliable. Unfortunately, I can't find anything in the docs to prove what I am saying, but I had some troubles in the past, mostly SyntaxError, that was resolved by using JSON.parse instead of just echoing the array as javascript code.

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

Comments

0
    var data = <?php echo json_encode($data); ?>;

    function loadCompleteTable()
    {
           var table = '';
            table += '<table>';

            for(var row in data){
                table += '<tr>';
                for(var col in data[row]){
                    table += '<td>';
                    table += data[row][col];
                    table += '</td>';
                }
                table += '</tr>';
            }

            table += '</table>';
            document.getElementById("tablePlaceholder").innerHTML = table;
        }

Comments

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.