Reputation: 151
I'm having a problem trying to use a PHP
variable
within JavaScript
. I keep getting the following message.
"Invalid or unexpected token. Message: Undefined variable: example."
I'm unsure why example is being undefined, as it is defined within the php code. Here is my code:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = "<?php echo json_encode($example); ?>";
</script>
Does anyone have any suggestions? I have also tried the following javascript
that results in the same problem:
<script type="text/javascript">
var php_var = "<?php echo $example; ?>";
</script>
Upvotes: 3
Views: 5836
Reputation: 12277
Tried and working both variant:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = <?php echo json_encode($example); ?>;
console.log(php_var);
</script>
<script type="text/javascript">
var php_va = "<?php echo $example; ?>";
console.log(php_va);
</script>
Upvotes: 0
Reputation: 99
Firstly, your original code has a syntax error: $example = '2'
needs a semicolon.
Secondly, the next piece of code is just assigning the string <?php echo $example; ?>
to the JavaScript variable php_var where the $example
PHP variable is first substituted. The $example
variable should be initiated properly first, however, for this to work.
As a separate note: JS cannot execute PHP directly -- only a PHP server can do so. What you're most likely trying to do is this:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example ;?>';
</script>
Upvotes: 1
Reputation: 21
This should work, use single quotes
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example; ?>';
</script>
Upvotes: 1