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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With