Aaron Fisher
Aaron Fisher

Reputation: 645

Use a PHP variable in JQuery

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

Example:

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

Thanks

Upvotes: 9

Views: 49810

Answers (4)

Lix
Lix

Reputation: 47956

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>

Upvotes: 9

Fosco
Fosco

Reputation: 38506

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)

Upvotes: 5

Evan Mulawski
Evan Mulawski

Reputation: 55334

Assuming your jQuery is in the same file:

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

Upvotes: 5

Marc B
Marc B

Reputation: 360582

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.

Upvotes: 11

Related Questions