Reputation: 1
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 ?>
Upvotes: 0
Views: 118
Reputation: 49
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.
Upvotes: 0
Reputation: 23958
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 ?>";
Upvotes: 0
Reputation: 8809
Change
var test = <?php $test ?>
to
var test = <?php echo $test; ?>
Upvotes: 0
Reputation: 3557
You can use
<pre>
var test = '<?php echo $test?>';
</pre>
below the definition of $test.
Upvotes: 0
Reputation: 3454
var test = '<?php echo $test; ?>';
Or using shorthand echos, like this:
var test = '<?= test;?>';
Upvotes: 0
Reputation: 214959
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)
Upvotes: 2