Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submission with single quotes using jQuery, Ajax and JSON

I've looked around, and I'm trying to find an elegant solution to this, and I'm yet to find one. I have an ASMX web service in .NET that I'm trying to call that requires parameters.

I'm using jQuery on the client side to call the service and my jQuery code looks something like this:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "/Reviews/HotelReview.asmx/SubmitReview",
    data: "{'name': '" + name + "', " +
        "'info': '" info + "'}",
    processData: true,
    beforeSend: function() { startSubmit(); },
    complete: function() { submitComplete(); },
    error: function(xhr) { submitError(xhr); },
    success: function(msg) { submitSuccess(msg.d); }
});

It works very well, except when either name or info contain the ' character, a single quote. Simple enough, because my JSON defines the end of the value of the field and is a single quote. When either of these fields contains a single quote, all I get is an "Internal Server Error", but further inspection using Fiddler showed me the results (I won't bother to post them) indicating the single quote issue.

I've put something in place temporarily to remove the single quotes on the client side and put them back in on the server side, but this is far from elegant. Is there a more elegant way to escape these single quotes so that my code can work?

like image 289
Odd Avatar asked Aug 20 '09 00:08

Odd


1 Answers

The specifications say that in JSON you can only use double-quotes around keys and values so try it with double quotes. I am pretty sure your error will be solved.

You may want to use json.js to encode / escape special characters in the actual values so you don't run into problems with values containing " for instance, or the stringify method from http://www.json.org/js.html.

like image 109
olle Avatar answered Nov 09 '22 13:11

olle