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. Tom
    December 30, 2010 at 9:55 am | Permalink

    Here is the solution I came up with. I knew it could be done, I just wasn't sure of the syntax. I found the syntax to use here http://preview.tinyurl.com/235ycyn. Anyway, because my ids are not necessarily sequential, I could load up a new array since CF wanted to populate the empty arrays with null values which was really slowing down the process. So, what I decided to do was populate a hidden input field with the IDs (the only form field that wasn't dynamic). That way, I would get a comma delimited listed when the form is submitted with the IDs being updated. From there, I just looped over those submitted IDs, set my database field name to the dynamic field value and then performed an update on the database. Below is the code snippet:

    <cfloop index="i" list="#attributes.sd_id#" delimiters=",">
    <cfset ActualLiveDate = form["ActualLiveDate_" & i]/>
    <cfset BkPSA = form["BkPSA_" & i] />
    …same format for the remaining form fields…
    <cfquery name="rsUpdate" datasource="#dsn#">
    update tablename
    set
    ActualLiveDate = <cfqueryparam cfsqltype="CF_SQL_DATE" value="#ActualLiveDate#">,
    BkPSA = <cfqueryparam cfsqltype="cf_sql_varchar" value="#BkPSA#" maxlength="50">,
    …same format for the remaining form fields…
    where id = <cfqueryparam cfsqltype="cf_sql_integer" value="#i#">

  2. Josh
    December 30, 2010 at 1:30 am | Permalink

    @Tom

    This Adobe ColdFusion docs example may give you enough sample code to help with your issue.

    http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec22c24-7f30.html

    Happy Holidays

  3. December 28, 2010 at 7:26 pm | Permalink

    @Tom
    Looks like you are going to have to loop 'em and group 'em. Might help to put the id first: 4206_ActualLiveDate
    then sort:
    <cfloop list="#listSort(structKeyList(form), 'numeric')#" index="i">
    <!—create and add to structure here—>
    </cfloop>

  4. Tom
    December 28, 2010 at 5:05 pm | Permalink

    Okay, I'm still having a devil of a time getting this to work.

    With my sample submitted data set,
    ActualLiveDate_4206
    ActualLiveDate_4207
    ActualLiveDate_4208
    BkPSA_4206
    BkPSA_4207
    BkPSA_4208
    ProposedLiveDate_4206
    ProposedLiveDate_4207
    ProposedLiveDate_4208

    If you notice the 4206, 4207, 4208, those values are the ids so I know which record to update. In other words, think of the data set like this:

    ActualLiveDate_4206
    BkPSA_4206
    ProposedLiveDate_4206

    ActualLiveDate_4207
    BkPSA_4207
    ProposedLiveDate_4207

    ActualLiveDate_4208
    BkPSA_4208
    ProposedLiveDate_4208

    My ultimate goal is to have an update query like below so in this scenario, this query would loop three times, one for id 4206, 4207, and 4208 (note it could have been 4206, 4210, 4400, etc). The id would be the (4206, 4207, 4208, etc).

    cfloop index=x list=#id# delimiters=,
    update table
    set
    actuallivedate = "#ActualLiveDate_valueofx#"
    BkPSA = "#BkPSA_valueofx#"
    ProposedLiveDate = "#ProposedLiveDate_valueofx#"
    where id = #valueofx#
    /cfloop

    I'm thinking I should put the data into a strcutures for each id and then loop over the structure updating the database on each loop.

    structure for
    4206
    ACTUALLIVEDATE 12/01/2010
    BKPSA Tom
    ProposedLiveDate 01/01/2011

    structure for
    4207
    ACTUALLIVEDATE 05/05/2011
    BKPSA David
    ProposedLiveDate 06/01/2011

    structure for
    4208
    ACTUALLIVEDATE 12/10/2010
    BKPSA Mary
    ProposedLiveDate 01/13/2011

  5. December 22, 2010 at 9:47 am | Permalink

    @Tom
    You're welcome. Let me know if you get it to work the way you want. Happy Holidays!

  6. Tom
    December 22, 2010 at 9:44 am | Permalink

    Geez, where are my manners! Thank you for your help.

  7. Tom
    December 22, 2010 at 9:44 am | Permalink

    Ah, I see what you are doing now and that <em>should</em> work. Let me try that. I'm only working a half-day today and then I've off for the rest of the year. It might be next year before I can follow up.

  8. December 21, 2010 at 7:02 pm | Permalink

    @Tom
    OK. Got a better picture now. Wouldn't this work then?
    <cfloop collection="#FORM#" item="i">
    <!— Field name —>
    #i#
    <br />
    <!— Field Value —>
    #Form[i]#
    </cfloop>

  9. Tom
    December 21, 2010 at 6:02 pm | Permalink

    Here is a sample of data being submitted. From this, you should be able to get an idea of what I'm referring to with the form field names above. I've only included a few of the form field names (3 of the 12 form fields total) but in the data below, there are 3 systems related to the project.

    ActualLiveDate_4206
    ActualLiveDate_4207
    ActualLiveDate_4208
    BkPSA_4206 ntreq
    BkPSA_4207 ntreq
    BkPSA_4208 0
    ProposedLiveDate_4206 12/13/2010
    ProposedLiveDate_4207 12/21/2010
    ProposedLiveDate_4208

  10. Tom
    December 21, 2010 at 5:54 pm | Permalink

    Can you elaborate? I'm not following. I probably didn't provide enough details in my example which is why this isn't clicking. Along with the sysName_###, I also have date_### where ### corresponds to the unique id in the database. I have a total of 12 fields (subject to change of course) and not every field will have data. If it were one form field, I'd just separate the form field using listFirst and listLast to obtain the column and the id but there is not a common character I can use to split the data up unless I make up my own.

    Stand by, typing this I may have sorted out my problem.

One Trackback