Reputation: 2197
I have a page saving some data from textboxes to the back end using a jquery ajax call thus:
function saveAsYouGo(){
$.ajax({
type: "POST",
url: "Report.aspx/SaveReport",
data: "{'EditorHTML': '" + _sftabs_rTxtRep.GetHTML() + "', 'Actions' : '" + GetActions() + "', 'Notes': '" + GetNotes() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
lastHTMLVal = _sftabs_rTxtRep.GetHTML();
alert(msg.d);
}
});
}
the GetActions and GetNotes basically just grab the text from a number of textboxes along the lines of this
function GetActions(){
var na = [];
$('#optionsTable :checkbox:checked').each(function(){
var textVal, idVal;
textVal = $(this).parent().parent().next("td").find("textarea").val();
idVal = $(this).attr("id");
if(textVal != ""){
na.push(idVal, textVal);
}
});
return na;
}
but when there are quotes etc in the textareas it busts the ajax call. I have looked a bit for JSON.stringify but this doesnt seem to make any difference. I assume that there is a way to encode the text before sending , so that I can unencode it at the other end before doing what needs doing..?
as ever any help very happily received thanks
EDIT found these little gems which help for most things
function htmlEncode(value){
return $('<div/>').text(value).html();
}
function htmlDecode(value){
return $('<div/>').html(value).text();
}
however the above DO NOT WORK for dealing with quotes as far as I can tell and the below which suggested ditching the quotes around the data elements, didn't work at all.
data: {'EditorHTML': _sftabs_rTxtRep.GetHTML() , 'Actions' : GetActions(), 'Notes':GetNotes()},
any other ideas? this is driving me potty
EDIT 2
just ended up wrapping the textVal in an escape thus:
if(textVal != ""){
cn.push(idVal, escape(textVal));
}
thanks
nat
Upvotes: 1
Views: 1623
Reputation: 342635
Instead of passing a JSON string, just pass an object and jQuery should correctly encode it for submission:
data: {'EditorHTML': _sftabs_rTxtRep.GetHTML(), 'Actions' : GetActions() , 'Notes': GetNotes() }
From the $.ajax
manual (under the data
option):
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Upvotes: 2