Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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>
share|improve this question

marked as duplicate by epascarello, hjpotter92, pilsetnieks, Reuben Mallaby, Anand May 1 '13 at 10:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
you just need to echo it –  Dagon Apr 30 '13 at 20:18
    
Just look at the page source –  zerkms Apr 30 '13 at 20:18
    
I looked at the source code and the variable {$var} displays <span class="itemprop" itemprop="name">Name</span> –  Roku Apr 30 '13 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. –  Brad May 2 at 12:55

2 Answers 2

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; ?>;
share|improve this answer
1  
may want to add addslashes() to that. –  Ryan Naddy Apr 30 '13 at 20:20
1  
@RyanNaddy, That's only part of the problem. See my answer with JSON-encoding for the correct solution. –  Brad Apr 30 '13 at 20:21
    
{$production} displays <span class="itemprop" itemprop="name">Name</span> Does that count as a string? –  Roku Apr 30 '13 at 20:29
    
are you using a template engine? (smarty)? –  hek2mgl Apr 30 '13 at 20:31
    
Not that I know of. –  Roku Apr 30 '13 at 20:32

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

share|improve this answer
    
Looks better than my! ;) –  hek2mgl Apr 30 '13 at 20:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.