Link to home
Start Free TrialLog in
Avatar of dignified
dignified

asked on

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
world
this is me"

and the browser hangs.

How do I get around this?
Avatar of Richard Quadling
Richard Quadling
Flag of United Kingdom of Great Britain and Northern Ireland image

Try converting the physical \r and \n into "\r" and "\n"...

In PHP ...

<?php
$s_Text = <<<END_TEXT
Line 1
Line 2
Line 3
END_TEXT;
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!
ASKER CERTIFIED SOLUTION
Avatar of dignified
dignified

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial