ColdFusion and jQuery – Using AJAX to Call a CFC and Return JSON
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:
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.