Getting Started with jQuery, HTML forms and ColdFusion
Picking up where I left off in my last post, I'll begin with a brief review of our HTML form and then detail a method for validating the required form fields with our jQuery-based JavaScript. After detailing form validation, I'll take a look at getting the form submission response back from the server and outputted on the screen.
Form Validation
In our HTML form, we had two required fields: Question and Answer. Actually, these are the only meaningful(to the user) fields in the form. The other fields are either hidden or buttons. The purpose of this form, within the CMS I built, is to empower my client with the ability to add, edit, and/or remove security questions that are applied to the site's various forms.
If a user is adding or editing a security question and answer, both the question and answer fields must contain data. For the purposes of this post/example, "containing data" just means a non-empty string.
When the user presses the Save button on the HTML form, the jQuery JavaScript code jumps to action. In the previous post, we created an options object to instruct jQuery how to treat the form data when it is submitted. One of the settings we made involved what jQuery should do before the form data is submitted to our processing page (the CFC).
Specifically, our code set the following value:
beforeSubmit: showFormSecurityRequest
This line of code tells jQuery to run the function showFormSecurityRequest before it submits the data.
It is here that we run our form validation code. If validation fails, we'll show an alert and provide other user-friendly information about their error. If validation succeeds, we'll have jQuery submit the form to the processing page (CFC).
Form Validation JavaScript
The following is the JavaScript function invoked when a user submits the form:
function showFormSecurityRequest(formData, jqForm, options) {
// formData is an array; here we use $.param to convert it to a string to display it
// but the form plugin does this for you automatically when it submits the data
var queryString = $.param(formData);
$("#question_error").empty().hide();
$("#answer_error").empty().hide();
var question = $("#question").val();
var answer = $("#answer").val();
var errors = 0;
if (question == null || question == '')
{
$("#question_error").show().append("A question is required");// adds the text inside append() to the page
errors++;
}
if (answer == null || answer == '')
{
$("#answer_error").show().append("An answer is required");// same as above
errors++;
}
if (errors > 0)
{
alert ("Errors were found on the form");// used to grab the user's attention
return false;
}
else
{
return true;
}
}
Of course, form validation will often be far more involved in this (validating email addresses, checkboxes, radio buttons, multiple related fields, etc.) but my hope is that this shows you just how simple the general process is to implement. Keep in mind that all of this occurs without the page ever refreshing, so it's quite responsive for the user.
Form Processing
If, when the above function is run, there are no validation failures, the form is submitted to the CFC. Our particular form has been set to submit to a CFC named FormSecurity.cfc. We also instructed jQuery to invoke the method named ajaxSave and provide our return data in JSON (JavaScript Object Notation).
These instructions came from the JavaScript options object we built as noted in the following line of code:
url: FormSecurity.cfc?method=ajaxSave&returnformat=JSON
url: FormSecurity.cfc?method=ajaxSave&returnformat=JSON
Form Security CFC
<cffunction name="ajaxSave" output="true" access="remote" returntype="void">
<cfargument name="formSecurityId" type="numeric" default="0"/>
<cfargument name="question" type="string" default=""/>
<cfargument name="answer" type="string" default=""/>
<cfargument name="doDel" type="boolean" default="false"/>
<cfscript>
// first, create the object
formSecurity = createObject( "component", "FormSecurity").init();
formSecurity.setId( '#arguments.formSecurityId#' );
formSecurity.setQuestion( '#arguments.question#' );
formSecurity.setAnswer( '#arguments.answer#' );
// return object
_msg = StructNew();
// if this is not a delete call, save the object
if( not arguments.doDel )
{
save( formSecurity );
if( formSecurity.getId() gte 1)
{
_msg.message = "Form security item details saved. Existing form security item (#formSecurity.getQuestion()#) has been updated in the system.";
}
else
{
_msg.message = "Form security item details saved. New form security item (#formSecurity.getQuestion()#) has been added to the system.";
}
}
else
{
// delete it
deleteById( arguments.formSecurityId );
_msg.message = "Form security item deleted. Previously published form security item has been removed from the system.";
}
_msgJSON = SerializeJSON(_msg);
</cfscript>
<cfoutput>#_msgJSON#</cfoutput>
</cffunction>
The method begins with a list of the arguments it is expecting to receive. These arguments correspond directly to the fields in my HTML form, including hidden fields. I won't get into the details of how I save the object. The general approach is to create a formSecurity object and set its various fields (properties) to the appropriate form value. I then check to see if the doDel form field value is true or false. If it's true, I run a deletion and, if it's false, I create/update the object by calling the appropriate method (save or deleteById).
You can choose to handle this step (the ColdFusion processing) any way that works for you. I just prefer an OOP approach.
There is one other aspect of the CFC I want to call out. The _msg variable. This variable, a structure, contains but one key, message. It could contain as many keys as you need but, as I mentioned, I'm trying to keep the code simple. I fill the key (message) with the appropriate message for the user based on the processing of the form. Before exiting the function, I output a string as JSON using ColdFusion's SerializeJSON method. This method takes a structure and converts it to a JSON-compatible string.
When we output this JSON string at the end of the function, this string is read by the jQuery script and converted to a JavaScript object that is used by our jQuery code to let the user know how things went (appends data to one of the span elements on the HTML page shown in the previous post).
And that's it for the basics of submitting a form from a CFML page via jQuery to a CFC.