Reputation: 13441
<?php
/* ... Getting record from database */
$comment = $record["comment"];
/* There might be quotes or double quotes, we don't know */
echo "<input type='button' onclick=\"doSomething('$comment')\" />";
?>
<script>
function doSomething(comment) {
alert(comment);
/* Something else */
}
</script>
When $comment string contains a single quote , I'm getting "Uncaught SyntaxError: Unexpected token ILLEGAL" error in javascript.
$comment = str_replace("'","\'",$comment);
How can I escape quote and double quote in this example?
Upvotes: 0
Views: 2269
Reputation: 360842
Use json_encode(), which guarantees your output will be syntactically valid JavaScript code:
<input type="button" onclick="doSomething(<?php echo json_encode($comment) ?>">
Upvotes: 9
Reputation: 16177
You can try something like this in Javascript:
function addslashes(str){
str=str.replace(//g,'\');
str=str.replace(/'/g,''');
str=str.replace(/"/g,'"');
str=str.replace(//g,'');
return str;
}
function stripslashes(str){
str=str.replace(/'/g,''');
str=str.replace(/"/g,'"');
str=str.replace(//g,'');
str=str.replace(/\/g,'');
return str;
}
Hope this help :)
Upvotes: 0