Most of my AJAX calls just work with the daya attribute in jQuery to pass singular values. But sometimes I need to pass a structure in JSON to the server for further processing. I know how to, I know it works. But it seems to work only 90% of the time.
The setup is Railo 4.2 and IIS, both have most of their settings still as default. I'm also unable to reproduce this locally, where I have Coldfusion server instead of Railo. I'm also working in the Coldbox framework.
The jQuery code that sends the JSON data is as follows:
var oJSON = {'param1': param1, 'param2': param2, 'param3': param3};
$.ajax({
type: "POST",
url: uAjax + "?action=someurlparameter",
data: JSON.stringify(oJson),
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(oData)
{
// do something
}
});
The Coldfusion CFC that handles the incoming data does the following:
<cffunction name="cashup" returntype="struct" output="false" hint="handle json data">
<cfargument name="event">
<cfargument name="rc">
<cfargument name="prc">
<!--- get json data --->
<cfset LOCAL.oJson = deserializeJSON(toString(getHttpRequestData().content)) />
<cfreturn someService.someProcessing(LOCAL.oJson) />
</cffunction>
This seems pretty straight forward code to me. But for some reason 10% of the time these calls fail because the request body is empty. And I have no clue why. It can't be the data that is being sent, because clicking the button again, without refreshing the page, and thus retrying the ajax call, most of the time results in a good call, on that comes through WITH a filled request body.
edit 1:
sample data in json:
"MoneyLocation": {
"MoneyLocationPaymentTypeCountList": [
{
"Amount": 175.28,
"Description": "CASH ",
"IdPaymentType": 2,
"ImageLocation": ""
},
{
"Amount": 0,
"Description": "Generieke bon ",
"IdPaymentType": 62,
"ImageLocation": ""
}
],
"IdTill": -1,
"IdMoneyLocation": 35
}
Working with a couple of other people on the Railo Google Group we've discovered that somewhere during the request the request body gets lost in time and space. sometimes. and very randomly. I'm no longer the only person to have experienced this issue and we've foudn that initially the request body is filled with the expected value.
By adding the following code to you onRequestStart() method in your application.cfc, you can again be sure of the values to expect in your request body:
request._body = ToString( GetHttpRequestData().content );
This is by no means a permanent solution. It poses no longer a threat to the integrity of the coldfusion application, but there is still something going awry behind it all. If we ever find out what is going on, I'll make sure to update this answer.
I also don't want to take credit for this bypass, I've not found this out myself. The good folks over at the Railo Google Group have pointed me in the right direction. But I want to be able to provide an answer to the question posed on stackoverflow as well.