4

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?

Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
Son of Man
  • 117
  • 1
  • 3
  • 10

7 Answers7

9
<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">
Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
Florian
  • 3,015
  • 1
  • 24
  • 36
  • You mean I have to mix my javascript with my php code??? I want to separate them... Pls help I am a beginner... – Son of Man Jun 28 '11 at 06:00
  • notice the ' instead of ", because JSON uses " >> This line works for me ...thanks – Atul Jun 07 '19 at 05:59
3

Try this

PHP Code

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

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

In Javascript File

function showMovies(movies) {
  movies = movies.split(",");
  alert(movies.length);
 return false;
}

Output

7

I hope this will help you.

Gaurav Porwal
  • 423
  • 2
  • 6
2

Encode as JSON before outputting.

<input type="submit" value="Test Javascript" onclick="showMovies(<?php echo json_encode($movies); ?>);" />
Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283
  • what is json??? Is that something built-in in native javascript or is that a plugin I need to install? – Son of Man Jun 28 '11 at 05:49
  • Read documentation first, *then* come back with a sensible question. – Ignacio Vazquez-Abrams Jun 28 '11 at 05:50
  • 3
    Wow, Ignacio, that was rude. @Son of Man: You can do a quick search on Google for "JSON" to get a good idea of what JSON is. – Joel Jun 28 '11 at 05:51
  • 2
    Rude is expecting someone else to do all the research for you. – Ignacio Vazquez-Abrams Jun 28 '11 at 05:52
  • 3
    Rude is treating honest ignorance as maliciousness. – ErikE Jun 28 '11 at 05:54
  • @Son: At that point you need to fix your quotes as mentioned in the other answer. And don't trust Firebug to show you what your page really looks like. – Ignacio Vazquez-Abrams Jun 28 '11 at 05:55
  • @ErikE: Feel free to guide the asker to the Getting Answers page then. – Ignacio Vazquez-Abrams Jun 28 '11 at 05:56
  • I doubt a sterile page on JSON would do the OP any good. He has a conceptual hole he is not aware of called server/client. He doesn't know enough to see this hole or even ask how to fix it. You with your godlike 100k rep should be able to figure this out as well as I did. So, are you going to send him to your favorite tutorial on the subject or just mock? He's likely to land at w3schools if you don't help him. – ErikE Jun 28 '11 at 06:01
  • Printing an array in PHP results in `"array"`. Ain't nothing server/client in that. – Ignacio Vazquez-Abrams Jun 28 '11 at 06:03
  • So you don't grasp his conceptual problem? Bizarre! Maybe you should do a search instead of expecting me to explain it to you. Seriously, though, don't be Evil. @Son start with [this tutorial](http://www.webdevelopersnotes.com/basics/client_server_architecture.php3). – ErikE Jun 28 '11 at 06:09
  • It's an output problem. He doesn't (didn't) know how to encode something in one language in a manner that the other language would understand. – Ignacio Vazquez-Abrams Jun 28 '11 at 06:10
  • 1
    Read my answer. It goes deeper than that. – ErikE Jun 28 '11 at 06:17
  • @Ignacio By the way, you are absolutely correct that in the given question the OP **was** almost on track to spit out the `movies` PHP value and just needed to know how to convert it to an array. My apologies for arguing so vociferously when you were correct and I was wrong. Interestingly enough, the OP still marked my answer as the selected one... not sure why, but maybe I was on to something a bit elusive. Again, sorry about continuing to argue even though I was wrong. – ErikE Jun 28 '11 at 19:03
1

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.

Community
  • 1
  • 1
ErikE
  • 43,574
  • 19
  • 137
  • 181
  • It is perfectly valid to generate JavaScript code via PHP, which is what is being done in the question. – Ignacio Vazquez-Abrams Jun 28 '11 at 06:21
  • Of course. The JS can be in a separate file or in the HTML returned from the PHP script. But the actual values have to be encoded in JS in some place where JavaScript is expected, like an event attribute or a script tag. You can't actually put JavaScript in PHP or vice versa because neither would execute. You have to switch back and forth appropriately. – ErikE Jun 28 '11 at 06:25
  • @Ignacio if you really thought you had to explain to me that you "can generate JavaScript via PHP" then you are really not getting it! Trust me, the way I explained it is what the OP needs. @son do you have any input for us? – ErikE Jun 28 '11 at 06:30
  • Where does the value of the variable ever change? – Ignacio Vazquez-Abrams Jun 28 '11 at 06:37
  • @Ignacio what are you talking about? If you want to change a variable's value, do so. If you want the client to change data on the server, GET or POST and read the data. – ErikE Jun 28 '11 at 15:03
1
<?php
  $movies = array("Bloodsport", "Kickboxer", "Cyborg", "Timecop", "Universal Soldier", "In Hell", "The Quest");
  $str=implode(",",$movies);
?>
<script type="text/javascript" >
  var arr=new Array();
  var str="<?php echo $str; ?>";
  arr=str.split(',');
  //alert(arr.toSource());
  function showMovies(movies) {
    alert(movies.length);
    return false;
  }
</script>

<input type="submit" value="Test Javascript" onclick="showMovies(arr)" >

Hey Please use above for your desired result. It is tested code.

Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
1

You can pass array in js by json_encode() php function.. json_encode() will make array into string. you can get array back by saprating that string in js.

Rukmi Patel
  • 2,545
  • 8
  • 26
  • 41
0

You can also parse an array for JavaScript with json_encode()

$array = array('1','a','b');

echo '<script type="text/javascript">';
echo 'var x = ' . json_encode($array) . ';';
echo '</script>';

This also works for associative arrays:

$array = array("x" => '1',"y" => 'a',"z" => 'b');
echo '<script type="text/javascript">';
echo 'var x = ' . json_encode($array) . ';';
echo '</script>';
5442224
  • 73
  • 6