I am trying to output Google Translate code from PHP (wordpress plugin) to the page and it is giving me Illegal Token errors even though when I paste the exact same line of code directly into the console and run it, it works.
Here is my PHP:
function AddTranslateSidebar(){
echo "<script>
jQuery(document).ready(function(){
gt = escape('<div id=\"google_translate_element\"></div><script type=\"text/javascript\">function googleTranslateElementInit() {new google.translate.TranslateElement({pageLanguage: \"en\", layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, \"google_translate_element\");}</script><script type=\"text/javascript\" src=\"http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit\"></script>');
jQuery('#sidebar').prepend(unescape(gt));
});
</script>";
}
That code outputs the following into the page as HTML/JavaScript:
<script>
jQuery(document).ready(function(){
gt = escape('<div id="google_translate_element"></div><script type="text/javascript">function googleTranslateElementInit() {new google.translate.TranslateElement({pageLanguage: "en", layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, "google_translate_element");}</script><script type="text/javascript" src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>');
jQuery('#sidebar').prepend(unescape(gt));
});
</script>
Which causes the error
Uncaught SyntaxError: Unexpected token ILLEGAL
On the gt = escape( … ); line.
However, if I copy that code directly from the HTML source using the inspector and then paste it into the console and run it, it works and the translate dropdown shows up.
Why is this happening?
Thanks.
The sequence of characters
</script>always means to end the current script block. My suspicion is that this is causing the problem.You can’t include
</script>verbatim in a JavaScript string. Instead you need to break it up and re-concatenate the parts.E.g. this:
Should become this: