Using a Page Controller to simplify AJAX

While working on a form that makes use of some simple AJAX, I discovered that using a Page Controller can make this easier - especially when combined with JSMX.

In my entry on a ColdFusion Page Controller (might want to read that first), I covered that the page controller can retrieve data from the model for use in the view. This can be done in a method with access="remote" (assuming that the data isn't sensitive).

Using the example from the previous entry (sample-page.cfc), the getLessons() method will return a query of all of the lessons for a given category. Since this method is remote, it can also be accessed directly as a web service. This includes remote access by JavaScript.

<cffunction name="getLessons" access="remote" returntype="query" output="no">
<cfargument name="category" type="numeric" required="yes">

<cfreturn variables.Lessons.getLessons(arguments.category)>
</cffunction>

So, an XmlHttpRequest to the following URL would return a WDDX representation of a query of all lessons for category 2.

sample-page.cfc?method=getLessons&category=2

The only difficulty there is that WDDX data isn't something that JavaScript reads naturally. Fortunately, JSMX can take care of this. Just load the engine.js file in your browser and then use the following code:

file = 'sample-page.cfc?method=getLessons&category=2';
http('GET', file, myMethod);

The http() method (from JSMX) will call myMethod() and pass it a JavaScript representation of your query. This will be in the same format as if you had used cfwddx to translate the query to JavaScript.

Now you have your query data available from your JavaScript - just as if you had used cfwddx. Except that by taking advantage of AJAX you can load only the data that you need when you need it.

The upshot of this is that you can expose your data to AJAX without the use of an extra file (assuming that you are already using a page controller and JSMX).

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.