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?
You can also parse an array for JavaScript with json_encode()
This also works for associative arrays:
Hey Please use above for your desired result. It is tested code.
Try this
PHP Code
In Javascript File
Output
I hope this will help you.
Encode as JSON before outputting.
Your PHP variables only live on the server. They are completely separate from the JavaScript variables on the client. The only mechanism for passing values from the server to the client is through the contents of the web page (or through specially requested behind-the-scenes web content through AJAX).
This means that to make your JavaScript receive PHP values, you have to write JavaScript with those values embedded inside of it. You must mix the PHP with the JavaScript at least a tiny bit to get the stuff that runs on the client to have any data from the server.
This is how all web server-side scripting works in all languages.
JavaScript simply cannot know what goes in your movies variable unless you stuff it full of values, in JavaScript.
I recommend you to @levu's answer to see a good way to get your PHP variable's values into JavaScript.
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: