Getting Started with jQuery, HTML forms and ColdFusion
Over the past year, I've read a lot of forum posts related to submitting HTML forms to a CFC, specifically using Ajax techniques. Because I recently completed a CMS for a client that made heavy use of CFCs and jQuery (my Ajax library of choice) to handle all CRUD operations. Overall, it worked out quite well.
This is a long post and sorry for that. I am breaking the topic up into several smaller parts.
General Approach
The basic approach I've used is to have the form on my CFM page submit to a CFC via jQuery. The CFC then does it's thing and returns a message, serialized JSON data. The jQuery code receives the JSON data from the CFC and acts accordingly on the DOM. What's nice is that everything is handled asynchronously and no page reloads are required to run the desired action.
The FORM from the CFML (HTML) Page
The snippets I'll use in my examples are for a small module in the aforementioned CMS: form security questions. My client is, with this module, able to add security questions to their online forms in an attempt to prevent form spammers and XSS attacks.
I selected this one because it is a very basic module (simple CRUD operations) and has the least code. I've also stripped out all layout/formatting code in an effort to make it easier to read.
HTML FORM
<form method="post" name="formsecurityform" id="formsecurityform">
<input id="formSecurityId" name="formSecurityId" value="0" type="hidden">
<input id="doDel" name="doDel" value="false" type="hidden">
<label for="question">Question<span class="parentIndicator">*</span>:</label> <span class="serverResponses" id="question_error"></span>
<input id="question" name="question" class="textinput" maxlength="150" type="text">
<label for="answer">Answer:</label><span class="serverResponses" id="answer_error"></span>
<input id="answer" name="answer" class="textinput" maxlength="255" type="text">
<label for="buttons"> </label>
<input id="btnFormSecuritySubmit" value="Save" class="buttonSubmit" type="button">
<input id="btnFormSecurityReset" value="Clear" class="buttonSubmit" type="button">
<input id="btnFormSecurityDelete" value="Delete" class="buttonSubmit" type="button">
</form>
<div id="formOutput"></div>
A couple of important items to note in the form:
  • Required fields have a tag after their tag with an ID of field_error. The JavaScript code will use this if a required field does not meet validation requirements.
  • I've ensured that the buttons all have unique ID values.
  • There is no JavaScript in this form (unobtrusive JavaScript) and this keeps the form portable/reusable for future projects (I can change the JavaScript as needed but the form is set).
  • Take note of the ACTION attribute in the form tag. Note that is points to a CFC and uses a URL variable string to determine both the mothod to be invoked and the return format.
  • The DIV element with an ID of formOutput will be used by the JavaScript code to return messages to the user on the screen.
The JavaScript Part I: Initial Setup
I won't go into the details of jQuery and how it's used (as many sites, including the jQuery site itself, do this far better than I will). The function below is run when the document (DOM) is ready and serves to initialize the HTML document for interaction with my JavaScript code.
The first task of this function (ready()) is to create a JavaScript object called "options". The properties of the options object determine how jQuery will handle the processing of the form.
$(document).ready
(
function()
{
var options = {
target: '#formOutput', // target element(s) to be updated with server response
beforeSubmit: showFormSecurityRequest, // pre-submit callback
success: showFormSecurityResponse, // post-submit callback
resetForm: true, // indicates that the form should be reset upon successful completion
dataType: 'json',
url: 'FormSecurity.cfc?method=ajaxSave&returnformat=JSON'
// other available options (some repeated for completeness of code review):
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
//timeout: 3000
};
// bind form using 'ajaxForm' method of jQuery library to the ID of the form and pass in the options
$('#formsecurityform').ajaxForm(options);
  // ensure that the required field error tags are hidden
$("#question_error").hide();
$("#answer_error").hide();
}
);
The JavaScript Part II: Setting Up Button Behavior
The following code is (fairly) self-explanatory when read through. It sets up the onclick event handlers/actions for each button in the HTML form.
$(document).ready
(
function()
{
$( '#btnFormSecurityReset' ).click
(
function()
{
$( '#formsecurityform' ).resetForm();
// ensure special fields have the right value in them after form reset
$('#formSecurityId').val(0);
// the following line outputs a message to the screen
$( '#formOutput' ).html( '<p>Form Security Form Reset</p>' );
// a custom function to fade the above message after 2 seconds
waitToFade();
// clear the error <spans>s
$("#question_error").empty().hide();
$("#answer_error").empty().hide();
}
);
$( '#btnFormSecuritySubmit' ).click
(
function()
{
$( '#doDel' ).val( 'false' );
$( '#formsecurityform' ).submit();
}
);
$( '#btnFormSecurityDelete' ).click
(
function()
{
// I always force users to verify they want to delete something :)
var agree=confirm("Are you sure you want to delete this form security item?\nIf you continue, you cannot go back!!\nDo you still want to continue?");
if (agree)
{
$( '#doDel' ).val( 'true' );
$( '#formsecurityform' ).submit();
}
else
{
return false;
}
}
);
}
);

What makes the code above unobtrusive is that rather than littering my HTML with onclick="" attributes, I assign each button in the HTML form a function which runs when said button is clicked. The function assigned to the click event determines what happens (reset form, submit form, etc.). All this is contained in a single JavaScript making it easy to to reuse the above form in another CMS. I needn't alter the form and can simply edit the JavaScript file for the new project and server.
I want to make a quick note that I could have put all the jQuery code in one $(document).ready(){} call but am breaking it out here to show the various functions in this process as we go through it.
Next:
The next installment will illustrate how to validate the form and receive a response from the server.

Comments

Craig Kaminsky
Thanks, Marty! I couldn't agree more about CF and jQuery. They absolutely rock together!
Marty McGee
It's about time someone started getting into the nitty-gritty ability's of working with ColdFusion and jQuery. I look forward to future writings of such quality on the subject. To me, there is nothing you can't get done on a short time schedule with ColdFusion and jQuery (well, and a database :-)

Thanks! Marty McGee