Site icon Hot Pepper Communications

AJAX and ColdFusion

AJAX seems to be all the rage recently, what with all the hype behind GMail, Google Maps, flickr, and the like. I’ve been wanting to dabble in it to test out the waters before I implemented anything major.

Cameron Adams recently published an AJAX article over at SitePoint, and it sold me on giving it a shot. I also stumbled across Bill Bercik’s Guide to Using XMLHttpRequest (with Baby Steps), which gave me the idea that I may be able to combine AJAX and ColdFusion (he used PHP).

The basic idea behind my basic AJAX project was sending a request to a ColdFusion page, using the request to query an SQL database, returning the single record, and popping it up in an alert box.

The ColdFusion code

<cfquery datasource="xxx" name="qBio">
SELECT * FROM Bios
WHERE Username = '#URL.name#'
</cfquery>

<cfoutput>Name,#qBio.cn#</cfoutput>

As I said, this is a really simple query. ColdFusion queries the Bios table from the database (I renamed the database for security reasons) based on a ‘name’ variable in the URL, and then outputs the ‘cn’ cell based on the value of the ‘name’ variable. For example, if the value of the ‘name’ variable was ‘kim.siever’, the output would be ‘Name,Kim Siever’.

The web page

The web page was simply a default page that displayed some information about me and the URL was test.cfm?name=kim.siever.

The JavaScript code

First things first. I wrote some code to check if the browser can handle AJAX.

try {
var http = new XMLHttpRequest(); // non-IE
}

catch (error){
try {
var http = new ActiveXObject("Microsoft.XMLHTTP"); // IE
}
catch (error) {
return false;
}
}

IE and everyone else handle XMLHttp requests differently, so this code checks to see which browser the user is running.

Next comes the code to get the name from the current URL to be passed to our ColdFusion page.

var u = document.location.href;
var i = u.indexOf('name=');
var n = u.substring(i+5,u.length);

If you’re just testing this out, you could simplify it further and just have the following:

var n = 'kim.siever';

Then comes the query.

var q = 'query.cfm?name=';
http.open("GET", q + n, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);

Basically this queries query.cfm?name=kim.siever and then calls the handleHttpResponse function, which is below:

function handleHttpResponse() {
if (http.readyState == 4) {
var results = http.responseText.split(',');
alert(results[1]);
}
}

The response, which is Name,Kim Siever, is treated as an array with two elements: ‘Name’ and ‘Kim Siever’. The alert returns the second element in the array (the first element would be 0). And voilà, the alert returns Kim Siever.

Easy as pie.

Exit mobile version