Ajax call to coldfusion component using jQuery

The following post contains information on how to use jQuery and cfc to populate a select box with data.

The requirements are Coldfusion server 8+

You can download the latest Jquery from here.
You can download a development server from here.

I was looking over the internet for any posts on how to make an ajax call to a cfc and then populate the results to a select box.
My example will show how to populate names of cities depending on the country selection.

Firstly you must create a table called tblCountries and another one called tblCities in your database.
If you spend some time googling around you can find all the data you need easily.

Then we need a coldfusion component (cfc).
The code for the cfc is

Coldfusion component CountriesCities.cfc


<cffunction access="public" name="CountriesList" output="false" returntype="query">
<cfquery name="SelectAllCountries" datasource="#Session.DSN#">
SELECT * FROM tblCountries
ORDER BY title
</cfquery>
<cfreturn SelectAllCountries>
</cffunction>
<cffunction access="public" name="SelectedCities" output="false" returntype="query">
<cfargument name="CountryID" required="yes" type="numeric" default="-23" />
<cfquery name="SelectCities" datasource="#Session.DSN#">
SELECT * FROM tblCities
WHERE <cfif Arguments.CountryID neq -23>CountryID = #Arguments.CountryID#</cfif>
ORDER BY CityTitle
</cfquery>
<cfreturn SelectCities>
</cffunction>

There are two methods. The first method is used when the page loads in order to fill the first select box with country-related data. Then the story is more or less as you might expect: Once a country is selected the second method of the cfc will give us back a result with cities that belong to the selected country.

Now we need to write some html in order to have a form with these two select boxes.

The HTML code is:

HTML code


<cfsilent>
<cfinvoke component="Countries" method="CountriesList" returnvariable="CountriesList"/>
</cfsilent>
<label for="CountriesList">Select Country:</label>
<select name="CountriesList" id="CountriesList">
<option value="" selected="selected">...</option>
<cfloop query="CountriesList"><option value="#CountryID#">#CountriesList.CountryTitle#</option></cfloop>
</select>
<label for="SelectedCities">Select City:</label>
<select name="SelectedCities" id="SelectedCities"><option value="">...</option></select>

As you can see so far we have a selected box filled in with all results from our query and an empty one, with no options at all.
Nice and easy but lets go further. For the ajax call we will need a bit of Jquery.

jQuery ajax call to the coldfusion component


<script type="text/javascript">
// <!--
$(document).ready(function()
{

$("#CountriesList").change(function()
{
if($(this).val() != '')
{
$.ajax({
type: "POST",
url: "/_cfc/CountriesCities.cfc?method=SelectedCities",
data: ({
CountryID: $(this).val()
}),
dataType: "xml",
success: function(xml)
{
$('#SelectedCities option').remove();
$(xml).find('record').each(function()
{
$("#SelectedCities").append('<option value="' + $(this).find('cityid').text() + '">' + $(this).find('citytitle').text() + '<\/option>');
});
}
});
}
});

})

// -->
</script>

Let’s explain the code a bit.
It’s a simple jquery ajax call to the cfc component.
We post the selected country id and once we get a success callback we use jquery again to populate the results to the empty select box “SelectedCities”.
It’s really easy, isn’t it?

The only weird thing I may need to mention is that the format that we use for the call is XML and if you noticed my code I used lowercase to find my database fields.

lowercase field name


$(this).find('cityid').text()

That’s it, now you can go on and add more and more filters in order to have a complete form.

I hope you like my post and found this information interesting!

