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?

1

5 Answers 5

72

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>
4
  • 7
    You could have problems if $var contains single quotes, carriage returns... Commented May 5, 2011 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. Commented May 5, 2011 at 10:19
  • os-code-web.blogspot.com/2011/05/… Commented Jul 10, 2011 at 3: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 Commented Apr 11, 2017 at 6:20
13

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

var spge = <?php echo json_encode($cname); ?>;
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)

3

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

0
**var spge = '';** 
alert(spge);
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.