jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion

This is the same as the previous jquery form submit post that used PHP just flavored with CF this time.

Two jQuery functions that allow for the submission of form are the jQuery.ajax function and the jQuery.post function (there is also jQuery.get but that is not addressed here).

More functionality, along with more complexity, is offered with the .ajax function while the .post function, with its more simple functionality and implementation, will be all that is needed for simple form posts.

It is highly recommended that you get a tool like Firebug to see the post response coming back from the page. It helps immensely.

Here is an example of both in action doing the same thing: form submit with email validation.

jQuery.ajax

The form:

<form id="JqAjaxForm">
<fieldset>
<legend>jQuery.ajax Form Submit</legend>
<p><label for="name_ajax">Name:</label><br />
<input id="name_ajax" type="text" name="name_ajax" /></p>
<p><label for="email_ajax">E-mail:</label><br />
<input id="email_ajax" type="text" name="email_ajax"  /></p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
<div id="message_ajax"></div>

Pretty simple, nothing fancy. There is a form for each jQuery function, .ajax and .post. The only difference in the forms are the element names.

jQuery controls the submit for the forms. For the .ajax submission the jQuery is this:

$(function(){
    $("#JqAjaxForm").submit(function(){
        dataString = $("#JqAjaxForm").serialize();
    
        $.ajax({
        type: "POST",
        url: "process_form.cfm",
        data: dataString,
        dataType: "json",
        success: function(data) {
        
            if(data.email_check == "invalid"){
                $("#message_ajax").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
            } else {
                $("#message_ajax").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
            }
         
        }
          
        });
        
        return false;            
        
    });
});

The .serialize function is used to put the form data in a format that can be processed by a page on the server. The .ajax function options include:

  • type: “get” or “post”
  • url: the page to receive the form data
  • data: the form data itself
  • dataType: the data type the function should expect back from the server
  • success function: runs on a succesful post to the page

More information on the options and further explanations of the options used here can be found on the jQuery.ajax documentation page.

jQuery.post

As in the .ajax example, the form is simple, only the names have been changed:

<form id="JqPostForm">
<fieldset>
<legend>jQuery.post Form Submit</legend>
<p><label for="name_post">Name:</label><br />
<input id="name_post" type="text" name="name_post" /></p>
<p><label for="email_post">E-mail:</label><br />
<input id="email_post" type="text" name="email_post" /></p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
<div id="message_post"></div>

And again, jQuery controls the submit for the forms. For the .post submission the jQuery is this:

$(function(){
    $("#JqPostForm").submit(function(){        
        $.post("process_form.cfm", $("#JqPostForm").serialize(),
        function(data){
            if(data.email_check == 'invalid'){
            
                    $("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
            } else {
                $("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
                }
        }, "json");
        
        return false;
        
    });
});

jQuery.post is a shorter, easier way to post the form data. The function arguments are:

  • url of the form processing page
  • the form data
  • the callback function
  • the data type of the return data

More information can be found on the jQuery.post documentation page.

Processing the Form

Both methods are processed by the same page. It processes the form data, process_form.cfm in this example, by checking to see if the e-mail submitted is valid. Much more than that could be done on the page if needed.

<cfset email_check = "" />
<cfset return_json_string = "" />
<cfset return_struct = StructNew() />

<cfif (isDefined("form.email_ajax") AND isValid("email",form.email_ajax)) OR (isDefined("form.email_post") AND isValid("email",form.email_post))>
   <cfset email_check = "valid"/>
<cfelse>
    <cfset email_check = "invalid"/>
</cfif>

<cfset StructInsert(return_struct, "email_check", email_check) />

<cfif isDefined("form.email_ajax")>
	<cfset StructInsert(return_struct, "name", form.name_ajax) />
	<cfset StructInsert(return_struct, "email", form.email_ajax) />
	
	<!---return_json_string is for pre-CF 8 only, delete if you have cf 8 or later--->
	<cfset return_json_string = '{"email_check":"#email_check#","name":"' & form.name_ajax & '","email":"' & form.email_ajax & '"}' />
	
<cfelse>
	<cfset StructInsert(return_struct, "name", form.name_post) />
	<cfset StructInsert(return_struct, "email", form.email_post) />
	
	<!---return_json_string is for pre-CF 8 only, delete if you have cf 8 or later--->
	<cfset return_json_string = '{"email_check":"#email_check#","name":"' & form.name_post & '","email":"' & form.email_post & '"}' />

</cfif>

<!--- serializeJSON is CF 8 and above only, see below for pre-CF 8 --->
<cfoutput>#serializeJSON(return_struct)#</cfoutput>

<!--- Uncomment the cfoutput statement below and remove the cfoutput statement above if you don't have CF 8--->
<!--- <cfoutput>#return_json_string#</cfoutput> --->

This code puts the results of the e-mail validation and the form data in a JSON-formatted string. It then will output the return data string which is picked up by the success function in the .ajax function or the function(data) function in the .post function on the original page.

I prefer working with JSON, but there are other options for the return data. Check the jQuery documentation for the types available to you.

The JSON response will look like this:

{"email_check":"valid","name":"Julia","email":"julia@example.com"}

NOTE: If you have ColdFusion 8 or better use the serializeJSON function. This function can return query results, arrays, dates, strings, and the like to JSON which is easily consumed and digested by javascript. Pre-CF 8 will require building the JSON string manually but with some loops and other creativity, it can be done.

The appropriate message based on the e-mail validation check is then displayed.

Pretty simple, pretty handy couple of jQuery functions. Once you see it in action, you get the idea.

Usual recommended jQuery and CF reading:

Download zip of all files

Posted in ColdFusion, jquery. Tags: , , . Permalink. Both comments and trackbacks are closed.

24 Comments

  1. November 28, 2011 at 8:44 am | Permalink

    thanks for sharing the solution

  2. July 26, 2011 at 9:36 am | Permalink

    @Jeff

    You can write the code to insert into a database in the process_form.cfm file and return true or false after insertion. If true (inserted into db with no issues), display a success message, if false (form or db issues), display a failure message.

    That’s basic sql insertion. There is nothing special about the sql procedure as you grab the form fields in the same manner that you would if the form were submitted directly rather than via ajax.

  3. Jeff
    July 26, 2011 at 9:11 am | Permalink

    Jen, I question is closely related to your example here. I am a super newbie to jquery and I am just trying to submit a simple form and have it insert into my database. Here is my form, do you have any examples on how to insert it into the database:

    Select an item to watch for (start typing name or enter set number)
    Set Name or Number

    Price Range

    Submit

  4. December 30, 2010 at 10:13 am | Permalink

    @Tom
    Awesome! And, thanks for sharing the solution.

One Trackback

  1. […] This post was mentioned on Twitter by jen, Robert Lee Myers. Robert Lee Myers said: jQuery.ajax & jQuery.post form submit w/ CF http://bit.ly/gq4oz Tagged: #ColdFusion http://bit.ly/3F3xDV […]