Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variable in javascript "Invalid or unexpected token"

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>
like image 513
Jake Avatar asked Aug 01 '26 04:08

Jake


2 Answers

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>
like image 56
Monty Avatar answered Aug 02 '26 18:08

Monty


This should work, use single quotes

<?php
  $example = '2';
?>
  <script type="text/javascript">
      var php_var = '<?php echo  $example; ?>';
  </script>
like image 36
user3569377 Avatar answered Aug 02 '26 16:08

user3569377



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!