tags:

views:

80

answers:

3

Hi,

How to put php inside javascript?

I try (but its not working):

<?php  
$htmlString= 'testing';
 ?>
<html>
  <body>
    <script type="text/javascript">  
      var htmlString=<?php echo $htmlString; ?>;
      alert(htmlString);
    </script>
  </body>
</html>

tutorial that I use for that parpose: http://web-design.lovetoknow.com/Define_PHP_Variables_Inside_Javascript

Thanks

+13  A: 

You're missing quotes around your string:

...
var htmlString="<?php echo $htmlString; ?>";
...
John Conde
+1  A: 

you need quotes around the string in javascript

var htmlString="<?php echo $htmlString; ?>";
second
Beaten by a minute :]
Anraiki
+1  A: 

Try this:

<?php $htmlString= 'testing'; ?>
<html>
  <body>
    <script type="text/javascript">  
      // notice the quotes around the ?php tag         
      var htmlString="<?php echo $htmlString; ?>";
      alert(htmlString);
    </script>
  </body>
</html>

When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.

Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing' to $htmlString. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.

Daren Thomas