AJAX Code
This lesson shows you the code that was used to generate the example in the previous lesson.
The code
The Form
This code does the following:
- ColdFusion's
cfquery
queries the database for a list of countries. - The
script
tag links to a JavaScript file containing our AJAX code. - The
form
,select
andoption
tags create a form. TheonChange
event handler calls theshowRegions()
function from the .js file. This only executes when the user selects a country. - The
div id="regionList"
is a place holder for the regions select list. When the AJAX code is executed, this div will contain regions based on the country selected.
The JavaScript
This JavaScript code does the following:
- The
showRegions
function uses theopen()
method to initialise the connection. Thesend()
method can be used for sending extra data but we don't have any to send (hence "null"). - The
stateChanged
function uses thereadystate
variable of the XMLHttpRequest object to determine when the server has been contacted and the data retrieved. It then populates the "regionList" div with the data retrieved by the get_regions.cfm page. It does this by using theresponseText
method. - The
GetHttpObject
function creates an XMLHttpRequest object. Well, it actually has a couple of tries usingtry
andcatch
for browser compatibility reasons. Microsoft IE creates XMLHttpRequest as an ActiveX object while most other browsers do it the other way. Some don't support the XMLHttpRequest object.
The ColdFusion
This code does the following:
cfquery
queries the database. We are looking for all regions for this country code (as passed in via the URL).- If the
getRegions
query returned at least one record, we loop through the results, populating an HTMLselect
andoption
.