AJAX Tutorial

About this tutorial

This AJAX tutorial explains what AJAX is and demonstrates how you can use it.

This tutorial uses ColdFusion to perform the server-side code but you can use any language you like for the server-side code.

What is AJAX?

AJAX (also referred to as "remote scripting") stands for Asynchronous JavaScript And XML, and refers to a method of programming that incorporates the following technologies to send and receive data between the browser and server:

With traditional web applications, when users submit a form they have to wait around for the page to reload before seeing the results.

With AJAX, your application can dynamically populate a page (for example, retrieve data from a database) without having to reload the page.

Example

Select a country from the form. This will query the database. If it has a region associated with it (i.e. Australia), a "Region" option will appear.

Select a country:

The code

The Form

Copy to Clipboard
<cfquery name="getCountries" datasource="ajax_example">
select * from Countries
order by CountryName asc
</cfquery>
<script src="selectRegions.js"></script>
<form>
<div>
<span>
<b>Select a country:</b>
</span>
<span>
<select name="Country" onChange="showRegions(this.value)">
<cfoutput query="getCountries">
<option value="#CountryCode#">#CountryName#</option>
</cfoutput>
</select>
</span>
</div>
<div id="regionList">
</div>
</form>

This code does the following:

  1. ColdFusion's cfquery queries the database for a list of countries.
  2. The script tag links to a JavaScript file containing our AJAX code.
  3. The form, select and option tags create a form. The onChange event handler calls the showRegions() function from the .js file. This only executes when the user selects a country.
  4. 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

Copy to Clipboard
var oXmlHttp

function showRegions(str)
{
var url="/ajax/get_regions.cfm?&countryCode=" + str
oXmlHttp=GetHttpObject(stateChanged)
oXmlHttp.open("GET", url , true)
oXmlHttp.send(null)
}

function stateChanged()
{
if (oXmlHttp.readyState==4 || oXmlHttp.readyState=="complete")
{
document.getElementById("regionList").innerHTML=oXmlHttp.responseText
}
}

function GetHttpObject(handler)
{
try
{
var oRequester = new XMLHttpRequest();
	oRequester.onload=handler
	oRequester.onerror=handler
	return oRequester
}
catch (error)
{
try
{
var oRequester = new ActiveXObject("Microsoft.XMLHTTP");
oRequester.onreadystatechange=handler
return oRequester
}
catch (error)
{
return false;
}
}
}

This JavaScript code does the following:

  1. The showRegions function uses the open() method to initialise the connection. The send() method can be used for sending extra data but we don't have any to send (hence "null").
  2. The stateChanged function uses the readystate 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 the responseText method.
  3. The GetHttpObject function creates an XMLHttpRequest object. Well, it actually has a couple of tries using try and catch 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

Copy to Clipboard
<cfquery name="getRegions" datasource="ajax_example">
select * from Regions 
where CountryCode = 
  <cfqueryparam value = "#url.countryCode#" cfsqltype="cf_sql_varchar">
</cfquery>
<cfif getRegions.recordcount>
<span>
<b>Select a region:</b>
</span>
<span>
<select name="Regions">
<cfoutput query="getRegions">
<option value="#RegionCode#">#RegionName#</option>
</cfoutput>
</select>
</span>
</cfif>

This code does the following:

  1. cfquery queries the database. We are looking for all regions for this country code (as passed in via the URL).
  2. If the getRegions query returned at least one record, we loop through the results, populating an HTML select and option.

Summary

We learned that AJAX stands for Asynchronous JavaScript And XML, and that it can help you build more responsive, usable web applications. We then saw an example of AJAX in action - retrieving data from a database. Lastly, we saw the code behind the example.

Next steps

Feel free to check out these Quackit tutorials on the technologies we used in the above example:

In any case, Try and use your imagination and see what great uses you can find for AJAX!

Enjoy this page?

  1. Link to this page (copy/paste into your own website or blog):
  2. Link to Quackit using one of these banner ads.

Thanks for supporting Quackit!

Sponsored Link: Design CODE-FREE Websites

Check a Domain:

ZappyHost Logo