Yesterday, while presenting at the UKCFUG, a question was asked:
"How can I get ColdFusion to return me jSON encoded data, when I am still on version 7 and then use that data in jQuery?"
Well, I said I would blog the answer so it would be nice and clear, and this is that blog post.
In a nutshell, anything javascript loves jSON, the Javascript Object Notation (javascript speaking natively in simple terms). However, while in ColdFusion 8 you can easily get CFC's to return jSON encoded data, ColdFusion 7 did not include this, so we need to get a little more imaginative. Whilst not impossible by any means, it is definitely a little more tricky than in CF, so use that if you can.
To start off with, you obviously need some sort of function to get you your data to return to jQuery. Something like this should do:
[The requested file http://neilmiddleton.com/Mods/http://neilmiddleton.com/Mods/2008/02/cf 7_datasource.txt could not be found]
Now, thats a pretty simple function, nothing special at all. So how is this invoked? Well, one way of doing it is to create a gateway CFM file that calls your method and returns the result to the page (and this is by no means the only way). However, for this to render the data on the page it needs to convert it to something that takes the form of a string (jSON perhaps?). This is where you need to look at 3rd party code as there is no serializeJSON function in CF7.
Luckily, there is just such a bit of code, jSON.cfc . By using this we can convert pretty much anything into a jSON string for display. Like so:
[The requested file http://neilmiddleton.com/Mods/http://neilmiddleton.com/Mods/2008/02/cf 7_datagateway.txt could not be found]
So, now we have a URL that gives me some jSON data. All that is left is to write the jQuery to get this data and handle it. Luckily for us, that's real simple too:
[The requested file http://neilmiddleton.com/Mods/http://neilmiddleton.com/Mods/2008/02/cf 7_jsonscript.txt could not be found]
Put all this together (with Firebug in Firefox) and you should see the variable you set in CF appearing in your browser.
Now as I said, there are other ways of doing this, so have a think about what you're trying to do and you could probably find at least five other ways.
If you want to download jSON.cfc, it can be found here:


Thanks for doing the seminar last night. A light bulb went on for me and I spent today converting a 500kb cf8 login page (with cfwindow) into a jquery page with some tabs thrown in for good measure that weighed in a 87kb!! The colourcharge png is proving really useful!!
Hi Neil, I am learning how to use jquery to populate multiple drop down menus without refreshing the page. I was reading your article and was hoping to get some example to start with. However, I cannot get the files you posted.
[The requested file http://neilmiddleton.com/Mods/http://neilmiddleton.com/Mods/2008/02/cf 7_datasource.txt could not be found]
Can you please email me the files?
Thanks much,
kiki