tags:

views:

227

answers:

3

I'm generating a string in PHP and then eventually passing this string into a Javascript alert box, my problem is I actually can't add line breaks in my alert box.

My code looks as follows

$str = "This is a string\n";
$alert = $str."This is the second line"; 

     if(!empty($alert)){
              ?>
               <script type="text/javascript">
                $(document).ready(function() {
                 alert('<?=$alert?>');
                });
               </script>
              <?php
             }

I'm getting the error

Undeterminnated string literal

If I remove the \n from string it works 100% but without line breaks

A: 

Have you tried \r\n?

tommieb75
Yes, tried this and it also failed
Roland
That is return and newline, that will still cause a php error.
Zoidberg
+6  A: 

This happens because PHP interprets the \n before JavaScript has the chance to, resulting in a real line break inside the Javascript code. Try

\\n
Pekka
oooo pipped to the post!
Matt Ellen
This makes sense, I tried this and this worked for me, thx Pekka
Roland
Actually this isn't generally enough, since the string may contain quotes and other characters which make code invalid. You should escape the string. See http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-including-escaping-newlines for how to do this.
Amnon
+2  A: 

You need to change $str to

$str = "This is a string\\n";

so that the \n gets passed to the javascript.

Matt Ellen