3

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!

Community
  • 1
  • 1
Alisso
  • 1,861
  • 1
  • 17
  • 32
  • First things first: Are you sure the carriage return's aren't being saved in the database? Also, how are you making your paragraph (`

    `) editable?
    – Telmo Marques Dec 30 '11 at 00:54
  • What takes the space of the linebreaks? Spaces? Tabs? Nothing? – sarnold Dec 30 '11 at 01:09
  • contenteditable="true" inside the

    makes it editable :)

    – Alisso Dec 30 '11 at 01:40
  • May I ask what: "carriage return's" means? – Alisso Dec 30 '11 at 01:40
  • also not sure what you mean by "What takes the space of the linebreaks?" If i do an alert(); of the value of the paragraf I get: alert(encodeURI($("#forbiddenField").text())); The text: Föbjudet: allt som inte är tillåtet. (Forbidden: All that is not allowed) Another line down here. gives: F%C3%B6bjudet:%20allt%20som%20inte%20%C3%A4r%20till%C3%A5tet.%20(Forbidden:%20All%20that%20is%20not%20allowed)Another%20line%20down%20here. – Alisso Dec 30 '11 at 01:41
  • A carriage return is a control characater that, when used toghether with the line feed character, represents the beginning of a new line (See more here: http://en.wikipedia.org/wiki/Carriage_return). Could you perhaps show us the website where we can see the input and output behaviour of the application? Also, your URL encoding function is not representing the line feeds (%0A), if you're using that function to save it's output on the database that might be the problem right there. – Telmo Marques Dec 30 '11 at 02:50
  • Looking to your code again, the `encodeURI()` function might well be the problem. Please see my answer. – Telmo Marques Dec 30 '11 at 03:16

1 Answers1

0

Try removing the encodeURI() function from your javascript, like so:

var whatIsNowForbidden = $("#forbiddenField").text();

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's nl2br() 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:

$("#forbiddenField").blur(function(){
        var whatIsNowForbidden = $("#forbiddenField").val();

        $.ajax({
            type: "POST",  
            url: "updateForbidden.php",  
            data: "forbiddenStuff="+ whatIsNowForbidden,
            success: function(){
            }  
        });
});

adding to database:

<?php
    include('connect.php');

            if($_POST['forbiddenStuff']){
                $forbiddenInput = $_POST['forbiddenStuff'];
            }


    If($forbiddenInput){
        mysql_query("SET NAMES 'utf8'");
        $changeDataInDB = "UPDATE heroes_and_helpers SET forbidden='$forbiddenInput' WHERE name ='sabina'";
        mysql_query($changeDataInDB);

    }
?>

fetching from database:

   mysql_query("SET NAMES 'utf8'");
    $fetchForbidden = mysql_query("SELECT * FROM heroes_and_helpers WHERE name='sabina'");

        if (!$fetchForbidden)
          {
          die('Ngt ar fel: ' . mysql_error());
          }

    $whatIsForbidden = mysql_fetch_array($fetchForbidden); 
    $forbidden = $whatIsForbidden['forbidden'];

on the site:

<textarea id="forbiddenField" style="width: 450px; height: 500px;"><?php echo $forbidden; ?></textarea>
Alisso
  • 1,861
  • 1
  • 17
  • 32
Telmo Marques
  • 5,066
  • 1
  • 24
  • 34
  • It didn't work for me. Does it matter that I'm working on localhost? – Alisso Dec 30 '11 at 15:22
  • It shouldn't matter. Might we see the updateForbidden.php file code? – Telmo Marques Dec 30 '11 at 16:14
  • How about if you echo the value of `nl2br($forbiddenInput);` directly, without passing through the database, will it work? – Telmo Marques Dec 30 '11 at 16:44
  • 1
    Also, try to change the paragraph to a ``... I'm getting some really weird behavior from the paragraph. `encodeURI()` seems to encode the newlines in a textarea, but not in the paragraph. http://jsfiddle.net/LN7QC/1/ – Telmo Marques Dec 30 '11 at 16:48
  • 1
    Everything works great with – Alisso Dec 31 '11 at 01:19
  • You're welcome! Just a final observation, you should sanitize your SQL query before executing it to prevent [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection). You can use [Prepared Statements](http://php.net/manual/en/pdo.prepared-statements.php) or, a faster alternative, using the `mysqli_real_escape_string()` function. For example: `$changeDataInDB = "UPDATE heroes_and_helpers SET forbidden='"+mysqli_real_escape_string($forbiddenInput)+"' WHERE name ='sabina'";`. Glad I could help! – Telmo Marques Dec 31 '11 at 01:50