I want to load a php array from a php file into a javascript array in a javascript file.
Originally, I was just doing var wordsArray = <?php echo json_encode($wordsArray) ?>; in a php file to get it, but now I've put all Javascript functions a .js file, which can't run PHP. Is there a $.get function that can return a php array?
something like:
JavaScript: Utilities.js file
$.get("php/Quests.php", {},
function(returned_data) {
var wordsArray = returned_data;
}
);
PHP: Quests.php file
<?php
include 'DbConnect.php';
$sql = $mysqli->query(
"SELECT t.*, v.*
FROM task t
INNER JOIN vocabtask vt ON (t.id = vt.taskid)
INNER JOIN vocab v ON (v.id = vt.vocabid)
WHERE vt.taskid = 1");
$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
$wordsArray[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
//return php array as json_encoded to js file through get function
echo json_encode($wordsArray);
?>
EDIT:
Or instead of the $.get, I tried doing this on the PHP file:
echo "<script type='text/javascript'> var wordsArray =json_encode($wordsArray); </script>";
Then in JS do:
alert(wordsArray[1]);
Would something like this work?