Coldfusion and jQuery AJAX

The other day, I decided that I wanted to add in a dependent drop down for the country and state selection to one of our programming projects.  The system will be very basic, since the only countries in the end will be the U.S. and Canada, but each should have a good selector for its respective states or provinces.  Now I’ve been working with jQuery for a while now, and I still love it, but I was having a hard time getting my head wrapped around certain things.  In the end, I came up with a simplified way of getting a basic dependent drop down using a selectboxes plugin for jQuery and some basic Coldfusion.  I didn’t go all out to the extreme, nor did I use the handy ajax cfc.

I created my drop downs the standard way, with looping through the query etc on the form.  With jQuery and the selectboxes we can then add in an ajax call.
$(function(){
$(“select#country”).change(function(){
// Below functions come from the jquery.selectboxes.js plugin, yay
//REMEMBER that javascript is CASE SENSITIVE!!!
$(“select#state”).removeOption(/./); //removes all options
$(“select#state”).ajaxAddOption(“<cfoutput>#application.root#</cfoutput>search.cfm”, {country: $(this).val(), ajax: ‘true’}, false);
})})

So then also in our CF search page (which is calling itself BTW – it can also call a cfc if you want, just have to make the adjustment) we use a little variable selects and some output formatting, and that’s all she wrote.
<cfif url.ajax>
<cfif url.country neq “”>
<cfset qStates = getStatesQuery(country=url.country)>
<cfsavecontent variable=”result”>
{<cfoutput query=”qStates”>”#qStates.stateAbbrev#” : “#qStates.stateName#”<cfif qStates.currentrow LT qStates.recordcount>,</cfif></cfoutput>}
</cfsavecontent>
</cfif>
</cfif>

When you click on the country drop down, it calls the page via ajax returning a formatted string that we can then use to populate the dependent state drop down.  Nifty.

Tomorrow – more fun with jQuery… loading a flash video to a div.