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,457
  • 1
  • 13
  • 26
Elitmiar
  • 35,072
  • 73
  • 180
  • 229

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
  • 442,112
  • 142
  • 972
  • 1,088
  • 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,457
  • 1
  • 13
  • 26
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90