views:

87

answers:

3

I'm doing something like following to transfer value from PHP to javascript:

var str = '<?php echo $v; ?>';

If there is no "'" in $v, it'll just be fine.

But in case there is "'" in $v, obviously error will be reported.

So far I've only used mysql_real_escape, which is not applicable now.

+8  A: 

You should be using json_encode() to go from PHP to Javascript:

var str = <?=json_encode($v);?>;
Greg
It works like charm!!
Shore
+3  A: 

mysql_real_escape_string is intended to be only used for value to be used in a string in a MySQL query. Use json_encode to convert your string into a valid JavaScript expression.

Gumbo
A: 
<?php
    $v = "blah's";
?>
<script language="javascript">
    var str = '<?php echo addslashes($v); ?>';
    alert(str);
</script>
NinethSense