Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?> [duplicate]

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?

like image 897
Steven Avatar asked Nov 27 '09 11:11

Steven


People also ask

Can I access a PHP variable in JavaScript?

We can use the short PHP echo tag inside the JavaScript to pass the PHP variable to JavaScript.

Can jquery access PHP 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.

How set JavaScript variable to PHP variable?

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'].

How use JavaScript variable on same page in PHP?

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.


2 Answers

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.

like image 62
Karsten Avatar answered Oct 09 '22 11:10

Karsten


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> 
like image 39
stroncium Avatar answered Oct 09 '22 09:10

stroncium