I am trying to post data using ajax in jquery of json datatype. I am using json’s stringify method to avoid single quote but It is not doing so for one value but doing other value. I am confused. I tried using replace function also but no use.
Following is my jquery code,
$.ajax({
type: "POST",
url: "<%=ResolveUrl("~/QualityComplaintService.asmx") %>/DoesVariantExists",
contentType: "application/json; charset=utf-8",
data: "{categoryId: '" + category.val() + "', subcategoryId: '" + subcategory.val() + "', brandId: '" + brand.val() + "', variant: '" + variant.val() + "'}",
dataType: "json",
success: function(msg) {
var d = msg.d;
if (d == true)
{
alert("Variant already exists! Please choose another one.");
return false;
}
else
{
var parameter = {
categoryId: category.val(),
subcategoryId: subcategory.val(),
brandId: brand.val(),
size: size.val(),
variant: variant.val(),
chkIsActive: chkActive
};
$.ajax({
type: "POST",
url: "<%=ResolveUrl("~/QualityComplaintService.asmx") %>/RegisterVariant",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parameter),
dataType: "json",
success: function(msg) {
__doPostBack('<%=btnAdd.ClientID.Replace("_", "$") %>','');
}
});
}
}
});
When I run the above code, I can insert single quote in size field but when I insert single quote on variant field i get error. But are of same datatype. What can be the problem?
In your first AJAX request you have the following line:
which obviously should be replaced with
JSON.stringifyto avoid the horrible string concatenation which will break as soon as one of the parameters contains some special characters such as a single quote:Your second ajax call seems fine as you are properly using the
JSON.stringifymethod.