I've file with extension php. In here I've read information from Database. And I need to pass this data(associate array) to js, which also include in this php 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);
?>
<script>
const arr = JSON.parse( '<?php echo json_encode($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"
}
...
console.log(arr);
Uncaught SyntaxError: missing ) after argument list
Conclusion: On the part of php all good. But when we try to parse this array in js object in js part - We see strange Error.
Questions:
- How to load data(For example, associate array, in my case) from php to js. When php and js are in the same extension file(php).
- How to load data(For example, associate array, in my case) from php to js. When php and js are in different files. For example We've 1 extension file php, where we've implement logic(With DB, in my case). And we need to import this data to extension file js.