Twitter: raymondcamden


Address: Lafayette, LA, USA

Simple example of a Form post to ColdFusion with jQuery

03-20-2009 32,461 views jQuery, JavaScript, ColdFusion 88 Comments

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.

view plain print about
1<form id="testForm">
2    Name: <input type="text" name="name"><br/>
3    Email: <input type="text" name="email"><br/>
4    Gender:
5    <select name="gender">
6    <option value="M">Male</option>    
7    <option value="F">Female</option>
8    </select><br/>     
9    <input type="submit" value="Save" />
10</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.

view plain print about
1<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
2<script>
3$(document).ready(function() {
4    $("#testForm").submit(sendForm)
5});
6
7function sendForm() {
8    $.post('post.cfm',$("#testForm").serialize(),function(data,status){
9        $("#result").html(data)
10    });
11    return false
12}
13
14</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:

view plain print about
1<cfparam name="form.name" default="">
2<cfparam name="form.email" default="">
3<cfparam name="form.gender" default="">
4
5<cfoutput>
6Thanks for writing,
7<cfif form.gender is "m">Mr<cfelse>Ms</cfif> #form.name#.
8I've sent a subscription email to #form.email#.
9</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.

88 Comments

  • Commented on 03-20-2009 at 7:21 AM
    Ray, have you looked into the awesomesause that is jQuery form plug-in? ( http://www.malsup.com/jquery/form/ )

    ~Todd
  • Commented on 03-20-2009 at 8:02 AM
    @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.
  • Commented on 03-20-2009 at 8:26 AM
    @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. ;)
  • Commented on 03-20-2009 at 8:33 AM
    @Ray: I agree with you, but there's a handful of plugins I can't live without:

    * form ( http://www.malsup.com/jquery/form/ )
    * metadata ( http://plugins.jquery.com/project/metadata )
    * validate (you discussed previously - http://docs.jquery.com/Plugins/Validation)
    * uiblock ( http://www.malsup.com/jquery/block/ )

    That's about it. None of my project begin without me copying these base plug-ins and putting them in place.
  • Commented on 03-20-2009 at 11:13 AM
    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.
  • Sean Ford #
    Commented on 03-21-2009 at 5:32 PM
    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
  • Eric Lee #
    Commented on 03-22-2009 at 11:12 AM
    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
  • Commented on 03-22-2009 at 1:53 PM
    Eric - you really think that's a lot of code? Looks pretty slim to me.
  • Travis #
    Commented on 03-22-2009 at 10:52 PM
    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
  • Commented on 03-23-2009 at 8:23 AM
    @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.
  • Adam #
    Commented on 08-12-2009 at 8:32 AM
    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
  • Commented on 08-13-2009 at 4:07 AM
    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 :-)
  • Commented on 08-15-2009 at 6:41 AM
    @Adam: This sounds like an error is occurring. Have you looked at Firefox's Error window?
  • Adam #
    Commented on 08-25-2009 at 11:31 AM
    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.
  • Commented on 08-26-2009 at 9:33 AM
    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.
  • Jose #
    Commented on 10-14-2009 at 4:09 PM
    awesome! thanks!!
  • Commented on 12-03-2009 at 2:54 PM
    Once again, you helped me find out what I was doing wrong. Appreciated!
  • Commented on 08-10-2010 at 2: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.
  • Commented on 08-10-2010 at 2: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?
  • Commented on 08-10-2010 at 2:33 PM
    Thanks Ray, it works right now...i guess it's old CF version cause problem...
  • Commented on 03-30-2011 at 8:25 AM
    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>
  • Commented on 03-30-2011 at 9:35 AM
    I'd use event handlers for your buttons instead of onClick.
  • Commented on 07-01-2011 at 12: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.
  • Commented on 07-01-2011 at 12:35 PM
    Works for me in IE9. Are you an older one?
  • Commented on 07-01-2011 at 12:39 PM
    I’m using IE8 and cross scripting with the latest FF.

    Thanks,
  • Commented on 07-01-2011 at 12: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. ;)
  • Andy Idema #
    Commented on 04-11-2013 at 11:52 AM
    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.
  • Commented on 04-11-2013 at 12: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.
  • Conan Green #
    Commented on 04-17-2013 at 12: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!
  • Andy Idema #
    Commented on 05-01-2013 at 3:04 PM
    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?
  • Commented on 05-01-2013 at 4:46 PM
    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.
  • Andy Idema #
    Commented on 05-01-2013 at 7:17 PM
    @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.
  • Commented on 05-01-2013 at 7:51 PM
    Ok, so what do you see in the console?
  • Andy Idema #
    Commented on 05-01-2013 at 8:15 PM
    I'm sorry... What do you mean by console?
  • Commented on 05-01-2013 at 8:20 PM
    The Chrome Dev Tools console. It is essential for diagnosing issues. Start here: http://www.raymondcamden.com/index.cfm/2013/3/21/N...
  • Andy Idema #
    Commented on 05-02-2013 at 7:51 AM
    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.
  • Andy Idema #
    Commented on 05-02-2013 at 7:59 AM
    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.
  • Commented on 05-02-2013 at 8:55 AM
    Dude, half of my blog posts are based on mistakes. Don't stress. ;)
  • Andy Idema #
    Commented on 05-03-2013 at 5:11 PM
    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?
  • Commented on 05-04-2013 at 11:34 AM
    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.com/index.cfm/2013/5/2/Re...
  • Andy Idema #
    Commented on 05-04-2013 at 12:39 PM
    Great vid. Very helpful for me thank you.
  • Andy Idema #
    Commented on 05-14-2013 at 10:09 PM
    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.
  • Commented on 05-15-2013 at 5:56 AM
    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. :)
  • Andy Idema #
    Commented on 05-15-2013 at 7:21 AM
    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.
  • Andy Idema #
    Commented on 05-15-2013 at 8:49 AM
    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/ajax/libs/jquery/1.9.1/...'
    May 15 07:45:51 Phone-of-Ides TestApp[13838] <Warning>: ERROR whitelist rejection: url='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/...'
    May 15 07:45:51 Phone-of-Ides TestApp[13838] <Warning>: ERROR whitelist rejection: url='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/...'
    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?name=Test&email=Test@email.com&gender=M
  • Commented on 05-15-2013 at 8:52 AM
    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/2.7.0/guide_whitelist_...
  • Andy Idema #
    Commented on 05-15-2013 at 9:01 AM
    The last line in the Util is promising... "TestApp.app/www/index.html?name=Test&email=Test@email.com&gender=M" but it's just not showing up in the result div.
  • Commented on 05-15-2013 at 9:03 AM
    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.
  • Andy Idema #
    Commented on 05-15-2013 at 9:07 AM
    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!
  • Andy Idema #
    Commented on 05-15-2013 at 9:54 AM
    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.com/index.cfm/2013/5/2/Re...

    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.
  • Andy Idema #
    Commented on 05-16-2013 at 9:24 AM
    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?
  • Commented on 05-16-2013 at 9:29 AM
    If using jQuery, your success handler can take the result and write it out anywhere you want.
  • Andy Idema #
    Commented on 05-16-2013 at 9:30 AM
    I'm wondering if I just point to descriptions id instead of result... No way it can be that easy.
  • Andy Idema #
    Commented on 05-16-2013 at 10:00 AM
    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?
  • Commented on 05-16-2013 at 12:25 PM
    It depends on what you mean by 'navigate'. You can scroll to it. You can show it. Etc.
  • Andy Idema #
    Commented on 05-21-2013 at 5:20 PM
    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/mobile/details.cfm?id=2731&q...; But its navigating to http://www.mysite.com/mobile/#/mobile/details.cfm?... 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?
  • Andy Idema #
    Commented on 05-21-2013 at 7:34 PM
    Found http://www.raymondcamden.com/index.cfm/2009/3/17/S...
  • Andy Idema #
    Commented on 05-22-2013 at 4:07 PM
    Also, how do you add a loading.gif to this?
  • Commented on 05-22-2013 at 4:20 PM
    @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.
  • Andy Idema #
    Commented on 05-23-2013 at 2:08 PM
    Ray I ended up using some of the logic from this post: http://www.raymondcamden.com/index.cfm/2011/12/21/.... 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.
  • Commented on 08-27-2013 at 12: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.
  • Commented on 08-27-2013 at 12:40 PM
    When you open up Firebug, what do you see?
  • Commented on 08-27-2013 at 3:08 PM
    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...
  • Commented on 08-27-2013 at 3:10 PM
    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.com/demos/jqform/test2.h...:6" target="_blank">http://www.coldfusionjedi.com/demos/jqform/test2.h...
    [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.com/demos/jqform/test2.h...
    --
    [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.com/demos/jqform/test2.h...
    --
    [13:24:07.236] ReferenceError: $ is not defined @ http://www.coldfusionjedi.com/demos/jqform/test2.h...?name=Andrew&email=andrew%40muschamp.ca&gender=M:6" target="_blank">http://www.coldfusionjedi.com/demos/jqform/test2.h...
    [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.com/demos/jqform/test2.h...?name=Andrew&email=andrew%40muschamp.ca&gender=M
  • Commented on 08-27-2013 at 3:16 PM
    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/ajax/libs/jquery/1/jque...

    Try to open that in your browser and if it doesn't work, maybe your network is blocking it.
  • Commented on 08-27-2013 at 4:18 PM
    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/8389841/using-jquery-to-determine-selected-option-causes-specified-attribute-is-depreca/
  • Commented on 08-27-2013 at 4:19 PM
    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.
  • Commented on 08-27-2013 at 4:20 PM
    Oh, well for that issue, keep in mind my code here is 4 years old. :)
  • Commented on 08-27-2013 at 4:21 PM
    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.
  • Commented on 08-27-2013 at 4:24 PM
    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...
  • Commented on 08-27-2013 at 4:33 PM
    " 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.
  • Sean #
    Commented on 10-23-2013 at 3:39 PM
    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/ajax/libs/jquery/1/jque...;
    <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>
  • Commented on 10-23-2013 at 7:08 PM
    In the result handler, just set the form field values to "".

    Also, you really shouldn't use "naked" query values like that - use cfqueryparam.
  • Sean #
    Commented on 10-24-2013 at 7:22 AM
    Thanks again Raymond. I added the cfqueryparam and for form reset I used
    $( '#testForm' ).each(function(){
    this.reset();

    Does the job.
  • Jan #
    Commented on 12-17-2013 at 6:38 AM
    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
  • Commented on 12-17-2013 at 7:02 AM
    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
    });
  • Jan #
    Commented on 12-17-2013 at 8:59 AM
    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
  • Jan #
    Commented on 12-17-2013 at 11:04 AM
    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/jquery-latest.js"; 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
  • Commented on 12-17-2013 at 11:43 AM
    Are you saying that if you edit the form to make it invalid, when you click submit, it isn't rechecked?
  • Jan #
    Commented on 12-17-2013 at 1:09 PM
    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
  • Commented on 12-17-2013 at 1:12 PM
    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.
  • Jan #
    Commented on 12-17-2013 at 3:35 PM
    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
  • ECL #
    Commented on 09-16-2014 at 12: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/ajax/libs/jquery/1/jque...;
    <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.
  • Commented on 09-16-2014 at 12: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.
  • Jan #
    Commented on 10-03-2014 at 6:43 AM
    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
  • Commented on 10-03-2014 at 6:46 AM
    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.
  • Jan #
    Commented on 10-03-2014 at 6:52 AM
    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
  • Jan #
    Commented on 10-03-2014 at 8:20 AM
    Ignore my last gibberish - I have got it working and now have a far better understanding of how this world!!

    Cheers

    Jan

Post Reply

Please refrain from posting large blocks of code as a comment. Use Pastebin or Gists instead. Text wrapped in asterisks (*) will be bold and text wrapped in underscores (_) will be italicized.

Leave this field empty