1

Ajax POST calls fail when I assign low-to-complex JavaScript objects to the [data] key/value pair after being serialized using JSON.stringify().

Question – What additional ajax call configuration is needed to successfully send a POST message with JavaScript object serialized with JSON.stringify()?

I strongly suspect some small configuration item is missing, but I have not been able to identify the issue in my research and testing. The call fails on the simplest of Javascript types, e.g., Objects, Arrays, etc.

  • Verified the remote web service can respond to POST calls with simple data.

  • Verified the remote web service can respond to POST calls with at least 22MB of simple data.

  • The same error behavior is observed across different browsers.

  • Referencing the code snippet, [MSG No. 1] always succeeds.

  • Referencing the code snippet, [MSG No. 2] always fails.

function stackoverflowAjaxPostCall() {

// The remote service is a WCF (REST) web service and performs as expected with the 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'}";

}

  • The first message is not a valid json, and when you passe it to JSON.stringify it will give also a not valid JSON, may be the server refuse the JSON content type. – Shakir El Amrani Aug 18 '20 at 23:08

1 Answers1

0

The root cause was a JSON message formatting issue. The object that I stringify is magnitudes more complex than the sample and included characters that caused the [data] to be rejected with a generic 400 StatusCode.

I resolved the issue by replacing/reformatting the problem back slashes, forward slashes, and double quotes. I added the code below. The [saveRequestData] can be used directly by [data].

var messageData = JSON.stringify(messageToBeSent);
messageData = messageData.replace(/[\\]/g, '\\'); // Black slashes 
messageData = messageData.replace(/[/]/g, '\\/'); // Foward slashes
var saveRequestData = messageData.replace(/["]/g, '\"');  // Double quotes 

Replace Both Double and Single Quotes in Javascript String

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

https://mathiasbynens.be/notes/javascript-escapes