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

SELECT * FROM tblCountries
ORDER BY title

SELECT * FROM tblCities
WHERE CountryID = #Arguments.CountryID#
ORDER BY CityTitle

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:

<label for="CountriesList">Select Country:</label>
<select id="CountriesList" name="CountriesList">
<option selected="selected">...</option> <option value="#CountryID#">#CountriesList.CountryTitle#</option>
</select>

<label for="SelectedCities">Select City:</label>
<select id="SelectedCities" name="SelectedCities"><option>...</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.

<script type="text/javascript">// <![CDATA[
	$(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.
$(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!

Share it!Share on Google+Share on FacebookTweet about this on TwitterShare on LinkedInShare on StumbleUpon

Comments (7)

  1. Ben
    May 27, 2010 at 11:33 pm · Reply

    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.

  2. giorgos
    May 28, 2010 at 10:44 am · Reply

    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.

  3. sam
    August 18, 2010 at 11:54 pm · Reply

    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.

    • giorgos
      August 23, 2010 at 10:00 am · Reply

      Hi Sam,

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

      cheers,
      Giorgos

  4. Rob
    December 4, 2010 at 11:32 pm · Reply

    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:

    • Rob
      December 4, 2010 at 11:34 pm · Reply

      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:

    • giorgos
      December 6, 2010 at 10:47 am · Reply

      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

Leave a reply

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

Back to Top