Use a PHP variable in JQuery

jquery, php

Solution

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>

Problem

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

Original source