Today I attempted to send a giant amount of user-entered text from a standard HTML page, via jQuery's .ajax() method - passing a jSON packet to a REST-enabled WCF service.
It was failing.
Turns out the newlines were destroying the jSON formatting, so I needed to find a way to preserve the information for the server. I ran across a blog post dealing with this here, and he suggested the following bit of code:
function escapeNewLineChars(valueToEscape) {
if (valueToEscape != null && valueToEscape != "") {
return valueToEscape.replace(/\n/g, "\\n");
} else {
return valueToEscape;
}
}
It didn't work.
Turns out, after fiddling with it, the "replace with" value needed to be wrapped in single (not double) quotes. So, in order to prepare your text for transmittal via jSON, try this:
function fixMyUserEnteredData(giantBlobOfText) {
giantBlobOfText = $.trim(giantBlobOfText.replace(/\n/g, '\\n')); // converts the newlines and trims the string
return giantBlobOfText.replace(/\"/g, '\\"')); // converts all double quotes
}
That did the trick.