0

Possible Duplicate:
How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

this may have been covered, but I'm wondering if it's possible to pass a php variable to a jQuery selector.

I have a variable called $tDate, and I want to be able to use it in this code:

$('$tDate').backstretch([
          "pot-holder.jpg",
          "coffee.jpg",
          "dome.jpg"
        ], {
            fade: 750,
            duration: 4000
        });
Community
  • 1
  • 1
Rob
  • 79
  • 6
  • This issue has been covered though: http://stackoverflow.com/questions/1808108/how-to-access-php-variables-in-javascript-or-jquery-rather-than-php-echo-vari – Justus Romijn Oct 04 '12 at 06:44

3 Answers3

3

I would suggest keeping your javascript as much as possible in seperate .js files. But you can set javascript variables in your php-generated html, like so:

<html>
  <head>
    <title>PHP variables to Javascript</title>
    <script type="text/javascript">
    var myVar = <?php echo $myVar; ?>;
    </script>
    <!-- you can use that variable in your .js files 
         that are loaded after setting the variable -->
    <script src="/javascripts/myjavascript.js"></script>

  </head>
  <body>
    <h1>Passing php variables to javascript</h1>
  </body>
  </html>

And your javascript could use that variable like so:

// I assume myVar is a string
$(myVar).backstretch
...

Seems nice and tidy this way to me. I don't like cluttering my clientside code with serverside code. And if you mess up your PHP variable somewhere in the future, you can easily detect it because it will throw an exception on the variable, instead of jQuery barfing up unreadable errors.

Justus Romijn
  • 15,699
  • 5
  • 51
  • 63
2
$('<?PHP echo $tDate; ?>').backstretch([
      "pot-holder.jpg",
      "coffee.jpg",
      "dome.jpg"
    ], {
        fade: 750,
        duration: 4000
    });
Adam Plocher
  • 13,994
  • 6
  • 46
  • 79
0
    <?php $tDate = "varXYZ";?>
    $('$<?php echo $tDate; ?>').backstretch([
      "pot-holder.jpg",
      "coffee.jpg",
      "dome.jpg"
    ], {
        fade: 750,
        duration: 4000
    });
meWantToLearn
  • 1,691
  • 2
  • 25
  • 45