Returning XML in ColdFusion for AJAX

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:

<cffunction name="test" returnType="string" access="remote" output="false">
	<cfset var xml = "">
	<cfxml variable="xml">
	<cfreturn xml>

Viewed in your browser, the result is:

<wddxPacket version='1.0'><header/><data><string><?xml version="1.0" encoding="UTF-8"?><char code='0a'/><root><char code='0a'/><char code='09'/>
<char code='09'/><people>ray</people><char code='0a'/><char code='09'/>
<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:

<?xml version="1.0" encoding="UTF-8"?>

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.

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:

<cfcontent type="text/xml">	
<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.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA