I am mostly bogging this so I don't forget this stupid mistake I made. I am using jQuery to make an ajax call to a CFC. The CFC returns json data that I am using to populate a form.

The call worked just find and data was returned. However, for some reason, in JavaScript the JSON data was not being treated as JSON. I spent ages searching for solutions and doing trial and error.

This is the JavaScript call I was making:

view plain print about
1function getDetail(item){
2 $.ajax({
3 url: '/components/packages.cfc?method=getPackageByID',
4 cache: false,
5 type: "get",
6 data: {
7 packageid: item
8 },
9 success: function(data){
10 console.log(data.DATA);
11 }
12 });
13 }

This is the CFC that returned JSON.

view plain print about
1<cffunction name="getPackageByID" access="remote" returnformat="JSON" >
2        <cfargument name="packageid" required="true" type="numeric" >
3        
4        <cfset var getdata = "">
5        
6        <cfquery name="getdata" datasource="#request.dsn#" >
7            select * from package
8            where packageid = <cfqueryparam value="#arguments.packageid#" cfsqltype="cf_sql_integer" >
9        </cfquery>
10    
11        <cfreturn getData>
12    </cffunction>

Knowing what I know (which I started to question) I should have been able to use "data.DATA" to get to the JSON data in the result. However, when I output it to the console I would get "undefined". I also tried, among other things, "data[0]" which got me "{".

The lovely kicker was that the Chrome debugger network tab showed the call return as JSON.

I continued to try anything I could think of to get JavaScript to understand the return as JSON. All I ended up doing was finding a ton of ways to not process JSON.

Finally, I figured something out. It finally dawned on me that JavaScript was processing the data as a string not JSON. The "Intelligent Guess" feature of $.ajax() in jQuery was apparently failing to see the data as JSON.

I then added " dataType: 'json' " to the ajax call. Once I did that everything started working as expected.

If there is a moral here I would say it is to not expect data types to be auto assigned correctly. If you can, define what the data types will be. this will save you pain and anguish later.

Till next time...

--Dave