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>
4
  • 1
    you just need to echo it Commented Apr 30, 2013 at 20:18
  • Just look at the page source Commented Apr 30, 2013 at 20:18
  • I looked at the source code and the variable {$var} displays <span class="itemprop" itemprop="name">Name</span> Commented Apr 30, 2013 at 20:22
  • This question is not a duplicate. It should not have been closed as a duplicate. Everyone that voted for this question to be closed as a duplicate isn't paying much attention. Commented May 2, 2014 at 12:55

2 Answers 2

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().

Sign up to request clarification or add additional context in comments.

1 Comment

Looks better than my! ;)
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; ?>;

11 Comments

may want to add addslashes() to that.
@RyanNaddy, That's only part of the problem. See my answer with JSON-encoding for the correct solution.
{$production} displays <span class="itemprop" itemprop="name">Name</span> Does that count as a string?
are you using a template engine? (smarty)?
I would assume this as {$producetion} wouldn't output anything if it's just php (or even html)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.