Ajax call to coldfusion component using jQuery
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.
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.
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!