Simple Ajax requests with cfWheels and jQuery

Someone asked me via email today – I would like to know how to include a Partial dynamically based on a link/button click;

Well, I thought I’d rustle up the simplest way of doing this I could think of.

This example has three parts to it: an Ajax.cfc controller, an index.cfm file and a _time.cfm partial. I’m assuming you’ve got the index.cfm and _time.cfm files in /views/ajax/ and the controller file will live in /controllers/Ajax.cfc

I’ve included two ways of essentially doing the same thing: one renders the partial (which is what the emailer asked for), but depending on what you want to get back, renderWith() can be really useful too, and saves you having to create a partial just to return something simple like a string.

So what’s going on is:

  1. jQuery looks for the class “callremotedata” and takes over its “click” event
  2. It stops the a tag from firing as a normal request
  3. It takes the href value from the a tag
  4. Then fires an ajax request and replaces the HTML in #result with the html returned from the Ajax.cfc controller