2

I have a message that I would like to show by using alert()

$message = "No result found for the following info:Name: ".$FullName."IC: ".$ID." in database.";
echo "<script>alert('".$message."'); window.history.back();</script>";

This is working but if I add a new line '\n' into the message

$message = "No result found for the following info:\nName: ".$FullName."\nIC: ".$ID." in database.";


it will not show out the pop out message. What is the problem?

Kevin
  • 41,694
  • 12
  • 53
  • 70
Newbie
  • 1,584
  • 9
  • 33
  • 72

5 Answers5

5

Edit it to not change to newline in PHP, instead in javascript:

'No result found for the following info:\nName: '.$FullName.'\nIC: '.$ID.' in database.'
^                                               ^           ^      ^     ^             ^

OR by adding extra backslash: "\\n".

According to Panther, also truth: use 'alert("' . $message . '")'.

yergo
  • 4,761
  • 2
  • 19
  • 41
4

Or use PHP_EOL

 $msg = 'Hello' . PHP_EOL . 'Next line';
Tom
  • 691
  • 4
  • 7
3

Add another \ backslash on your newlines:

$message = "No result found for the following info:\\nName: ".$FullName."\\nIC: ".$ID." in database.";

Output

Kevin
  • 41,694
  • 12
  • 53
  • 70
1

\n etc. aren't interpreted in single quotes, just in double quotes.

echo "<script>alert(\"" . $message . "\"); window.history.back();</script>";

OR

echo '<script>alert("' . $message . '"); window.history.back();</script>';
pavel
  • 26,538
  • 10
  • 45
  • 61
  • This will not affect the content in `$message` – Gerald Schneider Apr 23 '15 at 08:52
  • 1
    @GeraldSchneider: when you downvote something, you should be sure it isn't the solution. Did you try it before you downvoted? Of course it works, that's how JS interprete escaped chars like `\n, \r, \t`, etc. – pavel Apr 23 '15 at 10:21
  • As a matter of fact I did try it. Your suggestion would work if you applied it to the definition of `$message`, as yergo did in his answer. But this way `$message` is echoed verbally, including the newlines which break the javascript code. – Gerald Schneider Apr 23 '15 at 11:32
  • 1
    @GeraldSchneider: if in HTML, which is generated from PHP, will be `alert("whatever \n content...")`, in alert will be two lines. Doens't matter if text in alert comes from PHP or not. – pavel Apr 23 '15 at 11:34
0

You need to use Line feed + Newline

\r\n

and that will work as shown in the following script:

echo "If you view the source of output frame \r\n you will find a newline in this string.";
echo nl2br("You will find the \n newlines in this string \r\n on the browser window.");
Michael Haephrati
  • 3,660
  • 1
  • 33
  • 56
Amr Angry
  • 3,711
  • 1
  • 45
  • 37