Posted in ColdFusion | Posted on 02-08-2007 | 7,026 views
I've blogged this before, but only as a side point. Since the question came in to me this morning I thought I'd mention it again in a new post. The question is simple - how do you return XML data in ColdFusion to be consumed by AJAX? (Or really any source.)
First off - if you want to return XML from a CFC method, you have to use returnType="xml". If you do not, the result will be WDDX encoded. Consider this method:
2 <cfset var xml = "">
3 <cfxml variable="xml">
4 <root>
5 <people>ray</people>
6 <people>jeanne</people>
7 </root>
8 </cfxml>
9 <cfreturn xml>
10</cffunction>
Viewed in your browser, the result is:
2<char code='09'/><people>ray</people><char code='0a'/><char code='09'/>
3<char code='09'/><people>jeanne</people><char code='0a'/><char code='09'/><char code='09'/></root></string></data></wddxPacket>
(Note, I added a line break or two so it wouldn't break the site layout.)
If you switch the returnType to XML, you then get:
2<root>
3<people>ray</people>
4<people>jeanne</people>
5</root>
So far so good. Before I go on - a quick note. You have to actually return an XML string or XML object. You can't just return a query and expect the returnType="xml" to convert it for you. That would be nice probably. (If you need an easy way to create XML, check out toXML.)
What if you don't have ColdFusion 7? First - buy it and mention my name! If you must use ColdFusion 6, create a ColdFusion page called proxy.cfm. This CFM file will call your CFC and then return the XML. Here is an example taken from BlogCFC:
2<cfoutput>#queryToXML(entries, "entries", "entry")#</cfoutput>
In this case, I used a UDF to convert a query into an XML string. I use cfcontent to let the browser know XML is being returned. As a last step, I set up my AJAX front end to hit proxy.cfm instead of the CFC.


I do have one request can you show how to update a cf page through Spry with out reloading the page like on this page check your email i sent you the source code.
http://www.johnramon.com/checklink.cfm
Set the returntype="void" and output="yes" then output the XML just as you would in a .cfm page.
cfcontent is still required. It is a bit hacky, but it works.
Of course, you can also use JSMX to digest the WDDX that a CFC method returns by default.
http://steve.coldfusionjournal.com/jsmx__another_a...
One of the subtopics was returning XML.
http://www.ncfug.com/index.cfm?fuseaction=dspArchi...
Anyway, the point of this moan is that Spry is not easy to integrate with at all and has little CF resource to help.
I have only been able to get Spry working when I create the XML using cfsavecontent in a cfm file! I cannot get a call to a cfc working or indeed via my fusebox framework! I'm sure I am missing something, but this frustration serves to weaken my opinion of Spry.
Has anyone integrated Spry with Fusebox, if so can you help?
[Add Comment] [Subscribe to Comments]