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?
This question is related to
php
javascript
html
**var spge = '';**
alert(spge);
Put quotes around the <?php echo $cname; ?>
to make sure Javascript accepts it as a string, also consider escaping.
Use json_encode() if possible (PHP 5.2+).
See this one (maybe duplicate?): Pass a PHP string to a JavaScript variable (and escape newlines)
The most secure way (in terms of special character and data type handling) is using json_encode()
:
var spge = <?php echo json_encode($cname); ?>;
Source: Stackoverflow.com