0
$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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

3 Comments

Thanks for answer but content is coming from admin section editor means admin is managing content from admin panel so how can i give slash after each line
"multiple whitespace will be removed" - unless you're using white-space:pre-wrap or similar. Then again, considering how few people even know that exists, they probably aren't.
admin inserting content in following format <div class="col-md-12"> <div class="col-md-5"><img title="Facebook" src="images/fb128.png" alt="Facebook" /></div> <div class="col-md-7"> <div class="form-group"><label>You&rsquo;ve got mail!</label> <p>Check your email account and click on the link to continue to activate your MyOffer account</p> </div> </div> </div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.