itsachen
itsachen

Reputation: 199

Textarea not updating when passed a string with a newline from POST?

I'm running into some troubles with my code, which I narrowed down and simplified in the two following segments:

index.html

<html>
<body>

<form name="form" method="post" action="upload.php" target="iframe">
<textarea id="text1" name="text1"></textarea>
<input type="submit" />
</form>

<textarea id="text2"></textarea>

<iframe name="iframe" id="iframe" style="display:none;" ></iframe>

</body>
</html>

upload.php:

<?php
$message= $_POST['text1'];

echo <<<_END
<script language="JavaScript" type="text/javascript">
var parDoc = window.parent.document;
parDoc.getElementById('text2').value = '$message';
</script>
_END;
?>

The overall goal of the code above is to present in text2, what I submitted from text1. This works with the exception of a message in text1 that contains newlines. When attempting to submit a message with newlines text2 is not updated. I can't seem to trace the error and I'm really stuck in a mental rut with this one. Any ideas? Again, this is a simplified version of my overall code. I whittled the error down to this problem.

Upvotes: 1

Views: 1507

Answers (1)

psx
psx

Reputation: 4048

Try this in upload.php

<?php
$message= nl2br($_POST['text1']);
$message = str_replace("\r\n",'',$message);

echo '
<script language="JavaScript" type="text/javascript">
var parDoc = window.parent.document;
var text = "' . $message . '";
text = text.replace(/<br \/>/ig,"\\n");
parDoc.getElementById("text2").value = text;
</script>';
?>

Upvotes: 2

Related Questions