AJAX in ColdFusion 8: Don’t overthink it!
For CFMenuCal, I'm planning on using AJAX to display a "settings" type window, which will allow you to edit your meal data, allowable proximities, and other settings. To teach myself the basics of CFAjaxProxy and get a better idea of how to write my components to that end, I made a simple page that dumps the session scope, and has a form with a textbox and submit button that should - in theory - make the AJAX call to my test component, which will then update the session scope.
I know this sounds pretty simple, and in actuality, it is. But I spent at least a couple of hours on Saturday reading up on JSON, and thinking about how I'll need to implement it. I was thinking I would need to serialize my data on the client side, and then use DeserializeJSON() in my component to turn the JSON string into CF variables. As it turns out - that was wasted time. It's all done implicitly for you.
So first, let's build our component:
<cfcomponent name="AjaxTest" hint="Performs some proof of concept AJAX functionality for CFMenuCal."> <cffunction name="updateSession" access="remote" output="false" returntype="Boolean"> <cfargument name="data" type="any" required="true"> <cftry> <cfset session.data = arguments.data> <cfreturn true> <cfcatch type="any"> <!--- log the error via cfmail or cffile ---> <cfreturn false> </cfcatch> </cftry> </cffunction> </cfcomponent>
Notice that the I set the ACCESS of the function to REMOTE. This pretty frequently gets me (I commonly use PUBLIC), and I spend too much time trying to figure out why I'm getting "method X doesn't have any properties" JavaScript errors.
So now that we have our component, we need a page that uses it. Enter test.cfm:
<cfajaxproxy cfc="com.AjaxTest"> <cfdump var="#session#" label="Session Scope"> <form method="post" name="fooForm"> <input type="text" name="bar" size="30" /> <input type="button" onClick="sessionize(this.form.bar.value);" value="Save" /> </form> <script type="text/javascript" language="javascript"> sessionize = function(data){ var updater = new com.AjaxTest(); var myObj = {}; myObj.numberValue = 42; myObj.stringValue = "hello, world!"; myObj.userValue = data; var success = updater.updateSession(myObj); if (success == "true" || success == true){ alert('Success! Refreshing the page to update dump...'); document.location.href = document.location.href; }else{ alert('An error occurred. Check the log for details...'); } } </script>
The above assumes the component is named AjaxTest and resides either in a subdirectory named "com" of the current directory, or of the root folder. Running it should produce a cfdump that looks something like this:

The moral of the story is: Don't overthink it! The ColdFusion 8 team over at Adobe has made this too easy.
Posted in AJAX | CFMenuCal | ColdFusion | Scorpio