View Full Version : Alert box line breaks

05-06-2009, 07:29 PM
This is easy in Javascript, but somehow it is not recognized in PHP. I want to display an alert message but break up the message with line breaks. It works without the \n, but errors out when I include the \n.

The error is "unterminated string constant".

What is wrong with my syntax?

This works...

if (isset($_SESSION['error_messages'])) {
$error_messages = $_SESSION['error_messages'];
print "<script>alert('Errors were found!' + '$error_messages')</script>";

This does not work...

// Retreive error messages //
if (isset($_SESSION['error_messages'])) {
$error_messages = $_SESSION['error_messages'];
print "<script>alert('Errors were found!' + '\n' + '$error_messages')</script>";

This does not work either...

if (isset($_SESSION['error_messages'])) {
$error_messages = $_SESSION['error_messages'];
$m_message = "Errors were found!\n$error_messages";
echo "<script>alert('$m_message')</script>";

05-06-2009, 07:45 PM
Edit: Guy below me is correct, overlooked that :)

05-06-2009, 07:53 PM
Your problem is that PHP converts the \n to a line break before JS even gets it. Escape it and all will be well:

print "<script>alert('Errors were found!' + '\\n' + '$error_messages')</script>";

Alternatively, you could use single quotes in order to make PHP not care:

print '<script>alert("Errors were found!" + "\n" + "'.$error_messages.'")</script>';

05-06-2009, 08:05 PM
That worked! Thank you very much!

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum