User999999
User999999

Reputation: 2520

JSON: Handle linebreaks (and other invalid JSON-Chars)in textArea

On an HTMl i have a textarea (a comment box) (id = #comment") that can contain multiple lines. When I send it through with ajax i have no problems. Although when retrieve this data, the JSON-data is no longer valid(below a minor extract of json:

"items" : [  {  
     ...<<other values>>...,
     "comment": "Approved!!!!

     Or Not

     Or Did I


     Approve this....." 
     ,...<<other values>>...}

So i assumed I'd had to convert the value of my textarea when sending it to the server. But when i tried using JSON.Parse I got an error:

$.ajax({
    type: "POST",
    url: "updateitem.aspx",
    data: {
        myId: $("body").attr("id"),
        comment: JSON.parse($("#comment").val()),
    }
    ...
})

But this results an error:

SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data
comment: JSON.parse($("#comment").val()),

So my question really is: How can send the data from an textarea to the server. While preserving any non-JSON characters & linebreaks. The solution is probably simple but the only this i seem to find are: Past JSON in textarea, ReplaceAll (which could work but i'm searching for a better solution)

Tried the following solution but to no avail. how-can-i-pass-textarea-data-via-ajax-that-contains-ampersands-and-or-linebreaks

Upvotes: 2

Views: 1325

Answers (1)

SnakeDrak
SnakeDrak

Reputation: 3642

You need use JSON.stringify for this:

var comment = JSON.stringify($("#comment").val());
        
// Now comment is a JSON string to send to your server

$.ajax({
    type: "POST",
    url: "updateitem.aspx",
    data: {
        myId: $("body").attr("id"),
        comment: comment,
    }
    ...
})

See the jsfiddle: http://jsfiddle.net/14cjojhq/1/

Upvotes: 1

Related Questions