2

In my HTML file, I'm using a string variable called {$var} which is passed from a PHP file. How could I use {$var} in a javascript function within the same html file? I would like to display this variable using the js function. This is what I have so far:

<span id="printHere"></span>
<script type="text/javascript">
    var php_var = {$production};
    $('#printHere').html(php_var);
</script>
Brad
  • 159,648
  • 54
  • 349
  • 530
Roku
  • 69
  • 1
  • 7

2 Answers2

8

For PHP

You can echo out the variable directly into your JavaScript. Just be sure to json_encode() it so that data types and escaping are all done automatically.

var php_var = <?php echo json_encode($production) ?>;

For Smarty

If you are using Smarty for your templating engine, you want this instead:

var php_var = {$production|json_encode nofilter};

What this does is disable the HTML escaping of Smarty (with nofilter) and passes the value through json_encode().

Brad
  • 159,648
  • 54
  • 349
  • 530
1

Make sure $production is set. If it is a (javascript) String then use:

var php_var = '<?php echo addslashes($production); ?>';

If it is a Number then use

var php_var = <?php echo $production; ?>;
hek2mgl
  • 152,036
  • 28
  • 249
  • 266