CFC, returnForm, JSON, and content-type

I could have sworn that in ColdFusion 9, when asking a CFC to return JSON data with returnFormat=json, that ColdFusion used a response type of application/json. However, it looks like this is not the case. Maybe this behavior changed or maybe I just assumed wrong, but I’m definitely seeing an incorrect content type. Here is a quick example and a possible fix.

First, a simple CFC with two remote methods:

component { remote function getone() { return 1; } remote function gettwo() { return 2; } }

And then a quick front end client for it:

<cfajaxproxy cfc="test" jsclassname="theproxy"> <script> var foo = new theproxy(); var result = foo.getone(); alert(result); var result = foo.gettwo(); alert(result); </script>

When I check the response types in Chrome, I see...

So, in my particular case, I had a core CFC that my remote CFCs extended. I was able to add this to the constructor area and it worked fine:

<cfcontent type="application/json">

It just so happened that my base CFC was tag based so that worked ok. So what about script? This code works fine:

response = getPageContext().getResponse(); response.setContentType("application/json");

But oddly, when placed in the constructor area of my CFC above, it made everything use that content type, ie both the CFM and the CFC. That seemed odd. I'm assuming cfajaxproxy actually ran the CFC when creating the proxy. This seems to be an issue with cfajaxproxy only though. I changed my front end to a simple jQuery version and it worked fine. Here is my front end now and the CFC after.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(document).ready(function() { $.get("test.cfc?method=getone&returnformat=json",{}, function(res) { alert(res); },"json"); }) </script>

component { response = getPageContext().getResponse(); response.setContentType("application/json"); remote function getone() { return 1; } remote function gettwo() { return 2; } }

One last tip. This is something I learned from Mark Drew a long time ago. Don't forget that CFCs can also use the constructor area to preselect a method returnformat. So in the CFC above, I can also do:

url.returnformat="json";

What's nice then is that people calling my CFC don't have to bother specifying it.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments