Use PHP variable in jQuery

Anyway, can I use the php variable in a jQuery script?

Example:

  • PHP variable: $sr2
  • Excerpt from jQuery script (with variable): $('#a2_bottom_$sr2')

How can I make the variable be valid in this part of jQuery?

thanks

+6
source share
4 answers

What you could just do was use your PHP for the echo code to trigger the JavaScript variable.

 <script type="text/javascript"> <?php $phpVar = "foo"; echo "var phpVariable = '{$phpVar}';"; ?> </script> 

After the PHP code is parsed and the HTML is sent to the user - everything they saw is the result of a PHP echo -

 <script type="text/javascript"> var phpVariable = 'foo'; </script> 

Now your phpVariable is available for your JavaScript! So you use it, as in any other case -

 $("div."+phpVariable); 

This will lead us to any <div> element with class foo -

 <div class="foo"></div> 
+8
source

PHP runs on the server, jquery runs on the client. If you want the jQuery variable to be accessible to PHP (and by extension, the basic javascript mechanism), you will have to either send the value of the variable when the page is output to the server, for example.

 <script type="text/javascript"> var my_php_var = <?php echo json_encode($the_php_var) ?>; </script> 

or get the value through an AJAX call, which means that you basically create a web service.

+9
source

You can output it as part of the page in a script tag ... i.e.

 <script type="text/javascript"> <?php echo "var sr2 = \"" . $sr2 . "\""; ?> </script> 

Then your jQuery string will be able to access it:

 $('#a2_bottom_' + sr2) 
+5
source

Assuming your jQuery is in a single file:

 ... $('#a2_bottom_<?php echo $sr2 ?>') ... 
+2
source

Source: https://habr.com/ru/post/916170/


All Articles