Fetching Data With jQuery

I've been doing more and more with jQuery and thought I'd post a few examples. In my current project I'm building a really huge form for people to fill out if they want to work from home. The form needs to be approved by different people depending on your division. So on my form I have a series of radio buttons and based on the users selection the form will submit the request to the appropriate manager. I wanted to provide some form of visual feedback and came up with this:

Fetching Data with jQuery

Now lets take a look at the code to see how I did it...

First my form is generated dynamically so I've simplified it quite a bit for this example:

My form:

HTML:
  1. <div class="editfield">
  2.     <input type="radio" name="divisionid" id="divisionid1" value="1"/> OD
  3.     <input type="radio" name="divisionid" id="divisionid2" value="2"/> OM
  4.     <input type="radio" name="divisionid" id="divisionid3" value="3"/> DERT
  5.     <input type="radio" name="divisionid" id="divisionid4" value="4"/> DIR
  6.     <input type="radio" name="divisionid" id="divisionid5" value="5"/> NTP
  7.     <input type="radio" name="divisionid" id="divisionid6" value="6"/> ORAR
  8. </div>
  9.  
  10. <div id="loading">Loading... </div>
  11.  
  12. <label for="approval">Approving Official Signature</label>
  13. <input type="hidden" name="approval" id="approval" value=""/>
  14. <input type="text" name="approval_dsp" id="approval_dsp" value="(select division above)"/>

This gives me my series of radio buttons, a div to contain my "Loading" animation, and finally the text field which will receive my approvers name.

For the dynamic loading graphic - there are a few sites out there with graphics you can grab or create. Then it's a simple matter of creating a div container to display it and some simple CSS:

Loading CSS:

CSS:
  1. <style type="text/css">
  2. #loading {
  3.     background: #fff url('../img/ajax-loading.gif') left no-repeat;
  4.     color: #369;
  5.     display: none;
  6.     font-weight: bold;
  7.     margin: 1em 0;
  8.     padding-left: 20px;
  9.     }
  10. </style>

This initially hides the loading graphic (display: none) and we'll later use jQuery to flip that on when we need it.

Next - the jQuery magic! For help installing and getting jQuery setup - check out the "How jQuery Works" tutorial on the jQuery wiki.

For this example - I'm also using the jQuery Form plugin. This provides the fieldValue method which allows me to grab the value of the selected radio button.

We're going to assume you have the jQuery library and form plugin loaded... here is the jQuery code:

JavaScript:
  1. <script language="javascript">
  2.     $(document).ready(function(){
  3.         $("input:radio[@name='divisionid']").click(function() {
  4.             var foo = $(this).fieldValue();
  5.             $.ajax({
  6.             type: "POST",
  7.             url: "index.cfm?action=telework.getchief",
  8.             dataType: "html",
  9.             cache: false,
  10.             data: "divisionid=" + foo,
  11.             success: function(msg) {
  12.               $('#approval_2_Yes_2').val(foo);
  13.               $('#approval_2_Yes_2_dsp').val(msg);
  14.               // alert('Division ID = ' + foo);
  15.                     }
  16.             });
  17.         });
  18.     });
  19. </script>

So let's step through this...

First we grab the radio button value (divisionid) when a user clicks on one of the radio buttons. We then assign the value of that radio button (this) to a variable (foo).

JavaScript:
  1. $("input:radio[@name='divisionid']").click(function() {
  2. var foo = $(this).fieldValue();
  3. });

One thing to remember when working with CSS and jQuery - some things are case sensitive - so 'divisionid' != 'divisionID'.

Next we setup our Ajax call - this is all you need in jQuery to make an Ajax request. I'd suggest checking out the jQuery docs on Ajax.

JavaScript:
  1. $.ajax({
  2.     type: "POST",
  3.     url: "index.cfm?action=telework.getchief",
  4.     dataType: "html",
  5.     cache: false,
  6.     data: "divisionid=" + foo,
  7.     success: function(msg) {
  8.     }
  9. });

Here we are setting up our Ajax request parameters:

  • Type: we are going to make a POST request
  • URL: the URL where we are going to fetch our data from
  • DataType: What we are going to return - in our example we'll just fetch a simple HTML string
  • Cache: Whether or not to cache the results
  • Success: What to do on a successful request

