Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 428
Ravichandran Jothi Avatar asked Sep 01 '25 22:09

Ravichandran Jothi


1 Answers

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>
like image 149
Cups Avatar answered Sep 03 '25 11:09

Cups