How do I access PHP variables in JavaScript or jQuery? Do I have to write
<?php echo $variable1 ?> <?php echo $variable2 ?> <?php echo $variable3 ?> ... <?php echo $variablen ?>
I know I can store some variables in cookies, and access these values via cookies, but values in cookies are relatively stable values. Moreover, there is a limit, you can not store many values in cookies, and the method is not that convenient. Is there a better way to do it?
We can use the short PHP echo tag inside the JavaScript to pass the PHP variable to JavaScript.
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.
1) First add a cookie jquery plugin. 2) Then store that window width in a cookie variable. 3) Access your cookie in PHP like $_COOKIE['variable name'].
You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success"; </script> <? php echo "<script>document.
Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:
<?php $simple = 'simple string'; $complex = array('more', 'complex', 'object', array('foo', 'bar')); ?> <script type="text/javascript"> var simple = '<?php echo $simple; ?>'; var complex = <?php echo json_encode($complex); ?>; </script>
Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.
Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.
If AJAX isn't an option you can use nested data structures to simplify.
<?php $var = array( 'qwe' => 'asd', 'asd' => array( 1 => 2, 3 => 4, ), 'zxc' => 0, ); ?> <script>var data = <?php echo json_encode($var); ?>;</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