• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3483
  • Last Modified:

JSON and Fields with Carriage Returns

I am using JSON with AJAX. There are two problems when sending data from a textarea.

1) If there is no carriage return manually entered in the text area, the last line is not inserted into the database

2) when reading the data back from the db, the JSON looks something like this:
{textareadata : "hello
this is me"

and the browser hangs.

How do I get around this?
1 Solution
Richard QuadlingSenior Software DeverloperCommented:
Try converting the physical \r and \n into "\r" and "\n"...

In PHP ...

$s_Text = <<<END_TEXT
Line 1
Line 2
Line 3
echo json_encode($s_Text);

outputs ...

"Line 1\r\nLine 2\r\nLine 3"

I'm on windows, so \r\n is normal for me. On *nix systems \r only. Not sure about other OS's.
I usally replace \r and \n to the unicode line feed or a carriage return:   \u000A or \u000D.  So my code may look something like this:

string safeForJSON = unicodeReturn.Replace(escapeData, "\\u000A");

and my json data may look like this:
This is my json data. \u000A\u000AI am a scary badger...growl!
dignifiedAuthor Commented:
Only thing that worked was updating PHP and using their json_encode() function. MSIE was the big culprit having problems.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now