Simple example of a Form post to ColdFusion with jQuery

This post is more than 2 years old.

Following up on my earlier post demonstrating loading ColdFusion query data via jQuery, I've decided to do a few more simple jQuery+ColdFusion examples to give folks a taste of how easy it is to work with them both at the same time. For today's entry I'm going to show a very simple form post. This is as about as trivial as you can get, but I'm going to follow it up the next few days with a few more examples that will build upon it. So with that in mind, let's take a quick look at the code.

First I'll show the form. Notice that for this example I will not be doing any form validation. I want to keep things as nice and simple as possible.

<form id="testForm"> Name: <input type="text" name="name"><br/> Email: <input type="text" name="email"><br/> Gender: <select name="gender"> <option value="M">Male</option> <option value="F">Female</option> </select><br/> <input type="submit" value="Save" /> </form>

The form contains 3 fields: name, email, and gender. Notice I did not supply an action for the form. I'm going to let jQuery do everything. Now for the JavaScript.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(document).ready(function() { $("#testForm").submit(sendForm) });

function sendForm() { $.post('post.cfm',$("#testForm").serialize(),function(data,status){ $("#result").html(data) }); return false }

</script>

The first block of code simply says: When the page loads, I want you to bind the submit action of the form caleld testForm to a function called sendForm. This basically takes over the submit action. sendForm is a grand total of two lines. jQuery provides multiple ways to do Ajax calls. I'm using post for this example. The post function lets me specify a URL, some data, and a callback function. If callback functions confuse you (they were for me at first), just think of it as me telling jQuery: "Hey pal, when you are done sending the data, please run this function with the result."

How do I get the data? In the old days I might have used document.getElementById() on all the form fields. Luckily jQuery provides not one but two functions to handle this task for me. I can use serializeAray() to turn a form into a javaScript object. It will go throughout all the fields and create a name/value pair. It will be smart enough to know what to do for textfields, checkboxes, drop downs, you name it. An alternative to this is the serialize() function. This creates a string (think query string) version of the form data. The post() function will use either of these.

