JavaScript and Web Development

ColdFusion and jQuery – Using AJAX to Call a CFC and Return JSON

29 October 2009 - ColdFusion, JavaScript - James Brown - 2 Comments

I recently had a friend ask me about using jQuery to call a ColdFusion CFC via AJAX and return a value. It is actually quite easy and fun to do. It requires two files to be created. The two filenames I’m using for this example are: index.cfm and myCFC.cfc but you could easily use your own filenames.

The first file we’re going to start out with is index.cfm:

<script type="text/<span class=">// <!&#91;CDATA&#91;
javascript</span>" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
// &#93;&#93;></script>
<script type="text/javascript">
chkUsernameUnique = function(theUsername){
 $.getJSON("/assets/cfc/myCFC.cfc", {
 method: 'chkUsername',
 Username: theUsername,
 returnformat: 'json'
 }, function(isUsernameUnique){

 if (isUsernameUnique == true) {
 $("#theErrorDivID").html('Username is unique');
 }
 else {
 $("#theErrorDivID").html('Please select a new username');
 }
 });
};
</script>

<div id="theErrorDivID"></div>
<input type="text" name="username" id="username" onchange="chkUsernameUnique(this.value);" />

If you read through the code, it is self explanatory. We first include the jQuery library from the Google CDN (you could always point this at your web server if you are going to host the file instead). In the next set of lines, we create a function, setup our AJAX, specify the CFC (you can change the cfc path to match your web server), method and some variables. We then specify the return function to run once the data is returned from our cfc. Based on the data returned, we display a message to the user. The final lines outside the script tag are the DIV for displaying the message and the input.

The next set of code is the cfc we call (myCFC.cfc):

<cfcomponent>
<cffunction name="chkUsername" access="remote" returnformat="json" output="false">
    <cfargument name="Username" required="true">

    <cfquery name="chkUsername" datasource="YOURDATASOURCEHERE">
    SELECT ID FROM tb_user WHERE user_login = <cfqueryparam value="#arguments.Username#" cfsqltype="cf_sql_varchar" />
    </cfquery>

    <cfreturn yesNoFormat(chkUsername.recordCount) />
 </cffunction>
</cfcomponent>

This set of code queries the database to check if the username is unique and returns true or false based on that result. This example could quickly be expanded to check for other variables or perform additional functions. If you are new to jQuery, I highly recommend you check it out and dive right into it. If you are looking for a book to learn jQuery, I recommend: Learning jQuery 1.3. It is a great book and walks you through step-by-step to teach you the library.

2 Responses to “ColdFusion and jQuery – Using AJAX to Call a CFC and Return JSON”

Leave a Reply