1

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 the string it works 100% but without line breaks.

Alex
  • 1,197
  • 1
  • 10
  • 22
Elitmiar
  • 32,536
  • 72
  • 175
  • 228

2 Answers2

19

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
  • 431,103
  • 135
  • 960
  • 1,075
  • This makes sense, I tried this and this worked for me, thx Pekka – Elitmiar Nov 17 '09 at 12:29
  • 1
    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 Nov 17 '09 at 12:34
4

You need to change $str to

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

so that the \n gets passed to the JavaScript.

Alex
  • 1,197
  • 1
  • 10
  • 22
Matt Ellen
  • 10,460
  • 4
  • 67
  • 85