Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  191] [ 3]  / answers: 1 / hits: 41486  / 13 Years ago, tue, june 28, 2011, 12:00:00

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?


More From » php

 Answers
28

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.


[#91468] Sunday, June 26, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelynncherokeeg

Total Points: 697
Total Questions: 109
Total Answers: 104

Location: France
Member since Thu, Mar 18, 2021
3 Years ago
jaelynncherokeeg questions
Thu, May 27, 21, 00:00, 3 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Wed, Sep 18, 19, 00:00, 5 Years ago
;