Tags: , ,

  1. Prasanth’s avatar

    Can we access a function with access=”public” through Ajax? Shouldn’t that be access=”remote”?

    Reply

  2. Ida’s avatar

    What’s Happening i’m new to this, I stumbled upon
    this I’ve found It absolutely useful and it has helped me out loads. I’m hoping to give a
    contribution & help different customers like its aided me.

    Good job.

    Reply

  3. Steven’s avatar

    I know I’m coming in long after this was published, but is there anywhere to go to get a download of this project’s files? I tried assembling the code above into files on my server, but I can’t get it to work. Is there a working demo somewhere?

    The first error I get is “Could not find the ColdFusion Component or Interface Countries. “. I see Countries called above in the code, but I do not see where the component “Countries” is ever defined.

    Thanks in advance.

    Reply

  4. ben’s avatar

    I managed to work out a solution using json. I couldn’t get my CFC to output the XML in a format that the jQuery would work with. (wddx wrappers or something?)
    Of all the solutions I found on the internet, this one was the most elegant so I was excited to use it. I had not much joy when it didn’t work.
    specifically how the CFC returned queries rather than building the JSON response manually.

    here are the modifications I made to get it to work for my situation. (passing the data back as JSON)

    // <!–
    $(document).ready(function()
    {

    $("#CatList").change(function()
    {
    if($(this).val() != '')
    {
    $.ajax({
    type: "POST",
    url: "./prodSelect.cfc?method=SelectedSubCats",
    data: ({
    catID: $(this).val()
    }),
    dataType: "json",

    //on success, stuff the result from the cfc into the success function
    success: function(dataToParse){
    var r = dataToParse;
    //reset dependent select box
    $('#subCatList option').remove();
    //build a variable 'options' that is the list of subcats. ID for the value. Item Name to show user
    var options= '';
    for (var i = 0; i < r.DATA.length; i++) {
    options += '’ + r.DATA[i][1] + ”;
    }
    $(“select#subCatList”).html(options);

    }
    });

    }
    });

    })

    // –>

    and here is the CFC that returns the data:
    (cfdebugging kills all joy with JSON. cfsettin tag opitional if its not on)

    SELECT * FROM category
    ORDER BY category

    SELECT * FROM subcategory
    WHERE topCatID = #Arguments.catID#
    ORDER BY subcat

    {“COLUMNS”:["ID","SUBCAT","ACTIVE","TOPCATID"],”DATA”:[[2,"Flaming Newt",true,1],[9,"Granny Smith",true,1],[1,"Pink Lady",true,1],[10,"Red Delicious",true,1]]}

    http;//websauce.net/jquery/select.cfm

    Again, i really like the CFC,but just couldn’t get the XML response to parse.

    So many “tutorials” on this subject, that just fail.
    This one worked well for me once I figured out the parsing issue.
    (still curious about WDDX or whatever caused it fail)

    thanks for the tutorial

    Reply

  5. Rob’s avatar

    I have been trying to get this to work and am having some problems with the XML. I am am getting a result back but it appears to be a wddxpacket and either I do not know how to read the packet or Jquey doesn’t think it is valid XML. Any help would be appreciated.

    Here is what I have:

    CFC

    Select state_ID_PK, state_name
    From statesTbl

    Where state_country_ID_FK = #arguments.state_country_ID_FK#

    Order by state_name

    CFM

    // <!–
    $(document).ready(function(){

    $("#CountriesList").change(function() {
    if($(this).val() != ''){
    $.ajax({
    type: "POST",
    url: "http://localhost:8500/theadstreet/adStreetLayouts/adStreetLookup.cfc?method=getStates&quot;,
    data: ({ state_country_ID_FK: $(this).val() }),
    dataType: "json",
    success: function(json){
    $('#SelectedState option').remove();
    $(json).find('record').each(function() {
    $("#SelectedState").append('’ + $(this).find(‘state_name’).text() + ”);
    });
    }
    });
    }
    });
    });

    // –>

    Select Country:


    #CountriesList.Country_name#

    Select State:

    Reply

    1. Rob’s avatar

      It didn’t post everything…Here is the rest

      // <!–
      $(document).ready(function(){

      $("#CountriesList").change(function() {
      if($(this).val() != ''){
      $.ajax({
      type: "POST",
      url: "http://localhost:8500/theadstreet/adStreetLayouts/adStreetLookup.cfc?method=getStates&quot;,
      data: ({ state_country_ID_FK: $(this).val() }),
      dataType: "json",
      success: function(json){
      $('#SelectedState option').remove();
      $(json).find('record').each(function() {
      $("#SelectedState").append('’ + $(this).find(‘state_name’).text() + ”);
      });
      }
      });
      }
      });
      });

      // –>

      Select Country:


      #CountriesList.Country_name#

      Select State:

      Reply

    2. giorgos’s avatar

      Hi Rob,

      If your cf component works as expected then check this to your jquery code,
      The datatype expected should be xml and not json format. Try to change this to see how is it going.

      dataType: “json” –> dataType: “xml”

      Cheers, Giorgos

      Reply

    3. sam’s avatar

      Hey,

      Good post! I was banging my head to a brick wall trying to do something on these lines…..Very interesting way of putting things together.

      I have a suggestion though,
      I see the query name inside CFC not being declared in a var scope which is just a regular practice for me to put on…….

      Not a biggie :)

      Thanks,
      Sam.

      Reply

      1. giorgos’s avatar

        Hi Sam,

        Of course you can do that if you like to..

        cheers,
        Giorgos

        Reply

      2. giorgos’s avatar

        Hi Ben,

        There is no onLoad or something, the first select box is filled in with countries data from your database query while the second select box is empty.

        Then the $(“#CountriesList”).change function does the trick, once the countries select box value changed the jQuery ajax method call the cfc component which will deliver us cities depending on selected country id.

        Sorry I have no files online as this code comes from a project which is still under development.

        Reply

      3. Ben’s avatar

        I find this is very interesting and easy to understand, but, I can’t make it work in my project. My project is similar, I’m using counties as primary select and cities as secondary select. Do you have a link to a complete set of files? That would help. It looks as though the secondary select should be empty when it first loads, should there be an onLoad somewhere in the form?

        Am a ColdFusion programmer and have used just a little jQuery.

        Reply

Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>