You can pass the PHP variable to JavaScript using the php tags which is included into the js functions.
Necessary Checks:
- Ensure that you place the
;
at the end of the line.
- You need to
echo
the variable in order to set the value..
Example:
<?php
$date= date();
?>
<script>
document.write(<?php echo $date; ?>);
</script>
The same trick can be applied to other data types (e.g. integers, arrays, objects, etc.). The following passes an entire array from PHP to JavaScript:
Using json_encode()
, you'll always get a properly formatted JavaScript object.
$shirt = array(
'color' => 'blue',
'number' => 23,
'size' => 'XL'
);
echo '<script>';
echo 'var shirt = ' . json_encode($shirt) . ';';
echo '</script>';
The output looks like this:
<script>var shirt = {"color":"blue","number":23,"size":"XL"}</script>
To pass scalar data held in a PHP variable ($val)
to a JavaScript variable, place the following in a JavaScript segment:
var val = "<?php echo $val ?>";
Notice the quotes around the PHP tags. This will result in a string value in JavaScript which you may need to convert for use in your scripts. If the PHP value is numeric, you don't need to include the quotes.
Here we demonstrate with boolean, numeric, and string values assigned to PHP variables:
<?php
$bool = false;
$num = 3 + 4;
$str = "A string here";
?>
You could output them into JavaScript with the following:
<script type="text/javascript">
// boolean outputs "" if false, "1" if true
var bool = "<?php echo $bool ?>";
// numeric value, both with and without quotes
var num = <?php echo $num ?>; // 7
var str_num = "<?php echo $num ?>"; // "7" (a string)
var str = "<?php echo $str ?>"; // "A string here"
</script>
There are some conditions under which strings that are valid in PHP may generate errors in JavaScript when output using this approach. The PHP json_encode function can be used to resolve these problems as well as to preserve data type of booleans and numbers.