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?
The best method i can think of looks like this:
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 usejson_encode(), you should at least enclose the php-value with quotes to prevent syntax errors. Be aware of escaping!