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>
$example = '2'that might be problem.$exampleshould be output asvar php_var = "2";json_encodewill add double quotes, makingvar php_var = ""2"";Having said thatvar php_var = "<?php echo $example; ?>";worked as expected for me.