Possible Duplicate:
How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>
Is there any way to get access to a PHP variable in JavaScript?
I have a variable, $a
, in PHP and want to get its value in a JavaScript variable.
Most of the time you will need to access php variables inside jquery or javascript. If you have simple string value then you can echo this in javascript directly but if you have array type of value and you want to get it in javascript then you have to use json encode method.
Inside the JavaScript, we can use the PHP tag to echo the PHP variable assigning it to a JavaScript variable. For example, assign a value Metallica to a variable $var inside the PHP tags. Write a script tag and inside it, write a PHP tag. Inside the PHP tag, echo a JavaScript variable jsvar .
click(function() { var userID = $(this). attr('id'); //alert($(this). attr('id')); $. ajax({ type: "POST", url: 'logtime.
You can't, you'll have to do something like
<script type="text/javascript"> var php_var = "<?php echo $php_var; ?>"; </script>
You can also load it with AJAX
rhino is right, the snippet lacks of a type for the sake of brevity.
Also, note that if $php_var
has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.
metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:
<script type="text/javascript"> var something=<?php echo json_encode($a); ?>; </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With