What are the common pitfalls to avoid when implementing a JavaScript function for smilie insertion in PHP?

One common pitfall to avoid when implementing a JavaScript function for smilie insertion in PHP is not properly escaping the JavaScript code within the PHP script. This can lead to syntax errors or security vulnerabilities. To solve this issue, use the json_encode function to properly escape the JavaScript code before embedding it in the PHP script.

<?php
$javascript_code = '<script>function insertSmilie() { document.getElementById("textarea").value += ":)"; }</script>';

echo '<textarea id="textarea"></textarea>';
echo '<button onclick="insertSmilie()">Insert Smilie</button>';

echo '<script>';
echo json_encode($javascript_code);
echo '</script>';
?>