How to pass PHP array parameter to Javascript Function?

Son of Man picture Son of Man · Jun 28, 2011 · Viewed 38.8k times · Source

index.php

<script type="text/javascript" src="javascript.js"> </script>
<?php
 $movies = array("Bloodsport", "Kickboxer", "Cyborg", "Timecop", "Universal Soldier", "In Hell", "The Quest");
?>

<input type="submit" value="Test Javascript" onclick="showMovies(<?php echo $movies; ?>);" />


javascript.js

function showMovies(movies) {
 alert(movies.length);

 return false;
}

I am new to programming so Im having hard time fixing this one which is obviously simple for you guys.

When I hit the submit button it says the that the array size is 1 which I think should be 7. How could this be?

Answer

Florian picture Florian · Jun 28, 2011
<input type="submit" value="Test Javascript" onclick='showMovies(<?php echo json_encode($movies); ?>);' />

Notice the json_encode, which encodes objects or arrays for Javascript (JSON stands for JavaScript Object Notation) and also notice the ' instead of ", because JSON uses ".

Although, this soulution would be better:

<script type="text/javascript">
    document.getElementByID('submitButton').onclick = function() {
        var movies = <?php echo json_encode($movies); ?>;
        showMovies(movies);
    };
</script>
...
<input type="submit" value="Test JavaScript" id="submitButton">