I've got a PHP/Mysql app that lets users post text from a form. When I insert text from an HTML textarea into my mysql table, it's not keeping the carriage returns/line breaks. The text is not stored in the DB as "Hey SO, \n This is a new line". It's stored with white space in the column (exactly like it's typed), but there is no way for me to output it with nl2br()
and keep the breaks. I'm escaping before inserting the text like so:
$foo_text = mysql_real_escape_string(ucfirst($_POST['foo_text']));
But even if I remove everything and just use the POST parameter, it still does the same thing. Would this have anything to do with me serializing and posting this form via ajax (I'm using JQUERY)? I found this on stackoverflow, but I don't really see a solution. I'm posting with:
$.ajax({
type: "POST",
url: "insertFooBar.php",
data: $("#foo_form").serialize(),
success: function(msg) {
ETC...
}
})
Is there something really obvious I'm missing here? I'm stuck...
Thanks in advance for any help!
The problem is that serialization should encode a line break as %D0%DA, but jQuery encodes it as %0A.
The only (graceless) solution i found was to get the form serialized string, then modify it with a replacement function such as :
function keepLB (str) {
var reg=new RegExp("(%0A)", "g");
return str.replace(reg,"%0D$1");
}
Once the serialized string is modified, i send it using the $.post() function.
Hope it will help !
Thanks for the answers. I ended up removing the serialize() and sending each parameter manually as a string. I added $("#foo_bar").replace( /\n/g, '<br>' ))
to my textarea as a workaround and now I'm getting my breaks. Wish I didn't have to hack this to make it work, but it gets the job done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With