My callback function simply takes the result, trims it (don't forget how much ColdFusion likes whitespace!), and displays it within a div.

The ColdFusion side isn't doing much here. Let's take a look:

<cfparam name="form.name" default=""> <cfparam name="form.email" default=""> <cfparam name="form.gender" default="">

<cfoutput> Thanks for writing, <cfif form.gender is "m">Mr<cfelse>Ms</cfif> #form.name#. I've sent a subscription email to #form.email#. </cfoutput>

I do some basic validation on top and then simply output the result. I mention sending a subscription email, but don't really do it. (How many people think quite a few web apps lie like this?)

You can demo this here: http://www.coldfusionjedi.com/demos/jqform/test2.html

Ok, so pretty simple, but there are some things to think about it.

First, if I just wanted to load the result of posting the form into the div, I could have used the jQuery load function instead. I wanted to show a bit more... control over the process, so I used post() instead. I've said this before, but please remember - like ColdFusion, jQuery almost always provides more than one way to do somrthing.

Second, my form does zero error handling. Since I'm just dumping the result in a div, I could have done error handling in ColdFusion. What about errors in general? You can see I have access to a status variable. But as the docs say, this always returns true. This seems like a bug in jQuery, and it seems like it should be something simple to fix, so I'm assuming the issue is a bit more complex. In my testing, when I forced an error in the ColdFusion side, I still got 'success' for a status.

Third, just showing a message as the result is the simplest way to handle the result of the post. I could have also hidden the form. I could have done anything number of things really. What's nice though is how jQuery makes it easy to package up and wrap the logic all within a few lines. jQuery FTW!

Lastly, I mentioned I was going to skip client side validation in this post. I skipped it not because it was difficult, but because I wanted to create a simple example. I wrote a few blog entries on the topic and you should definitely check it out. (An introduction to jQuery and Form Validation)

As always, comments from the jQuery experts are welcome (well, any comments are welcome). My general plan for followups to this entry include: jQuery and a Login Form demo. jQuery and a Search Form demo. jQuery and a CAPTCHA demo where you can reload the CAPTCHA.

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Todd Rafferty posted on 3/20/2009 at 4:21 PM

Ray, have you looked into the awesomesause that is jQuery form plug-in? ( http://www.malsup.com/jquer... )

~Todd

Comment 2 by Andy Sandefer posted on 3/20/2009 at 5:02 PM

@Ray
You kind of touched on it a bit in your post but I'm still confused as to what seasoned jQuery developers are using in comparison to CF's setErrorHandler and setCallbackHandler functions. I totally see where you're building the callback into the one line submitter but how would this work if we were doing something more advanced than a form submit. For instance, calling a function that lives in a cfc to check for the existence of a conflicting primary key before we decided to even do the form submit.
Thanks for posting this, I may soon step outside of my comfort zone with CF's Ajax set and learn jQuery. I haven't been convinced yet and the jQuery team may have to call me and sing "If you don't know me by now" before I'll climb aboard.

Comment 3 by Raymond Camden posted on 3/20/2009 at 5:26 PM

@Todd: Nope. I can put it on my list though. In general I'm trying to avoid plugins for these blog entries. I kinda feel like the plugins can be a bit overwhelming to new jQuery users. Having multiple ways to do X is good. Having 500 ways to do X is overwhelming at times. :)

@Andy: So as I said, you can't really handle the error with .post. You _always_ get success back. You could return data that means something. By that I mean, instead of just a string like I did, I could have returned 0, which would mean 'bad', or 1, which would mean 'good'. Using the ajax() method gives you more fine grained control.

I'm still learning this stuff myself, so please keep that in mind. I'm not the expert here. ;)

Comment 4 by Todd Rafferty posted on 3/20/2009 at 5:33 PM

@Ray: I agree with you, but there's a handful of plugins I can't live without:

* form ( http://www.malsup.com/jquer... )
* metadata ( http://plugins.jquery.com/p... )
* validate (you discussed previously - http://docs.jquery.com/Plug...
* uiblock ( http://www.malsup.com/jquer... )

That's about it. None of my project begin without me copying these base plug-ins and putting them in place.

Comment 5 by Matt Williams posted on 3/20/2009 at 8:13 PM

Regarding error handling... for client side errors you can catch those before the $.post is even called. For server side errors, like Ray said, you can return anything. Like Ray mentioned, you could return "Successful update" and then show the values. Or you could return "Update failed" and an error message.

You could also return a json object that has a success flag (0/1 or T/F), a message string, and the form values.

Comment 6 by Sean Ford posted on 3/22/2009 at 2:32 AM

I have a question that is somewhat related to this post. I've been using a combination of JQuery and Coldfusion 8 for a while now and find them both indespensible. For ease of use, I've got a form that I am submitting via AJAX through CF8.
I am using CFAJAXPROXY to bind to a CFC like this:

<cfajaxproxy cfc="aqs3.contacts" jsclassname="CM">

Now, what I would like to do is access different methods of this CFC with information from several forms on the page. I know I can use the XXX.SetForm("formname") syntax to bind ALL of the values on the form to the method using named attributes. But what if I only wanted to call a method with a few of the form values? I can use JQuery (or simple JS) to get the values I need, but I can;t find a way to pass them as named attributes.

Since the SetForm command seems to figure out a way to do this, it must be possible, but for the life of me I can;t figure out how.

Any ideas?

--Sean

Comment 7 by Eric Lee posted on 3/22/2009 at 8:12 PM

That's a lot of code to do that. But it is what it is. I've been using jquery a lot myself lately.

For my web forms I've been using these guys:

http://www.formmailhosting.com

They do the form to email processing for me, but I like the example you came up with.

ERIC

Comment 8 by Raymond Camden posted on 3/22/2009 at 10:53 PM

Eric - you really think that's a lot of code? Looks pretty slim to me.

Comment 9 by Travis posted on 3/23/2009 at 7:52 AM

Ray, love the blog, nice example here again. I'm trying to upload a file using this technique. I have the below inputs in my form, and when I read the data like you showed using CF, I'm able to get the title field slick as can be, however, the uploadfile field is undefined when trying to retrieve it.

<input type="text" name="title">
<input type="file" name="uploadfile">

Any advice? Thanks

Comment 10 by Raymond Camden posted on 3/23/2009 at 5:23 PM

@Sean: If you want to use some form fields but not all, you would need to do it manually, or bind using specific form fields: {field1},{field2},{etc}. You really have to either take it all or do it manually one by one (which makes sense if you think about it).

@Travis: You can't do file uploads via Ajax. Period. You can only do it with iframe type hacks (which, for all intents and purposes ends up looking like normal Ajax). Please search my blog as I did an entry on this a few months ago.

Comment 11 by Adam posted on 8/12/2009 at 5:32 PM

Hi Ray -

I would like to add error checking to a form that I've created using this method. I have placed the error checking on the page that holds the form code (index.cfm) and have the form results post to another page (consultationPost.cfm). However, no matter where I place the form validation code, it isn't processed and the form results simply post without being validated.

Do I need to use jquery validation in this instance or am I just doing something wrong.

Thanks for any help,
Adam

Comment 12 by Shaun McCran posted on 8/13/2009 at 1:07 PM

This is a great post, I've been dipping my toe into this area much more recently, but I was missing the odd point here and there, and you've filled the gaps in for me. Hopefully one day the JQuery will 'roll off the tongue' like the CF does. until then I'll probably be stealing all your blogs on it :-)

Comment 13 by Raymond Camden posted on 8/15/2009 at 3:41 PM

@Adam: This sounds like an error is occurring. Have you looked at Firefox's Error window?

Comment 14 by Adam posted on 8/25/2009 at 8:31 PM

Hi Ray -

I've removed all error checking and have two forms. One is similar to your test2.html:

<cfoutput>

<cfform id="consultationForm">
<div id="consultations">
<!--- Our form submission flag. --->
<input type="hidden" name="submitted" value="1" />

<fieldset>
<legend>Consultations</legend>
<label for="client name">Client Username
<cfinput id="clientID"
name="clientID"
type="text"
value=""
maxlength="8"
<!---
onClick="ColdFusion.Window.show('userWin')"
bind="{clientLookup.client}"--->
/>

</label>
<label for="consultation date">Consultation Date
<input name="consultationDate" type="text" id="datepicker" />
</label>
<label for="consultation type">Consultation Type<br />
<select name="consultationType">
<option value="">&ndash; select &ndash;</option>
<option value="phone">Phone</option>
<option value="email">Email</option>
<option value="faceToFace">Face To Face</option>
<option value="online">Online</option>
</select>
</label>

<div class="clearer"></div>

<label for="Instructional Technology">Instructional Technology
<select id="instructionalTechnology" name="instructionalTechnology">
<option value="">&ndash; select &ndash;</option>
<option value="Oncourse">Oncourse</option>
<option value="Eportfolio">Eportfolio</option>
<option value="Web conferencing">Web conferencing</option>
<option value="Podcasting">Podcasting</option>
<option value="Video">Video</option>
<option value="Audio">Audio</option>
<option value="Turnitin">Turnitin</option>
<option value="Learning Objects">Learning Objects</option>
<option value="Web Development">Web Development</option>
<option value="Student Response Systems">Student Response Systems</option>
<option value="Collaborative web technology">Collaborative web technology</option>
<option value="Technology (other)">Technology (other)</option>
</select>
</label>
<label for="Instructional Design">Instructional Design
<select id="instructionalDesign" name="instructionalDesign">
<option value="">&ndash; select &ndash;</option>
<option value="Classroom Observations">Classroom Observations</option>
<option value="SGID">SGID</option>
<option value="Course Design">Course Design</option>
<option value="Syllabi">Syllabi</option>
<option value="Teaching Portfolio Development">Teaching Portfolio Development</option>
<option value="Assessment of Student Learning">Assessment of Student Learning</option>
<option value="SoTL ">SoTL</option>
<option value="Classroom Management Issues">Classroom Management Issues</option>
<option value="Academic Integrity">Academic Integrity</option>
<option value="Inclusive Teaching">Inclusive Teaching</option>
</select>
</label>
<div class="clearer"></div>

<label for="tags">Tags
<input id="tag1" name="tag1" type="text" maxlength="50" value="" tabindex="8"/>
<br />
<input id="tag2" name="tag2" type="text" maxlength="50" value="" tabindex="8"/>
<br />
<input id="tag3" name="tag3" type="text" maxlength="50" value="" tabindex="8"/>
<br />
<input id="tag4" name="tag4" type="text" maxlength="50" value="" tabindex="8"/>
</label>
<label for="internal notes">Internal Notes<br />
<textarea name="internalNotes" cols="20" rows="10" tabindex="7"></textarea>
</label>
<label for="notes to client">Notes to Client<br />
<textarea name="clientNotes" cols="20" rows="10" tabindex="9"></textarea>
</label>
<input type="hidden" value="#Now()#" />
<input class="submit"type="submit" value="Submit" /> <input class="reset" type="reset" value="Reset">
<div id="clearer"></div>
<div id="result"></div>
</fieldset>
</div>
</cfform>

My post.cfm is consultationPost.cfm and currently includes:

<cfoutput>

<cfquery name="qAddConsultation" datasource="myDSN">

INSERT INTO TEMPconsultations (submitDate,
transID,
weekOfYear,
username,
clientID,
consultationDate,
consultationType)

VALUES ('#DateFormat(now(), "mm/dd/yyyy")#',
'#transID#',
'#theWeek#',
'#trim(session.username)#',
'#trim(clientID)#',
'#trim(consultationDate)#',
'#trim(consultationType)#')

</cfquery>

<strong>Client</strong>: #form.clientID#<br />
<strong>Consultation Date</strong>: #form.consultationDate#<br />
<strong>Consultation Type</strong>: #form.consultationType#<br />

<strong>Instructional Technology</strong>: #form.instructionalTechnology#<br />
<strong>Instructional Design</strong>: #form.instructionalDesign#<br />
<strong>Tags</strong>: #form.tag1#, #form.tag2#, #form.tag3#, #form.tag4#<br />
<strong>Internal Notes</strong>: #form.internalNotes#<br />
<strong>Notes to Client</strong>: #form.clientNotes#
</cfoutput>

All works well until I include the query to write to the database.

I did not see an error window in Firefox and I'm not too familiar with the feature. This conversation tells me I need to.

Thank you.

Comment 15 by Raymond Camden posted on 8/26/2009 at 6:33 PM

You should stop using cfform if you wish to use jQuery validation. cfform has it's own validation libraries and routines and they can interfere with custom code.

Comment 16 by Jose posted on 10/15/2009 at 1:09 AM

awesome! thanks!!

Comment 17 by Bret posted on 12/4/2009 at 1:54 AM

Once again, you helped me find out what I was doing wrong. Appreciated!

Comment 18 by wen posted on 8/10/2010 at 11:02 PM

Hi, I am testing this code in IE7, but it seems like not working...Can you test to see if it works in your IE? Thanks.

Comment 19 by Raymond Camden posted on 8/10/2010 at 11:04 PM

I don't have IE7 myself. How does it appear to not be working? If you use a network monitoring tool like Charles do you see the post?

Comment 20 by wen posted on 8/10/2010 at 11:33 PM

Thanks Ray, it works right now...i guess it's old CF version cause problem...

Comment 21 by Mike Collins posted on 3/30/2011 at 5:25 PM

My forms post back to themselves and handle updates and deletes based on the button clicked. I was also finding that the serialize method was not sending my submit input values. So I added a few lines to the sample above and now it sends a formaction value based on the submit button.

<script src="/jquery/jquery-1.4.4.min.js"></script>
<form id="testForm">
<input type="hidden" name="formaction" id="formaction" value="noaction">
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
Gender:
<select name="gender">
<option value="M">Male</option>
<option value="F">Female</option>
</select><br/>
<input type="submit" value="Save" onClick="document.getElementById('formaction').value = 'saverecord';" />
<input type="submit" value="Delete" onClick="document.getElementById('formaction').value = 'deleterecord';" />
</form>

<script>
$(document).ready(function() {
$("#testForm").submit(sendForm)
});

function sendForm() {
$.post('testform.cfm',$("#testForm").serialize(),function(data,status){
$("#result").html(data)
});
return false
}

</script>

Comment 22 by Raymond Camden posted on 3/30/2011 at 6:35 PM

I'd use event handlers for your buttons instead of onClick.

Comment 23 by Ron Goldberg posted on 7/1/2011 at 9:33 PM

This feature is excellent...thank you. It doesn't seem to display the results with I.E. but fully functional in FF. Any idea why? Am I missing something? The post.cfm page is processing the data as I can send an e-mail; only the result text is missing from I.E.

Comment 24 by Raymond Camden posted on 7/1/2011 at 9:35 PM

Works for me in IE9. Are you an older one?

Comment 25 by Ron Goldberg posted on 7/1/2011 at 9:39 PM

I’m using IE8 and cross scripting with the latest FF.

Thanks,

Comment 26 by Raymond Camden posted on 7/1/2011 at 9:42 PM

Um well. Not sure. Sometimes IE is picky when you don't specify a content type, but in our case, we aren't sending JSON or XML back. So - not sure what to tell you. Upgrade to IE9. ;)

Comment 27 by Andy Idema posted on 4/11/2013 at 8:52 PM

Thanks for posting this Ray. Problem for me... My html form is posting automatically so I am not able to fill out the form or click submit. I'm using Chrome Version 26.0.1410.63.

Comment 28 by Raymond Camden posted on 4/11/2013 at 9:24 PM

If the form is posting, it means it the form handler is not firing or throwing an error. Check in the console to see if an error its there.

Comment 29 by Conan Green posted on 4/17/2013 at 9:19 PM

I wanted to find an alternative to using iframes for displaying coldfusion forms on our pages and this was extremely useful!

No more iframes! yay!

Comment 30 by Andy Idema posted on 5/2/2013 at 12:04 AM

When I put the full URL path in the post section it returns the webpage inside the result div instead of the code from the post.cfm page. When I leave out the full path it works fine.

$.post('http://www.mysite/post.cfm', - does not work

$.post('post.cfm', - works

Why?

Comment 31 by Raymond Camden posted on 5/2/2013 at 1:46 AM

Is your site on mysite.com? If not, it's the browser security blocking you. You have to be on the same site, subdomain, port, and protocol.

Comment 32 by Andy Idema posted on 5/2/2013 at 4:17 AM

@Ray - I used mysite.com as an example but the post.cfm file is in the same directory on the same server. My thought was that I could take this example and apply it to native phone app.

Comment 33 by Raymond Camden posted on 5/2/2013 at 4:51 AM

Ok, so what do you see in the console?

Comment 34 by Andy Idema posted on 5/2/2013 at 5:15 AM

I'm sorry... What do you mean by console?

Comment 35 by Raymond Camden posted on 5/2/2013 at 5:20 AM

The Chrome Dev Tools console. It is *essential* for diagnosing issues. Start here: http://www.raymondcamden.co...

Comment 36 by Andy Idema posted on 5/2/2013 at 4:51 PM

It says nothing. Just a right carrot. What happens when I use the full URL path is that it loads the entire webpage into the result div.

Comment 37 by Andy Idema posted on 5/2/2013 at 4:59 PM

I need to stop drinking at work. I was calling the original file in the full path. Once I called the post.cfm file with the full path it worked exactly as expected. Sheesh.

Comment 38 by Raymond Camden posted on 5/2/2013 at 5:55 PM

Dude, half of my blog posts are based on mistakes. Don't stress. ;)

Comment 39 by Andy Idema posted on 5/4/2013 at 2:11 AM

Hi Ray. I've got DW CS6 and I want to see if I can deploy this as a Phonegap app. Also, I'd like to test it on my phone (do I do that with Phonegap?) but am not sure what steps to take. Can you help?

Comment 40 by Raymond Camden posted on 5/4/2013 at 8:34 PM

That's kind of a big question. :) So, I'm going to punt and take an easy way. I'd suggest you watch my video on PhoneGap as it talks about how to do this. It does NOT cover Dreamweaver per se, but it should still be helpful.

http://www.raymondcamden.co...

Comment 41 by Andy Idema posted on 5/4/2013 at 9:39 PM

Great vid. Very helpful for me thank you.

Comment 42 by Andy Idema posted on 5/15/2013 at 7:09 AM

Hello again Ray. After watching several of your Phonegap demos and reading several tutes I am getting up to speed quickly on Phonegap build. Thus far I've waded through the initial config steps (config.xml, the ios key process, splash screens, icons, etc) and have a pretty lame test app up and running. I tried to take it a step further and added the code from this tute into my index.html to see if I could get it to post to the same file that tested successfully. When I fill out the form fields on my phone app and click save all that happens is that it clears out the fields. I have phonegap.js, and jquery 1.9.1 as includes.

Comment 43 by Raymond Camden posted on 5/15/2013 at 2:56 PM

If the form fields clear, it typically means your form handling code is broken. You should test your code on the desktop first. The actual POST will fail as it is going to another server, but you can at least see if the form submit handler is running.

I assume you know how to use the Chrome console to help you debug this. :)

Comment 44 by Andy Idema posted on 5/15/2013 at 4:21 PM

Oh dude yer gonna get it. I just threw my crumpled up notes at you. As you suspected I get the XMLHttpRequest cannot load .. Origin null is not allowed by Access-Control-Allow-Origin when I try it locally in Chrome. I'm going to use the iPhone Config Utility and see if it will tell me anything when I try it on the phone.

Comment 45 by Andy Idema posted on 5/15/2013 at 5:49 PM

Ok this is what the iPhone Configuration Utility is telling me...

May 15 07:45:41 Phone-of-Ides kbd[50] <Warning>: -[TIXPCDataTransport _handleForPurpose:withReplyBlock:] couldn't get data source for purpose=__TIRDTAB
May 15 07:45:45 Phone-of-Ides kernel[0] <Debug>: launchd[13840] Builtin profile: PasteBoard (sandbox)
May 15 07:45:51 Phone-of-Ides TestApp[13838] <Warning>: Resetting plugins due to page load.
May 15 07:45:51 Phone-of-Ides TestApp[13838] <Warning>: ERROR whitelist rejection: url='http://ajax.googleapis.com/...
May 15 07:45:51 Phone-of-Ides TestApp[13838] <Warning>: ERROR whitelist rejection: url='http://ajax.googleapis.com/...
May 15 07:45:51 Phone-of-Ides TestApp[13838] <Warning>: ERROR whitelist rejection: url='http://ajax.googleapis.com/...
May 15 07:45:51 Phone-of-Ides TestApp[13838] <Warning>: Finished load of: file:///var/mobile/Applications/DA9CE3B1-92AC-455B-BBB1-AB942F34F03C/TestApp.app/www/index.html?...

Comment 46 by Raymond Camden posted on 5/15/2013 at 5:52 PM

To your first comment, again, thats a good thing. It means, at least, that your form handler is running and trying to call the remote URL.

Second comment. Ah, whitelist rejection. You need to add your domain to the whitelist.

http://docs.phonegap.com/en...

Comment 47 by Andy Idema posted on 5/15/2013 at 6:01 PM

The last line in the Util is promising... "TestApp.app/www/index.html?..." but it's just not showing up in the result div.

Comment 48 by Raymond Camden posted on 5/15/2013 at 6:03 PM

Did you see my comment about white listing the domain?

The last line in the log happens because your Ajax portion failed and the form handler than returned to just submitting itself. Hence your app reloaded w/ form data. You can ignore that.

Comment 49 by Andy Idema posted on 5/15/2013 at 6:07 PM

Ok I will ignore. I read through the phonegap doc and then double checked my config.xml... sure enough. "<access origin="http://127.0.0.1*"/> <!-- allow local pages -->" so I'm going to add the domain of the server it's calling and see what that does. Thanks for the tip!

Comment 50 by Andy Idema posted on 5/15/2013 at 6:54 PM

Ok that was definitely it. Working now. Thanks Ray! I whitelisted my server and google and just like that... it's working. I'd like to thank you for this presentation as well: http://www.raymondcamden.co...

I've combined the post on this page and the other I just referenced to get my first phonegap build app up and running (albeit hello worldish). Thank you much. There are so many details and the documentation isn't the best on the Phonegap site. I may just need to put some help docs out there somewhere for beginners like myself. Anyway... cheers.

Comment 51 by Andy Idema posted on 5/16/2013 at 6:24 PM

Ray, once the user posts the form, is there a way to have the result get returned to another div that doesn't contain the original form? I have a few divs that are setup like this...

<div data-role="page" id="descriptions">
<div data-role="header">
<h1>Descriptions</h1>
</div>
<div data-role="content" data-theme="c">
Results here please
</div>
<div data-role="footer">
<h4>&copy; MySite - 2013</h4>
</div>
</div>

So let's say I want the form post results to end up inside the descriptions div... how do I do that?

Comment 52 by Raymond Camden posted on 5/16/2013 at 6:29 PM

If using jQuery, your success handler can take the result and write it out anywhere you want.

Comment 53 by Andy Idema posted on 5/16/2013 at 6:30 PM

I'm wondering if I just point to descriptions id instead of result... No way it can be that easy.

Comment 54 by Andy Idema posted on 5/16/2013 at 7:00 PM

So in this particular example, function(data,status{$("#descriptions").html(data)}); is indeed sending the result to the descriptions div which is what I want. What I'm wanting to do though is have the form navigate to that div after the data is submitted. Do I put an action="#descriptions" in the form?

Comment 55 by Raymond Camden posted on 5/16/2013 at 9:25 PM

It depends on what you mean by 'navigate'. You can scroll to it. You can show it. Etc.

Comment 56 by Andy Idema posted on 5/22/2013 at 2:20 AM

Hi Ray. I have this code setup in my app so the results load into the div with a hyperlink to a different page. The problem I'm having is that it is navigating to a different address than the full path I have as the hyperlink. Example. My link says <a href="http://www.mysite.com/mobil...">Link</a> But its navigating to http://www.mysite.com/mobil... and throwing an error. I am guessing that I need to return something different than an html path on the hyperlinked result? Do I need to do something other than just loading results into a div?

Comment 57 by Andy Idema posted on 5/22/2013 at 4:34 AM
Comment 58 by Andy Idema posted on 5/23/2013 at 1:07 AM

Also, how do you add a loading.gif to this?

Comment 59 by Raymond Camden posted on 5/23/2013 at 1:20 AM

@Andy (last comment): You could add a loading gif to your page that is hidden with CSS. Then use jQuery's show() command to show it, and hide to hide it, before and after the Ajax call.

Comment 60 by Andy Idema posted on 5/23/2013 at 11:08 PM

Ray I ended up using some of the logic from this post: http://www.raymondcamden.co.... JQM's docs say you can use $.mobile.loading( "show" ); and hide but I couldn't get it to work. I did however get it working using your example so thank you.

Comment 61 by Muskie posted on 8/27/2013 at 9:23 PM

I tried the demo and I tried to use this technique in development and neither seems to work in Firefox on Windows. I'm not sure the exact version of either, but hitting the button doesn't load a new page showing the results of the form submission which is obviously what we both want.

Comment 62 by Raymond Camden posted on 8/27/2013 at 9:40 PM

When you open up Firebug, what do you see?

Comment 63 by Muskie posted on 8/28/2013 at 12:08 AM

I don't know why your demo doesn't work on my work machine, but on our actual website we are using jquery 1.6.something which might be an issue. This is what I see on Firefox's javascript console.

[11:57:49.522] Use of attributes' specified attribute is deprecated. It always returns true.

I tried to post before and it seems to have vanished...

Comment 64 by Muskie posted on 8/28/2013 at 12:10 AM

I just tried your demo code and this is what Firefox's JavaScript console said. This is for loading the page and then after clicking the button too.

[13:23:48.556] ReferenceError: $ is not defined @ http://www.coldfusionjedi.c...
[13:23:48.561] The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. @ http://www.coldfusionjedi.c...
--
[13:24:02.225] A form was submitted in the windows-1252 encoding which cannot encode all Unicode characters, so user input may get corrupted. To avoid this problem, the page should be changed so that the form is submitted in the UTF-8 encoding either by changing the encoding of the page itself to UTF-8 or by specifying accept-charset=utf-8 on the form element. @ http://www.coldfusionjedi.c...
--
[13:24:07.236] ReferenceError: $ is not defined @ http://www.coldfusionjedi.c...
[13:24:07.241] The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. @ http://www.coldfusionjedi.c...

Comment 65 by Raymond Camden posted on 8/28/2013 at 12:16 AM

Err, not sure what to say. $ is not defined means jQuery didn't load. When I run the demo, jQuery's library loads just fine. I'm using this URL for jQuery:

http://ajax.googleapis.com/...

Try to open that in your browser and if it doesn't work, maybe your network is blocking it.

Comment 66 by Muskie posted on 8/28/2013 at 1:18 AM

It is possible my employer's firewall is messing with things, it wouldn't be the first time. I don't think it is the most developer friendly company, but I thought my software development days were done, now I work on a legacy extranet written in ColdFusion. I never started programming in ColdFusion until 2013 and I've been programming a long time.

I am trying to make your technique work on the extranet and I found this StackOverflow thread about the error I get so maybe it is the version of JavaScript that the extranet is using.

stackoverflow.com/questions...

Comment 67 by Muskie posted on 8/28/2013 at 1:19 AM

I tried your link to jquery, and Firefox through up this message:

"Firefox has detected that the server is redirecting the request for this address in a way that will never complete."

Firefox and the firewall are definitely possible sources of problems, which is disappointing as I had a good idea on how I wanted to do the UI using jQuery/JavaScript, now I will have to do something less slick.

Comment 68 by Raymond Camden posted on 8/28/2013 at 1:20 AM

Oh, well for *that* issue, keep in mind my code here is 4 years old. :)

Comment 69 by Raymond Camden posted on 8/28/2013 at 1:21 AM

Well, if you need it work, I'd ping IT. They are being stupid IMO to block you from loading jQuery. If you are learning on the job, I'd simply copy it to a USB stick at home and bring it to work. But still - I'd ping IT.

Comment 70 by Muskie posted on 8/28/2013 at 1:24 AM

If it makes you feel better it works in IE 8, the official corporate browser. I'll never be a JavaScript guy because far too many times it will work in one browser and inexplicably not work in another browser, once again that seems to be the case.

I installed Firefox on my work machine specifically for debugging, it should be newer and superior to the official IE 8 browser, but clearly Firefox is stricter. I also wanted to open a popup, I need to step back and think things through. I may have to try my code in IE, but it appears I need a new technique, one that works in jquery 1.6.1 and Firefox...

Comment 71 by Raymond Camden posted on 8/28/2013 at 1:33 AM

" I'll never be a JavaScript guy because far too many times it will work in one browser and inexplicably not work in another browser, once again that seems to be the case. "

I can promise you it gets better. :) Again - keep in mind this post is four years old. I may not have been doing things the best way.

Comment 72 by Sean posted on 10/24/2013 at 12:39 AM

Thanks Raymond, your tutorial helped me submit the form to a database. Next I am trying to add jquery function where once submitted, text fields get cleared onsubmit, so it can be quickly resubmitted with next user info.

This just shows on how to submit onto a database.
Form.cfm

<html>

<head>
<script src="http://ajax.googleapis.com/..."></script>
<script>
$(document).ready(function() {
$("#testForm").submit(sendForm)
});

function sendForm() {
$.post('post.cfm',$("#testForm").serialize(),function(data,status){
$("#result").html(data)
});
return false
}

</script>
</head>

<body>

<form id="testForm">
Name: <input type="text" name="name"><br/>

<input type="submit" value="Save" />
</form>

<div id="result"></div>
</body>

</html>

post.cfm

<cfquery datasource="MSSQLSERVER" result="mysqlresult">

Insert Into fd_TABLE (fd_uid)
values ('#form.name#')

</cfquery>

<cfoutput>

#form.name#

</cfoutput>

Comment 73 by Raymond Camden posted on 10/24/2013 at 4:08 AM

In the result handler, just set the form field values to "".

Also, you really shouldn't use "naked" query values like that - use cfqueryparam.

Comment 74 by Sean posted on 10/24/2013 at 4:22 PM

Thanks again Raymond. I added the cfqueryparam and for form reset I used
$( '#testForm' ).each(function(){
this.reset();

Does the job.

Comment 75 by Jan posted on 12/17/2013 at 5:38 PM

Hi there,

Love having found this - it is something I have searched for for a long time and it is so nice and simple!!

However - using your example in the validate article, I can't get that side and this to work together! Where would I be putting this validation code?

When I put ******* in:

$(document).ready(function() {
$("#signup").submit(sendForm);
});

It just submits the form and reloads the page?!

Any further tutorials on putting the two together?

Many thanks for all your useful articles.

Jan

Comment 76 by Raymond Camden posted on 12/17/2013 at 6:02 PM

To do form validation in JavaScript, you need to prevent the normal form submission. You would do something like this

$("#signup").submit(function(e) {
e.preventDefault();
//do validation here
});

Comment 77 by Jan posted on 12/17/2013 at 7:59 PM

Thank you - I will take it for a spin and if I have any problems I will no doubt mine your mind for help!!

Nice that there is a place that actually gets replies - and so quickly.

You are a great help - thank you.

Jan

Comment 78 by Jan posted on 12/17/2013 at 10:04 PM

I am almost there...

Based on your Ajax submit and using the validate that you suggest in the other article, it works, but if you keep clicking submit it bypasses the validate.

My code is here:

<form id="signup">

<h5>Newsletter</h5>

<input type="text" name="email" id="email" placeholder="Email address" /><button id="testForm" class="btn btn-7 btn-7f btn-icon-only icon-heart">Like</button>

<small id="result"></small>

<small>Enter your email address for updates of new properties</small>

</form>

<script src="http://code.jquery.com/jque..." type="text/javascript"></script>
<script src="js/jquery.validate.js"></script>

<script type="text/javascript">

$("#signup").validate({
rules: {
email: {
required: true,
email: true
}
},
messages: {
email: {
required: "REQUIRED",
email: "INVALID"
}
},
submitHandler: function(form) {
$("#signup").submit(sendForm);
}
});

function sendForm() {
$.post('<cfoutput>#application.domain#</cfoutput>post.cfm',$("#signup").serialize(),function(data,status){
$("#result").html(data)
});

return false
}

</script>

The handler is as follows:

<cfparam name="form.email" default="">

<cfoutput>
Thank you for signing up #form.email#
</cfoutput>

<script type="text/javascript">

$( '#signup' ).each(function(){
this.reset();
});

</script>

Sorry if I am asking too much of you as I am just some random asking for help!!!

Thank you very much in advance if you can help.

Jan

Comment 79 by Raymond Camden posted on 12/17/2013 at 10:43 PM

Are you saying that if you edit the form to make it invalid, when you click submit, it isn't rechecked?

Comment 80 by Jan posted on 12/18/2013 at 12:09 AM

Hi there

WhenI click submit with no entry it validates correctly - when I then try text which isnt an email it says invalid - so far so good!!

When I enter an email address and click submit after the above - it does nothing, then click submit again and it works.

THEN if I press submit once the form is processed it will just process the form every time I click submit, by passing validation until I refresh the page!

Does that make sense?

Thank you for your time.

Jan

Comment 81 by Raymond Camden posted on 12/18/2013 at 12:12 AM

Kinda. I think at this point it makes more sense for us to take this offline. Can you please ping me directly and also put this online where I can run it myself. My email address is in the header.

Comment 82 by Jan posted on 12/18/2013 at 2:35 AM

Hi there,

No worries - I will do this tomorrow as the files are at work and I will upload them there to email you.

Many thanks

Jan

Comment 83 by ECL posted on 9/16/2014 at 9:26 PM

Howdy! Good simple example, cept I seem to have trouble getting it to fire with some error authentication. I am new to CF and JQuery but I have a simple textarea form and a send button which I would like an email sent out when they click. Part of it though is I want to use this in a modal window so I don't want the page to disappear or the parent page to be wiped out.

But in this example it's just a single page form I am trying to get to work

This is all the code (not much anyway) but here is what my script looks like against yours.

Detail.cfm
<script src="http://ajax.googleapis.com/..."></script>
<script>

$(document).ready(function() { $("#frmSubmit").submit(sendForm) });

function SubmitForm()
{
Tbody = document.getElementById("txtBody");

if(Tbody.value == '')
alert('Please enter some text for your message.');
else
$("#frmSubmit").submit(sendForm);
//frmSubmit.submit();
}

function sendForm()
{
$.post('Detail.cfm',$("#frmSubmit").serialize(),function(data,status){
$("#result").html(data)
});
return false
}
</script>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email Test</title>
</head>

<body>

<cfif isdefined("form.txtBody")>
<CFMAIL TO=someguy@place.com
FROM= otherdude@place.com
SUBJECT= "Thank you for submitting the information">Message below sent from user #Session.UserID# , the message is:

#form.txtBody#

</CFMAIL>
<cfelse>

<form method="post" name="frmSubmit" id="frmSubmit" action="Detail.cfm" >
<table id="tblError" name="tblError" >
<tr><td colspan="2" class="ui-widget-content" align="center">Suggested Detail to Submit</td></tr>
<tr><td colspan="2" class="ui-widget-content">System does not recognize detail. Please provide a suggested name that you think should be associated with this detail in the boxes below. Click Send when done.</td></tr>
<tr><td colspan="2" class="ui-widget-content" valign="top">Comments: </td></tr>
<tr><td class="ui-widget-content" ><textarea cols="75" rows="5" id="txtBody" name="txtBody" class="ui-widget-content"></textarea></td><td class="ui-widget-content" ><input type="button" id="btnSubmit" value="Send" class="ui-widget-content" align="middle" onclick="SubmitForm();" /></td></tr>
</table></form>
</cfif>
</body>
</html>

So if you notice the one comment line in the JavaScript, if I use //frmSubmit.submit(); the email goes out, but then of course I lose the page. If I use the other method nothing happens when I click send, meaning the page sits there but I don't get the email (I am just using my own email address for testing).

Not sure why it's not firing, any ideas? Any help would be appreciated, as I am new to JQuery and CF. Thanks.

Comment 84 by Raymond Camden posted on 9/16/2014 at 9:58 PM

No, I don't see the commented out line. Please do not post code blocks here. As the form says, use a Gist or Pastebin.

You want to use e.preventDefault() where e is the argument you would add to your form submit handler, this stops the 'normal' form action and lets you handle it completely.

Comment 85 by Jan posted on 10/3/2014 at 3:43 PM

Hello,

Is it possible to set a parameter with this and have the page where the form sits pick up on it? So of instance if I wanted to use this technique for a login form - so the form submits to the handler and that pushes back the fact that the user is logged in and then some funky things can fade in?!

Thanks

Jan

Comment 86 by Raymond Camden posted on 10/3/2014 at 3:46 PM

You mean work with the result? If so, the code already does that. The result is HTML and I use code to inject it into the DOM. If you wanted to return data, like in the form of JSON, you could just as easily do that.

Comment 87 by Jan posted on 10/3/2014 at 3:52 PM

Hi Raymond - thanks for the speedy reply.

I am using Dreamweaver default login code (for this testing) and the login form is set up using this technique - the form is a full page overlay, and when the login is successful I wanted to fade out the login form as the session is now set - but wouldn't the page where the form sits need to be refreshed to pick up on the fact that the session is now in progress, thus negating the submission of the form without a page refresh?

I hope that makes sense - I feel I am gibbering...

Jan

Comment 88 by Jan posted on 10/3/2014 at 5:20 PM

Ignore my last gibberish - I have got it working and now have a far better understanding of how this world!!

Cheers

Jan

Comment 89 by Dave posted on 11/24/2014 at 9:26 AM

Thanks Raymond! I have been looking for a simple example of this with Coldfusion for weeks now!