user2670708
user2670708

Reputation: 143

Php output breaks the Javascript

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?

Upvotes: 1

Views: 324

Answers (3)

Felix Kling
Felix Kling

Reputation: 816442

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).

Upvotes: 4

Chang
Chang

Reputation: 1413

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); ?>";

Upvotes: 0

sanders
sanders

Reputation: 10898

Maybe you should strip all HTML

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

Upvotes: 0

Related Questions