<?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.
- I add slashes before quotes, it didn’t work –
$comment = str_replace("'","\'",$comment);
How can I escape quote and double quote in this example?
Use json_encode(), which guarantees your output will be syntactically valid JavaScript code: