Search code examples
javascriptphpsyntax-errorhtmlspecialchars

What is a proper way to escape HTML for Javascript function?


I'm getting Uncaught SyntaxError: Unexpected identifier due of the Java-Script clashing syntax or single and double quote.

In the source file,the $str is escaped as special chars but not sure why Javascript will hit error.

What is the Correct/Proper way to escape it with single or double quote inside a string for Javascript function use purpose?

Below is my code :

<?php
    $str = 'I\'m John Doe < lol > "19" ! ?';
?>
<div onclick="alert('<?php echo htmlspecialchars($str); ?>')">Test</div>
<div onclick="alert(&quot;<?php echo htmlspecialchars($str); ?>&quot;)">Test</div>

Solution

  • The important thing to note here is that you don't just have JavaScript. You have JavaScript in an HTML attribute, so you have to escape for JS then for HTML.

    json_encode will escape for JS. It will also add quotes around strings, so do you don't need to do that yourself.

    htmlspecialchars will escape for HTML.

    onclick="alert(<?php echo htmlspecialchars( json_encode( $str ) ); ?>"