This is a topic I cover pretty often, but as I still get emails about it I figure it doesn't hurt to repeat myself. One of the number one reasons folks have issues with Ajax and ColdFusion is the use of Application.cfc and onRequestStart. If you output anything in onRequestStart, like a header, or a footer (in onRequestEnd obviously), it will always output, even when you make requests to CFCs. Let's look at a quick example of this.

I'll begin with my front end fancy Ajax application. It's incredibly complex. It's going to use jQuery to call a CFC method that returns an array. It will take the array and make a nice UL out of it. Here's the code.

<html>

<head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(document).ready(function() { $.post("test.cfc?method=getarr&returnformat=json", {}, function(res,code) { var s = "<h2>Results</h2><ul>"; for(var i=0; i<res.length; i++) { s+= "<li>"+res[i]+"</li>"; } s+="</ul>"; $("#result").html(s); },"json"); }) </script> </head>

<body> <div id="result"></div> </body> </html>

The CFC is trivial, but for completeness sake, here it is:

component {

remote array function getArr() { return [1,2,3]; }

}

(By the way, to the person who just called ColdFusion "tag soup" on Twitter... suck it.) Ok, if everything works, we should see this:

However, when I ran my code I saw this instead:

Global Corp? Eh? Turns out I had an Application.cfc file and I used onRequestStart to output a header for all my files:

component {

this.name="root"; public boolean function onApplicationStart() {
return true;
}

public boolean function onRequestStart(string req) { writeOutput("<h1>Global Corp!</h1>"); return true; } }

The problems becomes more apparent when you make use of Chrome Dev Tools or Firebug. And folks, again, please please please please make use of these tools. You cannot, should not, must not, do Ajax development without them. Look at what my CFC returned:

You can see the header being output before the CFC. This is not a bug. You told ColdFusion to output the text on every request. Luckily it is easy enough to fix.

public boolean function onRequestStart(string req) { if(listLast(arguments.req,".") != "cfc") writeOutput("<h1>Global Corp!</h1>"); return true; }

I hope this helps (even if a repeat). As a reminder, I tend to recommend against using onRequestStart/End for templates just for this reason.