The question is:
How to save user input linebreak to database. (jQuery/php/mysql)
I have a paragraph which is editable by the user.
<p contenteditable="true" id="forbiddenField">Text</p>
When I retrieve data from db with this:
<p contenteditable="true" id="forbiddenField"><?php echo nl2br($forbidden); ?></p>
and that works great.
onblur (.blur) will activate a jQuery script which will send the new edited data to a database.
$("#forbiddenField").blur(function(){
var whatIsNowForbidden = encodeURI($("#forbiddenField").text());
$.ajax({
type: "POST",
url: "updateForbidden.php",
data: "forbiddenStuff="+ whatIsNowForbidden,
success: function(){
}
});
});
Problem:
If the user inserts new data, with linebreaks, then the linebreaks are not added to the data in the database, only the content is added.
I tried this among other things:
var whatIsNowForbidden = encodeURI($(“#forbiddenField”).text());
I looked at theese places for answers:
New Line in Textarea to be converted to <br/>
http://www.w3schools.com/tags/ref_urlencode.asp
Is replacing a line break UTF-8 safe?
how to escape input but save unescaped into the database
How to recognize every linebreak?
I can’t get it to work.
All input and hints are much appreciated!
Try removing the
encodeURI()function from your javascript, like so:I made a fiddle to test this and javascript’s
encodeURI()function doesn’t seem to translate the new lines made in the paragraph to%0A, like we were expecting to.By removing the function
encodeURI()PHP should be able to save the text, including new lines, to the database. And then, PHP’snl2br()should transform the new lines into<br />tag’s with no problem.The fiddle is available here: http://jsfiddle.net/LN7QC/
Final answer: use
<textarea>The jQuery:
adding to database:
fetching from database:
on the site: