There is a file with the php extension, it implements the collection of information from the database. It is necessary to transfer this data (associative array) to js, which is also connected to this file.
<?php require('../db.php'); function var_dump1($arr) { echo '<pre>'; var_dump($arr); echo '</pre>'; } // load data from Database $query = R::getAll('SELECT * from questions'); var_dump1($query); $query = json_encode($query); var_dump1($query); ?> <script> const arr = '<?=$query; ?>'; console.log(arr); </script> Outputs:
var_dump1 ($ query);
array(5) { [0]=> array(7) { ["id"]=> string(1) "1" ["question"]=> string(143) "The ______________ of a table is used to modify the design of a table, like modifying the name of a field or changing the data type of a field." ["answer1"]=> string(14) "Datasheet View" ["answer2"]=> string(11) "Desisn View" ["answer3"]=> string(10) "Table View" ["answer4"]=> string(11) "Wizard View" ["true_answer"]=> string(1) "1" } [1]=> array(7) { ["id"]=> string(1) "2" ["question"]=> string(83) "You can select multiple fields of a table in design view by using the ________ key." ["answer1"]=> string(3) "Alt" ["answer2"]=> string(8) "Spacebar" ["answer3"]=> string(5) "Shift" ["answer4"]=> string(4) "Ctrl" ["true_answer"]=> string(1) "3" } ... var_dump1 ($ query);
string(1302) "[{"id":"1","question":"The ______________ of a table is used to modify the design of a table, like modifying the name of a field or changing the data type of a field.","answer1":"Datasheet View","answer2":"Desisn View","answer3":"Table View","answer4":"Wizard View","true_answer":"... console.log (arr);
Uncaught SyntaxError: Unexpected identifier Conclusion:
From the above, it is clear that on the php side, the data is normally loaded from the database, then it is also correctly converted into JSON, but when you try to accept this JSON and convert to js, the object throws out an error.
Questions:
- How to load data (for example, an associative array, as in my case) from php to js, when php and js are in the same file, with php extension
- How to load data (for example, an associative array, as in my case) from php to js, if php and js are in different files. For example, there is a file with the php extension, where there is only logic, and from there you need to transfer the data to another file, with the js extension.
$query = json_encode($query);and in js, I tried as you say to doconst arr = '<?=$query; ?>'; const arr_obj = JSON.parse(arr);const arr = '<?=$query; ?>'; const arr_obj = JSON.parse(arr);but nothing works, just gives an error - helsereet