views:

116

answers:

5

I want to use a PHP variable as a javascript variable - specifically I want to user the PHP variable session_id(); and use this as a javascript variable.

<?php
$php_var = session_id();
?>
<script language="JavaScript" type="text/javascript">
js_var = <?php echo($php_var ?>;
</script>

This seems like it should work for me but it doesnt can anyone suggest a better way?

+3  A: 

That's just fine. Be sure that if the variable you're echoing is a string that you put quotes around it and escape any quotes, newlines, etc. inside it -- e.g., make sure it really gets output as a valid JavaScript string literal. Also, don't forget the var before js_var.

T.J. Crowder
+1  A: 

It doesn't work because your snippet contains errors, it should be:

<?php
$php_var = session_id();
?>
<script language="JavaScript" type="text/javascript">
js_var = <?php echo $php_var ?>;
</script>
Anax
+2  A: 
rhino
Funny how people upvote this answer the most although it misses the quotes around the php block and advertises using the shorthand syntax, which is [widely regarded as bad practise](http://stackoverflow.com/questions/1386620/php-echo-vs-php-short-tags/1386631#1386631).
Gordon
I didn't know that using the shorthand syntax is bad... thanks for the link. And you're right about the quotes... I've already changed it. I don't really know why did I forget about them...
rhino
+7  A: 

The best method i can think of looks like this:

<?php
$php_var = session_id();
?>
<script type="text/javascript">
    var js_var = <?php echo json_encode($php_var); ?>;
</script>

PHP's json_encode-function is always producing valid JavaScript, which is not ensured if you are simply outputting random values. If you decide not to use json_encode(), you should at least enclose the php-value with quotes to prevent syntax errors. Be aware of escaping!

<?php
$php_var = session_id();
?>
<script type="text/javascript">
   var js_var = "<?php echo $php_var; ?>";
</script>
elusive
+1 for `json_encode`. That's what it's there for. Don't ever use the raw-echo version. You risk bugs and XSS security holes.
bobince
A: 

You have a perfectly valid solution already.

You could extract it to a separate JS include if you don't like having inline script, but the technique would be the same.

The solution you're really hunting for is called JSON, which is basically a clever acronym for producing valid Javascript syntax in other languages. Recent versions of PHP (v5.0 or better) have JSON functions which allow you to produce blocks of valid Javascript variable code. It would look something like this:

<?php
$phpdata=array('key1'=>'some value','key2'=>'another value');
$jsondata=json_encode($phpdata);
echo "var mydata=".$jsondata.";";
?>

This will give you javascript that looks like this:

var mydata={'key1':'some value','key2':'another value'};

Hope that helps.

Spudley