Forum Moderators: open

Message Too Old, No Replies

Sending a textarea through Ajax, how to retain \n

         

csdude55

2:11 am on Oct 9, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a form that looks like this:

<?php
if ($_GET['confirm'] == 'true') {
$to = 'report@example.com';
$headers = "From: {$_COOKIE['user']} <$to>\r\n" .
'X-Mailer: php';
$subject = 'Whatever';

if ($_GET['why']) $body .= 'Why: ' . $_GET['why'] . "\n\n";
if ($_GET['summary']) $body .= 'Summary: ' . $_GET['summary'];

$body = stripslashes($body);

mail($to, $subject, $body, $headers);
}

echo <<<EOF
<form name="report" method="GET"
onSubmit="
var val;
for (i=0; i < 4; i++)
if (document.report.why[i].checked == true)
val = document.report.why[i].value;

$(#lightbox).ajax('$home/report.php?confirm=true&why=' + val + '&summary=' + this.summary.value);
return false">

Summary<br>
<textarea name="summary"></textarea>
</form>
EOF;


So if someone enters multiple lines in "summary", it should be delimited by \n or \r\n, right? I'm sending via plain text so I thought those would carry over to the mail, but by time it gets to the mail() function, I've lost those line breaks.

Any thoughts on how to keep those line breaks, so that the email I get has them in place?

csdude55

9:13 am on Oct 10, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



For future readers, the only way I could figure to do this was to convert the \n to <br> in the "onSubmit" of the form, then convert it back in the processing function.

<?php
if ($_GET['confirm'] == 'true') {

//// Converts the <br> in the URI to \n
$_GET['summary'] = str_replace('<br>', "\n", $_GET['summary']);
////

$to = 'report@example.com';
$headers = "From: {$_COOKIE['user']} <$to>\r\n" .
'X-Mailer: php';
$subject = 'Whatever';

if ($_GET['why']) $body .= 'Why: ' . $_GET['why'] . "\n\n";
if ($_GET['summary']) $body .= 'Summary: ' . $_GET['summary'];

$body = stripslashes($body);

mail($to, $subject, $body, $headers);
}

echo <<<EOF
<form name="report" method="GET"
onSubmit="
var val;
for (i=0; i < 4; i++)
if (document.report.why[i].checked == true)
val = document.report.why[i].value;

//// Converts the \n to <br> before sending, then encodes the whole thing for URI
var summary = this.summary.value.replace(/(\\r\\n|\\r|\\n)/g, '<br>');
summary = encodeURIComponent(summary);

$(#lightbox).ajax('$home/report.php?confirm=true&why=' + val + '&summary=' + summary);
////
return false">

Summary<br>
<textarea name="summary"></textarea>
</form>
EOF;