Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass PHP array parameter to Javascript Function?

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?

like image 875
Son of Man Avatar asked Dec 01 '22 02:12

Son of Man


1 Answers

<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">
like image 145
Florian Avatar answered Dec 03 '22 14:12

Florian