A reader, Andy, was looking for a very simple example of how jQuery can be used to load data from ColdFusion. I’ve done this many times before, but he wanted the bare bones, simplest demo I could muster. I covered this before, but I thought I’d share the code in case others were looking for simple examples as well.
I’ll begin with the initial template - the one that will use jQuery. It’s going to have a grand total of one button and clicking that will fire off our request to ColdFusion.
Let’s start at the bottom. Notice I’ve got two divs. One is going to be used as a status area. It will be used by jQuery to let the user know something is going on. (Ajax is not the same as instantaneous.) Moving up, I’ve got one main block of code all within $(document).ready. This is shorthand in jQuery for “Do this when the page is done.” Within it is one core function - an event handler for my button. When clicking we will first update the status div with a loading message and then disable the button. (Sometimes you have to do that or your users may go click crazy.) Next we actually fire off the Ajax request with the $.get command. test2.cfm is where my ColdFusion logic is (and I’ll share that code next), but in this example we aren’t doing much with it. I don’t grab any form data to pass to the script. I simply run it. I’ve then set up a response function to run. It first clears the status message, then sets the result into my div, and finally re-enables the button.
test2.cfm doesn’t do much at all. I simply made it a bit slow so that the loading message would be nice and obvious:
<cfset sleep(3000)> <cfoutput>Hello world, #timeFormat(now(), "long")#</cfoutput>
Not terribly much to it, but I thought it might be useful for folks who wanted a quick demo of how easy it is do Ajax with jQuery and ColdFusion. I’ve attached a zip of the two files to this blog entry and you can run the demo yourself.