1

i have php variables that is like this

var externalData = '<?php echo $matches[0]; ?>';

I when i load the source code of the page comes like this

var externalData = 'data,data,data,data,data
';

this breaks the javascript code, and browser cant run it.

I want to be like this:

var externalData = 'data,data,data,data,data';

the php output is a full line of a file, so may contains the end of the line. I test it by hand and working, how i can fix this?

user2670708
  • 143
  • 7
  • 3
    What is that closing parenthesis doing there? – Patrick Kostjens Aug 11 '13 at 13:14
  • sorry just error typing, i remove the parenthesis. – user2670708 Aug 11 '13 at 13:17
  • You should escape the result of $matches[0]. Also the ')' is not valid javascript so it is normal that it will break. –  Aug 11 '13 at 13:18
  • This is a bad practice. Serialize your PHP data to JSON via `json_encode()`, then parse it client side via `JSON.parse`, possibly from a `` tag [[see this answer](http://stackoverflow.com/a/7956249/1073758)]. – moonwave99 Aug 11 '13 at 13:29

3 Answers3

4

You can use trim (or rtrim) to remove the line break at the end of the string:

var externalData = "<?php echo trim($matches[0]); ?>";

Alternatively you could pass the whole string to json_encode:

var externalData = <?php echo json_encode($matches[0]); ?>;

This would not remove the line break, but it would encode it and the resulting value will be a valid JS string literal (i.e. all other characters that could break the code, such as ' or ", will escaped as well).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Maybe you should strip all HTML

var externalData = "<?php echo strip_tags($matches[0];) ?>");
sanders
  • 10,794
  • 27
  • 85
  • 127
0

You can also use substr() to get rid of the last char of string.

Like this:

var externalData = "<?php echo substr($matches[0], 0, strlen($matches[0]) - 1); ?>";
Patrick Kostjens
  • 5,065
  • 6
  • 29
  • 46
Chang
  • 1,163
  • 9
  • 14
  • Won't work if the break is actually `\r\n` (windows). Also `substr($blah,0,-1)` is more elegant. – Dave Aug 11 '13 at 13:24
  • @Dave Thank you! If it runs on windows. `substr($blah,0,-2)` may be OK – Chang Aug 11 '13 at 13:29
  • it's not about what it runs on, but where the newline is coming from in the first place. If it's known for sure, then yes this would be fine. If it's uncertain, `rtrim` is probably the better option. – Dave Aug 11 '13 at 13:30