34

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?

Community
  • 1
  • 1
Ravichandran Jothi
  • 3,028
  • 11
  • 52
  • 82

5 Answers5

73

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>
Cups
  • 6,901
  • 3
  • 26
  • 30
  • 7
    You could have problems if $var contains single quotes, carriage returns... – Maxime Pacary May 05 '11 at 10:10
  • 1
    I agree, however the I get the impression the question seems to have changed substantially since I first replied making this reply look rather redundant now. IIRC it was a question about the whole principle of how to pass a var, now its an array. – Cups May 05 '11 at 10:19
  • http://os-code-web.blogspot.com/2011/05/can-you-set-javascript-variable-value.html – Jagan Chennai Jul 10 '11 at 03:37
  • when i alert it, it shows empty, can anyone help me find a solution, also i would like to know where should I type those script, as of now i have it at end of page – G.Ashok Kumar Apr 11 '17 at 06:20
12

The most secure way (in terms of special character and data type handling) is using json_encode():

var spge = <?php echo json_encode($cname); ?>;
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
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)

Community
  • 1
  • 1
Maxime Pacary
  • 22,336
  • 11
  • 85
  • 113
3

Put quotes around the <?php echo $cname; ?> to make sure Javascript accepts it as a string, also consider escaping.

Dunhamzzz
  • 14,682
  • 4
  • 50
  • 74
0
**var spge = '';** 
alert(spge);
Sai Sherlekar
  • 1,804
  • 1
  • 17
  • 18