-1

Previously, I am encountering "unterminated string literal strange error" in JS: SyntaxError: unterminated string literal strange error

I kinda fix it using json_encode since newlines are escaped.

Now I am getting these odd results, for example this JS variable (processed with json_encode):

        cacheObj_open.handler='<pre class="brush: html;">"&lt;html&gt;\r\n&lt;body&gt;\r\n&lt;p&gt;Hello world.&lt;\/p&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;"</pre>';         

Will output with codes having double quotes around them:

"<html>
<body>
<p>Hello world.</p>
</body>
</html>"

The above code runs without console error. But the one below (also processed with json_encode) throws SyntaxError: missing ; before statement error:

cacheObj_open.handler='<pre class="brush: html;">"\r\n&lt;?php\r\n$stmt = $dbh-&gt;prepare(&quot;SELECT * FROM REGISTRY where name = ?&quot;);\r\nif ($stmt-&gt;execute(array($_GET['name']))) {\r\n  while ($row = $stmt-&gt;fetch()) {\r\n    print_r($row);\r\n  }\r\n}\r\n?&gt;"</pre>';            

What is the best way to avoid any errors when outputting HTML entity source code to a JS variable? I know that json_encode will escape some new lines(this is a good idea) but based on the above example, it still throws an error for some codes. I appreciate any inputs and suggestions.

I have tried adding addslashes on PHP side but it still throws the error.

Community
  • 1
  • 1
Emerson Maningo
  • 2,189
  • 9
  • 32
  • 47
  • How are you generating the `cacheObj_open.handler = ...` line? – DCoder Jan 05 '13 at 09:24
  • You can see the complete javascript here: http://stackoverflow.com/questions/14170153/syntaxerror-unterminated-string-literal-strange-error – Emerson Maningo Jan 05 '13 at 09:25
  • That doesn't show how you actually put the encoded string into HTML. The right approach is using `cacheObj_open.handler = ;` , and NOT putting any quotes around the output of `json_encode`. – DCoder Jan 05 '13 at 09:27

1 Answers1

0

The error in this case is at execute(array($_GET['name'], the single quotes here close the quotes surrounding the whole string. They should be escaped with a backslash.

Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62