max
max

Reputation: 3716

passing php string with multiple lines to a javascript function/variable

I'm working on someone else's website and it has a very stupid logic! Anyway, there is a php variable which contains a string which comes from database.

$x = ' aaaa
bbb

ccc


gggg ';

and I need to feed this string to a javascript function:

<script>

var x = "<?php echo $x ; ?>";
some_function(x);

</script>

As you know I end up with an error because a javascript variable cannot contain multiple lines without joining them together like this:

var x = ' i '+
        ' have '+
        ' different lines'; 

How can I do this? It doesn't matter if it removes the lines or formats it properly, I just want to get rid of this error.

Upvotes: 8

Views: 9549

Answers (4)

VLAZ
VLAZ

Reputation: 29039

If you absolutely have to do this, you can use template literals in JavaScript to side-step this issue. They can be multiline, so you can have

<script>

var x = `<?php echo $x ; ?>`;
some_function(x);

</script>

This will produce the following JavaScript code:

var x = ` aaaa
bbb

ccc


gggg `;

some_function(x);

function some_function(x) {
  console.log(x);
}

Something to watch out for is that template literals can have code in them and will be evaluated if placed inside ${}. So, if your PHP code produces such a string but you require it to be shown literally, then you might have a problem:

var x = `hello ${1 + 1}`;
var y = "hello ${1 + 1}";

console.log(x);
console.log(y);

This can be especially dangerous if your PHP code happens to produce something that JavaScript can interpret as a variable name:

var x = `hello ${y}`; //error - there is no variable `t`

With all this said, it is better to avoid programmatically generating source code, since it's error prone. It's better to use AJAX to transfer the data safely:

jQuery Ajax POST example with PHP

How to make an AJAX call without jQuery?

Upvotes: 2

Gray
Gray

Reputation: 2333

Pass the string into json_encode to properly escape it. If you're outputting to an HTML document, make sure to pass JSON_HEX_TAG as part of the options, to escape < and > and prevent a malicious user from ending your </script> tags early and introducing an XSS exploit.

Upvotes: 20

user2060431
user2060431

Reputation: 114

try this

var JsString = "<?php 
echo str_replace(array("\n","\r","\r\n"),'','YOUR 
MULTI LINE 
STRING');?>";

Upvotes: 4

Tanner Heggy
Tanner Heggy

Reputation: 1

Convert it into a string with the proper escape characters before printing it to the js.

Upvotes: -1

Related Questions