Behind the scenes this is a Fusebox application - so when the user clicks a radio button - jQuery makes a request to index.cfm?action=telework.getchief. This does all kinds of Fusebox stuff but eventually runs a query using the data we passed in (data: "divisionid=" + foo - ie: divisionid=4).

Query using divisionID as argument:

CODE:
  1. <cffunction name="getChiefs" output="no" returntype="query">
  2.     <cfargument name="divisionid" required="false" default="" type="string">
  3.     <cfquery name="qryApprovers">
  4.         select 
  5.             signature_name
  6.                         , org
  7.         from
  8.             tbldivision
  9.         where
  10.             divisionid = #arguments.divisionid#
  11.        </cfquery>
  12.     <cfreturn qryApprovers>
  13. </cffunction>

This is returned to a very simply layout with no HTML:

CODE:
  1. <cfoutput>#qryApprovers.signature_name & " (" & (qryApprovers.org) & ")"#</cfoutput>

And if the request is successful - we write our string back to our form field (the alert is handy for testing):

JavaScript:
  1. success: function(msg) {
  2.   $('#approval').val(foo);
  3.   $('#approval_dsp').val(msg);
  4.   // alert('Division ID = ' + foo);
  5. }

Here I'm writing our original radio button value (foo) to a hidden field (approval). I'm also writing the results of our Ajax request (msg) to my display field (approval_dsp) which overwrites the existing value '(select division above)'.

So this should work - (unless I've bungled something up) - but there is no indication to the user anything is happening. We want Web 2.0 and need a spinning 'loading' graphic!

jQuery makes this super easy by providing the ajaxStart and ajaxStop methods:

JavaScript:
  1. $('#loading').ajaxStart(function() {
  2.   $(this).show();
  3. }).ajaxStop(function() {
  4.   $(this).hide();
  5. });

So now we're simply saying - when an Ajax request starts - show $(this) which is our #loading div which we had originally set to display: none in our CSS. When the Ajax request finishes we hide it again. Simple!

Hopefully this example has piqued your interest in jQuery and demonstrated how easy it is to use. If you have questions, comments or suggestions on how to improve the jQuery above - please leave me a comment!

7 Comments

  1. Posted November 30, 2007 at 3:21 pm | Permalink

    Thanks for posting this example. I’m just getting started using jQuery. Since I use CF for my web apps, your example is quite useful.

  2. Phil
    Posted November 30, 2007 at 4:12 pm | Permalink

    This looks cool. I am new to JQuery and need to do pretty mush this exact thing. Wasn’t sure how I would do it, but now I know! Thx Jim!

  3. Travis Phipps
    Posted November 30, 2007 at 4:56 pm | Permalink

    Great explanation! One quick suggestion, you should be able to replace this:
    var foo = $(”input:radio[@name='divisionid']“).fieldValue();
    with:
    var foo = $(this).fieldValue();

    That would keep jQuery from having to select the object a second time and would provide a slight (as in you would probably never notice) performance improvement.

  4. Posted November 30, 2007 at 5:04 pm | Permalink

    Travis - yep - I totally missed that!!! I’ll update the code this evening!

  5. Posted November 30, 2007 at 9:46 pm | Permalink

    You’re also sort of breaking a cardinal rule of DOM development by giving each of your radio buttons the same ID. The same name is fine, because then they’ll submit in a group. But the same ID breaks xHTML validation. If you need to be able to reference all of them together, you’d more correctly give them the same class.

    That would also allow you to simplify your initial jQuery call as well:
    $(”input.className”).click(function() {

    Also, depending on what version of jQuery you’re using, you no longer need the @ symbol for use in attribute selectors, it’s been deprecated.

  6. Posted December 1, 2007 at 10:12 am | Permalink

    Andy - my radio buttons have different ID’s: divisionid1, divisionid2, divisionid3??

    I’m using the latest jQuery - so I could do: input:radio[name='divisionid']?

    Thanks!

  7. Posted December 3, 2007 at 10:21 am | Permalink

    Ah…

    Sorry about that. I just totally missed the numbers at the end of the ID for the radio buttons. You should still consider using a class for each instead of IDs. IDs are really only used when you need to specifically reference an object as unique on a page.

    Yeah…you can drop the @ if you’re using 1.2.1 or higher.

Creative Commons License

Creative Commons License This article: Fetching Data With jQuery, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License .

Copyright © 2007 thecrumb.com. All rights reserved.