0

Dont ask me why it is the way it is since it is not my code. This is the snippet from the code:

JS:

var myTitle = "<?= $this->myTitle ?>";

Now this works perfect but if $this->myTitle contains a double quote in it it breaks the Javascript code. Is it possible to escape this on JS side and still display the double quote?

The JS error message that I get:

SyntaxError: missing ; before statement
var myTitle = ""A" Test Title";

Things I want to avoid doing:

  1. I do not want to change "<?= $this->myTitle ?>" to '<?= $this->myTitle ?>' because it might contain single quote as well.
  2. I can not modify the code where I assign $this->myTitle to a hidden input and then grab it using JS. (Not up to me)
  3. Can not instal any plugins nor can I download any libraries to do so
  4. Can NOT modify PHP code to add slashes or encode it using JSON

Is there a simpler solution that only requires Javascript code modification?

GGio
  • 7,441
  • 11
  • 41
  • 76
  • 1
    How to pass variables and data from PHP to JavaScript http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript – John Hartsock May 22 '14 at 19:03
  • The simplest option is to output as JSON, which JavaScript can understand. See "[*3. Echo the data directly to JavaScript*](http://stackoverflow.com/a/23740549)" from "*[How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript)*." – Jonathan Lonowski May 22 '14 at 19:04
  • Updated my question. Cant really modify PHP – GGio May 22 '14 at 19:06
  • 3
    "*Can NOT modify PHP code to add slashes or encode it using JSON*" Then it's not possible. If the output from PHP is generating a syntax error, JavaScript can't fix that error within itself. – Jonathan Lonowski May 22 '14 at 19:06
  • Its not possible to escape quotes in Javascript? similar to addslashes but on javascript side – GGio May 22 '14 at 19:08
  • @GGio JavaScript supports escaped quotes, sure. But, it can't intercept the raw text of the script before it's evaluated by the engine to escape them itself. The PHP `echo` is writing that snippet of JavaScript code, it needs to write it correctly and escape the quotes itself. – Jonathan Lonowski May 22 '14 at 19:08

0 Answers0