Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a PHP variable in JQuery

Tags:

jquery

php

Is there anyway I can use a php variable in the JQuery script?

Example:

  • PHP variable: $sr2
  • Excerpt of JQuery script (with variable): $('#a2_bottom_$sr2')

How can I make it so the variable is valid in that JQuery part?

Thanks

like image 724
Aaron Fisher Avatar asked May 19 '12 19:05

Aaron Fisher


People also ask

Can you use a PHP variable in jQuery?

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.

Can you use a PHP variable in javascript?

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.

How pass variable value to PHP variable in jQuery on same page?

Just put the code in PHP Tag, while working with PHP in HTML pages use the code inside PHP tags.


4 Answers

PHP runs on the server, jquery runs on the client. If you want a PHP variable to be available to jquery (and by extension, the underlying javascript engine), you'll have to either send the variable's value over at the time you output the page on the server, e.g.

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

or retrieve the value via an AJAX call, which means you're basically creating a webservice.

like image 174
Marc B Avatar answered Oct 16 '22 05:10

Marc B


What you could simply do is use your PHP to echo out the code to initiate a JavaScript variable.

<script type="text/javascript">
<?php

  $phpVar = "foo";
  echo "var phpVariable = '{$phpVar}';";

?>
</script>

Once the PHP code is parsed, and the HTML is sent to the user - all they will see is the result of the PHP echo -

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

Now your phpVariable is available to your JavaScript! So you use it like you would in any other case -

$("div."+phpVariable);

That will retrieve us any <div> element with a foo class -

<div class="foo"></div>
like image 35
Lix Avatar answered Oct 16 '22 05:10

Lix


Assuming your jQuery is in the same file:

... $('#a2_bottom_<?php echo $sr2 ?>') ...
like image 37
Evan Mulawski Avatar answered Oct 16 '22 05:10

Evan Mulawski


You could 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 line would be able to access it:

$('#a2_bottom_' + sr2)
like image 28
Fosco Avatar answered Oct 16 '22 05:10

Fosco