Reputation: 13850
I got problem with line breaks in a textarea.
I get the text with .val() function:
var messageBody = $('#composeInput').val();
This is my ajax request
$.ajax({
url: 'serverScripts/messages/addMessage.php',
data: 'messageBody='+messageBody+'&invitedJSONText='+invitedJSONText,
success: function(){
//Do something
}
});
And PHP:
$messageBody = nl2br(mysql_real_escape_string($_GET['messageBody']));
The text:
Hi!
How are you?
Becomes:
Hi! How are you?
If I insert the variable messageBody to an another div-element I can't see any \n is this normal. How do I fix this?
Upvotes: 4
Views: 9803
Reputation: 272256
When the data
parameter is passed as a string, you must URL encode it yourself:
'messageBody=' + encodeURIComponent(messageBody) + '&invitedJSONText=' + encodeURIComponent(invitedJSONText)
But it is far more simpler to pass the data
parameter as an object; jQuery encodes the data automatically:
$.ajax({
url: 'serverScripts/messages/addMessage.php',
data: {
messageBody: messageBody,
invitedJSONText: invitedJSONText
},
success: function (data, textStatus, jqXHR) {
$("#foo").html(data); // <-- did something
}
});
PS: instead of nl2br
you can set CSS white-space
property to pre-line
on an element to display newline as newline.
Upvotes: 15
Reputation: 474
Is not that a known issue? http://api.jquery.com/val/
The workaround is using valHooks as explained in the Note section.
Upvotes: 0
Reputation: 15835
You may want to look at PHP's nl2br function. Newlines characters do not render in the browser, so you have to replace them with line breaks.http://us.php.net/nl
Upvotes: 0