It is exceedingly easy to get a variable from PHP to javascript
:
<script language="Javascript">
jsvariable = "<?php echo $phpvariable; ?>";
</script>
Remember, though, if the PHP variable is a string with line breaks, you need to escape that string, since a javascript string can only be on one line.
example:
<?php
$phpvariable1 = "Hello, this string has\n two lines";
$phpvariable2 = "This one
has
3 lines";
$phpvariable3 = "Hello, this string will \\n escape line breaks \\n in PHP so that Javascript can handle it.";
$phpvariable4 = addcslashes($phpvariable1, "\n\r");
?>
<html>
<head>
<script language="Javascript">
jsvariable1 = "<?php echo $phpvariable1; ?>";
jsvariable2 = "<?php echo $phpvariable2; ?>";
jsvariable3 = "<?php echo $phpvariable3; ?>";
jsvariable4 = "<?php echo $phpvariable4; ?>";
</script>
</head>
</html>
The above script would work for jsvariable3 and jsvariable4, but not for 1 and 2. The output to the browser would be:
<html>
<head>
<script language="Javascript">
jsvariable1 = "Hello, this string has
two lines";
jsvariable2 = "This one
has
3 lines";
jsvariable3 = "Hello, this string will \n escape line breaks \n in PHP so that Javascript can handle it.";
jsvariable4 = "Hello, this string has\n two lines";
</script>
</head>
</html>
If you want a more sophisticated way to send variables back and forth between Javascript and PHP, you could take a look at the
WDDX functions, which are
supported by PHP, and which provide a way to serialize variables and arrays from one environment to another. Using WDDX, you should be able to transport a whole array from PHP to Javascript and vice-versa.