Reputation: 113
$str is loading dynamic content from admin panel (tinymce) in following format
$str = 'First Line
Second Line
Third Line';
Now when i try to access this variable then it gives me unterminated string literal
<script type="text/javascript">
$(document).ready(function() {
var a = '<?php echo $str;?>';
$('#abc').html(a);
});
</script>
<div id="abc"></div>
when i convert string to $str = 'First line Second line Third line';
then it does not give error but my string is in above way.
Upvotes: 0
Views: 850
Reputation: 324640
When dumping a PHP variable into JavaScript, ALWAYS use json_encode
. Like this:
var a = <?php echo json_encode($str); ?>;
Note no quotes around the PHP code, this is important! PHP will add the quotes for you and escape everything correctly.
Upvotes: 2
Reputation: 38345
It's the line breaks, they're not valid inside a JavaScript string literal. If you want multiple lines in a JavaScript string, use a backslash (\
):
var testString = 'This is \
a test';
Even then, multiple whitespace (including linebreaks) will be removed when it's set as the content of an HTML element.
That said, I don't see why you're using the JavaScript to do this at all, you could simply do:
<div id="jaspreet"><?php echo $str;?></div>
Upvotes: 0