Debugging ajax calls with ColdFusion
I was debugging a video conversion application this afternoon that relies heavily on ajax to move the user along in the conversion process. After each step in the process another ajax call is fired off to continue to the next step. When things are working as expected it is a beautiful thing, when it does not things tend to get interesting. I had some code inside my CFC and the server was throwing a hard error, needless to say my response codes were never returned back to my ajax call from the remote method. The user would end up staring at a processing screen that would never go away.
To get around this I standardized all my ajax calls. No matter what information I am expecting back from my CFC, I always pass back a svrStatus variable and a svrMessage variable. Server status is the variable I check to make sure everything went as planned, if it is not 0 I know there was a problem. The svrMessage variable is what I want the users to see so they are not scratching their heads wondering what is going on.
I whipped up a quick demonstration. It is definitely nothing new, but I thought maybe it would help someone out.
Our basic page:
<cfcomponent output="no"> <cffunction name="remoteFunction" access="remote" returntype="struct" returnFormat="JSON"> <cfargument name="pass" type="numeric" required="yes"/> <cfset var respsone = structNew()/> <cftry> <cfset response['svrStatus'] = "0"/> <cfset response['svrMessage'] = "Method completed successfully"/> <cfif arguments.pass eq 1> <cfthrow message="Doh! Something broke!"/> </cfif> <cfcatch type="any"> <cfset response['svrStatus'] = "-1"/> <cfset response['svrMessage'] = cfcatch.Message/> </cfcatch> </cftry> <cfreturn response> </cffunction> </cfcomponent>
There is nothing too complicated going on here. The web page makes a call to our remote CFC and in this case it is hard-coded to throw an error on the second pass, simulating an error condition. The whole method is wrapped in a CFTRY block so if something did occur while the method was executing it would fire the CFCATCH block. The CFCATCH block sets the svrStatus to -1 letting me know that there was an error and it also sets the svrMessage variable to CFCATCH.Message so we will know the root cause of the problem.
The web page itself is not that complicated either. After making the ajax call we parse the data returned into JSON. At this time we could simply look at the svrStatus variable see if we have an error and display a message if so.
Any other tips and tricks for debugging ajax calls?