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. December 21, 2010 at 11:23 am | Permalink

    @Tom
    Just loop over the form fields as if you submitted it normally (without jquery).
    <cfloop collection="#FORM#" item="i">
    #i.sysName#
    </cfloop>

  2. Tom
    December 21, 2010 at 9:55 am | Permalink

    Jen,

    I have a form where the input fields are being looped over so the field names and ids are fields like sysName_208, sysName_209, sysName_210, etc. It could be one field or 101 fields. I can get the form to submit (thanks to your example above) but I'm not sure how to loop over the submitted json data to create the update sql statement (ms sql). The form itself is being use to allow for updates to the system and when submitted, the changes will be saved in the database.

    Is this something you can provide some guidance with?

  3. Pardeep
    August 5, 2010 at 1:19 am | Permalink

    Thanks Jen, I've been looking high and low for just such a tut, that shows how to do it, has a demo and even files to download.

    Much appreciated, I'm just getting started using jquery with coldfusion for db interactions.

  4. June 3, 2010 at 9:13 am | Permalink

    @Ben
    Easy error. Made many myself with code complete. Sometimes I pick the wrong attribute.

  5. June 3, 2010 at 8:43 am | Permalink

    Jen: Thanks, that was it. Guess I need to learn some JavaScript.

  6. June 3, 2010 at 8:34 am | Permalink

    @Ben
    Change type="application/javascript" to type="text/javascript" and it should work in IE8.

  7. June 3, 2010 at 8:23 am | Permalink
  8. June 3, 2010 at 7:01 am | Permalink

    @Ben
    I just tried the demo in the post in IE8 and it worked fine. Not sure what problem you are having. Do you have a test page I could look at?

  9. June 2, 2010 at 2:58 pm | Permalink

    Nice post. However, I cannot get this to work in IE8, it works fine in Firefox. Any ideas?

    I'm using the .post function and that syntax is confusing to me. I'm getting ready to try the .ajax function I like the syntax there much better?

    I have just a little experience with jQuery, am a ColdFusion programmer.

  10. October 23, 2009 at 8:22 am | Permalink

    Nifty post! Thanks for sharing.

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 […]