0

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?

4
  • Can't you just echo out the json in a js var when the page loads and have the external js use it as any other local var? Commented Jan 17, 2014 at 3:23
  • @ZombieBunnies can you give an example? Commented Jan 17, 2014 at 3:28
  • Have you actually tried the code you've written here? Commented Jan 17, 2014 at 3:31
  • @winterblood yes, why do you ask? please see edit. Commented Jan 17, 2014 at 3:34

2 Answers 2

1
try this.

echo "<script type='text/javascript'> var wordsArray = " . json_encode($wordsArray) . ";
    //this will output the contents of wordsArray into the console
     console.dir(wordsArray);

     // check the console. f12 or ctrl+shift+k
 </script>";
Sign up to request clarification or add additional context in comments.

6 Comments

in the JS file... alert(wordsArray[1]); outputs undefined
console.dir(wordsArray); what do you see in your console? or view the source to see what's being returned by json_encode( $wordsArray)
in my js file, I put console.dir(wordsArray); which shows object.
yep. inside the console window - f12 in chrome, ctrl+shift+k in firefox
Right, the console.dir output is Object
|
1

If your PHP returns a JSON-encoded data, you can parse it in your Javascript using JSON.parse:

function(returned_data) {
  returned_data = JSON.parse(returned_data);
}

returned_data will now be a JSON object instead of the original string.

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.