How to assign Php variable value to Javascript variable? [duplicate]
Possible Duplicate:
What's the best way to pass a PHP variable to Javascript?
I am using the following code:
<script type="text/javascript">
<?php $ctnme = $_SERVER['REQUEST_URI'];
$cnme = explode("/",$ctnme);
echo $cname = $cnme[1];
?>
var spge = <?php echo $cname; ?> ;
alert(spge);
</script>
The value doesn't alert. What is the mistake?
Solution 1:
Essentially:
<?php
//somewhere set a value
$var = "a value";
?>
<script>
// then echo it into the js/html stream
// and assign to a js variable
spge = '<?php echo $var ;?>';
// then
alert(spge);
</script>
Solution 2:
The most secure way (in terms of special character and data type handling) is using json_encode()
:
var spge = <?php echo json_encode($cname); ?>;
Solution 3:
Use json_encode() if possible (PHP 5.2+).
See this one (maybe duplicate?): Pass a PHP string to a JavaScript variable (and escape newlines)
Solution 4:
Put quotes around the <?php echo $cname; ?>
to make sure Javascript accepts it as a string, also consider escaping.