April 12, 2012
Escape all special characters in a string that is sent by jquery ajax
Question by developer747
I am trying to send text in key value pairs while doing a contentType: "application/json; charset=utf-8",
ajax post to a web service. The problem I am facing is that if one of the parameters (that accepts text from the user) has quotes (“) it breaks the code [Eror message: Invalid object passed in ] . So far I have tried these without any success
var text = $("#txtBody").val();
var output1 = JSON.stringify(text);
var output2 = text.replace(/[-[]{}()*+?.,\^$|#s]/g, "\$&");
Any ideas on how to escape the special characters for the jquery ajax post?
Answer by Trevor
Answer by Starx
There is already a function escape(var) which helps you escape the values. It should be enough for the purpose you are talking about
var output2 = escape(text);