If I have created a variable in php, say $test, how can I set a variable in javascript, say var test, to be equal to it.
I have already tried var test = <?php $test ?>
9 Answers 9
I guess
var test = <?php echo json_encode($test) ?>
The naive way var test = '<?php echo ($test) ?>' will fail if $test contains quotes or newlines, let alone is not of the string type (e.g. array, object)
Comments
var test = '<?php echo $test; ?>'
1 Comment
$test="bug's".try like this :
var test = '<?php echo $test ?>';
Comments
var test = '<?php echo $test; ?>';
Or using shorthand echos, like this:
var test = '<?= test;?>';
2 Comments
$test="bug's".var test = <?php echo json_encode($test); ?>
Comments
You can use
<pre>
var test = '<?php echo $test?>';
</pre>
below the definition of $test.
Comments
Change
var test = <?php $test ?>
to
var test = <?php echo $test; ?>
Comments
You are missing two things:
var test = <?php $test ?>
1) Echo statement.
2) Single Quotes around PHP snipplet.
So, the corrected code should be:
var test = "<?php echo $test ?>";
Within your page where you want your PHP to output to type:
var MyJavascriptVariable = <?php echo $myPHPVariable; ?>
Advise NOT to use short tags () as this can be disabled by webhosts and may break your code.