Simple Ajax Example Tutorial with ColdFusion

The following illustrates how to create a simple Ajax application with ColdFusion. This example sends a request to the server to get a list of product colors.

Use this JavaScript code:

//First, create the XMLHttpRequest object; the try/catch is to handle the various browsers implementation of XMLHttpRequest
try {
var objXHR = new XMLHttpRequest();
} catch (e) {
try {
var objXHR = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
var objXHR = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {
document.write('XMLHttpRequest not supported'); }
}
}

//Open the URL where the database query resides; replace the URL here with the URL of the page on your server
objXHR.open('GET','http://myURL.com',true);

//Set up a listener to handle the response from the server
objXHR.onreadystatechange = function(evt){
if (objXHR.readyState == 4) {
if(objXHR.status == 200)
colors = objXHR.responseXML.getElementsByTagName('color');
for (i=0;i<colors.length;i++)
document.write(colors[i].firstChild.nodeValue);

else
document.write('Error processing request');
}
};

//Send the request to the server
objXHR.send(null);
//End JavaScript

This is the ColdFusion page URL that should be referenced in the “open” method in the JavaScript, above:

<cfsetting showdebugoutput = 'false'>
<cfheader name='Expires' value='#now()#'>
<cfheader name='Content-Type' value='text/xml'>

<cfquery datasource=”mydatasource” name=”qryColors”>
SELECT Colors
FROM Products
</cfquery>

<cfoutput>
<colors>
<cfloop query=”qryColors”>
<color>#qryColors.Color#</color>
</cfloop>
</colors>
</cfoutput>

Related articles:
JavaScript: Creating XMLHttpRequest Object for Ajax
JavaScript XMLHttpRequest open Method: Calling a URL in Ajax
JavaScript XMLHttpRequest send Method: send a URL in Ajax
JavaScript XMLHttpRequest onreadystatechange for Ajax Requests
JavaScript: Getting Data From a Server for Ajax

Leave a Reply