I am facing an issue where my Ajax POST calls are failing when I attempt to assign complex JavaScript objects to the [data] key/value pair after using JSON.stringify() for serialization.
Could anyone advise on what additional ajax call configuration is required in order to successfully send a POST message with a JavaScript object serialized using JSON.stringify()?
I have a strong suspicion that there might be a small configuration detail missing, but despite researching and testing, I have been unable to pinpoint the problem. The failure occurs even with basic Javascript types such as Objects and Arrays.
I have confirmed that the remote web service can handle POST calls with simple data successfully.
The remote web service has also shown capability of responding to POST calls with data up to 22MB in size.
This error behavior persists across different browsers.
In my code snippet, [MSG No. 1] always executes without issues.
However, [MSG No. 2] consistently fails.
function stackoverflowAjaxPostCall() {
// The remote service is a WCF (REST) web service and performs as expected with one exception
//var url = "http://localhost/GenericWebService/GenericWebService.svc/SaveChanges";
// MSG No. 1 - This message works reliably and verified to work end-to-end with 22MB of "remarks" info
var messageToBeSent = "{ name: 'PostMyChanges', remarks: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}";
// MSG No. 2 - Simple Javascript object reliably fails with Client Side Error 400 (Bad Request)
// Stringify Output = {"name":"PostMyChanges","remarks":"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
//var messageToBeSent = new Object();
//messageToBeSent.name = 'PostMyChanges';
//messageToBeSent.remarks = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var serializedJson = JSON.stringify(messageToBeSent);
console.log(serializedJson);
console.log("Data Size: " + serializedJson.length);
$.ajax(url,
{
type: "POST",
contentType: "application/json",
dataType: "json",
data: serializedJson,
//contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15", // Fails with or without
success: function (response) { console.log("Success: " + response); },
error: function (e) {
var inspectIt = e;
console.log("POST Call - Error occurred");
console.log("Response Length: " + e.responseText.length);
}
}
);
// Successful Remote Service Call Response = "{name:'SavedChanges',remarks:'Reached REST service entrance'}";
}