php - Why do I get instead of a new line getting data from AJAX?

956

I have a problem: so I have a data thats coming out of the database and stored in a text area. When the user changes the data in the text area, the content is sent to javascript and via AJAX (POST to a PHP script) the database is updated. This works fine until the user starts adding newlines. Then javascript transforms this into a \n-character and thus it gets stored in the database as \n.

What I want is to have actual newlines in my database and not the \n newline-characters. Is there any way that I can use php to replace the \n with an actual newline (NOT a br)? I have tried altering the database field after the edit with the char(10), but for some reason this is not working in the script except when I do it manually in phpmyadmin?

When editting with a full php request, the newline in a text area is correctly stored as a char(10) in mysql, not as \n.

Anyone got a clue?

166

Answer

Solution:

Store it as it is but escape first with real_escape_string

real_escape_string converts what is a newline into the 4 character string '\n\r'

$text = $mysqli->real_escape_string($text);
547

Answer

Solution:

Use[nl2br][1] function to replace/n with newline

Insert line breaks where newlines (\n) occur in the string:

<?php
echo nl2br("One line.\nAnother line.");
?>

The browser output of the code above will be:

One line.
Another line.

People are also looking for solutions to the problem: javascript - PHP Mysql query - allow user to filter results

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.