0

Possible Duplicate:
Pass a PHP string to a Javascript variable (including escaping newlines)

So I'm wondering if it's possible to access the data in a php variable, in a jquery/javascript script. Say I have a wordpress query/loop, that brings up a particular post from the database.

Then if I store that post in a php variable, is there any way I could reference that variable/post from within a javascript/script?

Community
  • 1
  • 1
Demetrio M.
  • 207
  • 1
  • 3
  • 12

4 Answers4

0

You can do the below on a PHP page.

<script>
    alert("<?php echo $hello_world;?>");
</script>

This won't work in a .js file, however, as it obviously isn't set to interpret PHP syntax.

Cory Dee
  • 2,858
  • 6
  • 40
  • 55
0

Yes. You can.

Scenario: 1 If HTML and PHP are in seperate files

 HTML 
<html>
 <head>
  <script type='text/javascript' src='code.php' runat='server'></script>
  <script>
     // you can get phpVar here
     alert(phpVar);
  </script>
  </head>
 <body>
 </body>
</html>

 code.php 

 <?php
    $value =" Value from PHP";
    echo "var phpVar = '". $value ."'";
  ?>

Scenario: 2 If HTML and PHP are in same file

 <?php $value =" Value from PHP"; ?>
   <html>
     <head>
       <script>
         <?php echo "var phpVar ='" . $value ."'"; ?>
          alert(phpVar);
       </script>
      </head>
     <body>
     </body>
     </html>
shivashankar
  • 1,147
  • 1
  • 10
  • 16
0

So when your browser initiates a request, it hits the server. The server processes the request, running through all the necessary methods and setting variables, and then it sends the result back to the browser. At that point, anything not in session dies on the PHP side (i.e. it's not persistent) so there's no way for javascript to access this php variable.

If what you'd like to do is to pass a php variable or object to a javascript function, I'd recommend using json_encode: http://www.php.net/manual/en/function.json-encode.php

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

The above example will output:

{"a":1,"b":2,"c":3,"d":4,"e":5}
John Zumbrum
  • 2,786
  • 8
  • 36
  • 60
0

You could output information about the post inline in a script tag like this (assumes you're in the "loop" and only outputting one post):

<script>
var post_id = <?php the_ID(); ?>;
var post_title = "<?php the_title(); ?>";
var post_excerpt = "<?php the_excerpt(); ?>"; 
</script>

However, depending on what you're trying to accomplish you may want to approach this differently. Perhaps using a script to output post data in JSON format so that it can be natively understood by javascript then writing AJAX functions to retrieve and render those posts. Here are some resources that may be helpful:

Wordpress JSON API jQuery AJAX

Joe Landsman
  • 2,177
  • 13
  • 9