32

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
  • 2,990
  • 11
  • 48
  • 82

5 Answers5

68

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,771
  • 3
  • 25
  • 29
  • 7
    You could have problems if $var contains single quotes, carriage returns... – Frosty Z 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
11

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
  • 80,936
  • 24
  • 154
  • 184
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
Frosty Z
  • 21,350
  • 10
  • 81
  • 110
3

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

Dunhamzzz
  • 14,344
  • 3
  • 48
  • 74
0
**var spge = '';** 
alert(spge);
Sai Sherlekar
  • 1,782
  • 1
  • 16
  • 17