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:

<div class="editfield">
	 OD
	 OM
	 DERT
	 DIR
	 NTP
	 ORAR
</div>

<div>Loading... </div>

<label for="approval">Approving Official Signature</label>

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:


#loading {
	background: #fff url('../img/ajax-loading.gif') left no-repeat;
	color: #369;
	display: none;
	font-weight: bold;
	margin: 1em 0;
	padding-left: 20px;
	}

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:


	$(document).ready(function(){
		$("input:radio[@name='divisionid']").click(function() {
			var foo = $(this).fieldValue();
			$.ajax({
	  			type: "POST",
	  			url: "index.cfm?action=telework.getchief",
	  			dataType: "html",
	  			cache: false,
	  			data: "divisionid=" + foo,
	  			success: function(msg) {
	  				$('#approval_2_Yes_2').val(foo);
	  				$('#approval_2_Yes_2_dsp').val(msg);
	  				// alert('Division ID = ' + foo);
					}
			});
		});
	});

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).

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

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.

$.ajax({
	type: "POST",
	url: "index.cfm?action=telework.getchief",
	dataType: "html",
	cache: false,
	data: "divisionid=" + foo,
	success: function(msg) {
	}
});

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:


		select
			signature_name
                        , org
		from
			tbldivision
		where
			divisionid = #arguments.divisionid#

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

#qryApprovers.signature_name &amp; " (" &amp; (qryApprovers.org) &amp; ")"#

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

success: function(msg) {
  $('#approval').val(foo);
  $('#approval_dsp').val(msg);
  // alert('Division ID = ' + foo);
}

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:

$('#loading').ajaxStart(function() {
  $(this).show();
}).ajaxStop(function() {
  $(this).hide();
});

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!

Recent Related Posts

12 thoughts on “Fetching Data With jQuery

  1. 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!

  2. 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.

  3. 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.

  4. 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!

  5. 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.

  6. Wow! Really cool stuff.
    I’m trying to bind a checkbox, along with a few input fields, in one form to a couple of input fields in another form that “includes” the former. The data bindings are handled by CFCs. The input fields work nicely but I don’t see a way to get the checkbox to work. jQuery to the rescue, I hope. Any insights?
    -ag

    • So you have Form A which includes Form B (cfinclude?). What does the checkbox do? With these type of things I’ve found the easiest way to do it is write some vanilla HTML with the essentials – and use Firebug to see what’s going down behind the scenes. Once you have it working in the simple format – move it into your app.

  7. I’m missing something. When the original script makes the ajax call, you send the parameter into the query with the variable called data. How do you deference the data variable in the query/build the query string? WHERE ‘#data#’? If I have a not fusebox application, but just a page to handle the ajax call, how would I use the info in the data variable to create the query?

    And, when you write your HTML string to return, how to you return it to the Ajax process?

    And finally, I’m having a hard time debugging, because I don’t know how to output the results of the ajax call on the handling page, i.e. I can’t see what I have in data when it gets to the page handling the request, and I can’t see what I’m returning.

    Help is much appreciated!

    • Look at the code again… data is set to data: “divisionid=” + foo. This is where Firebug is essential. If you open Firebug and watch the Ajax request – you will see that it’s going to pass something like: index.cfm?action=telework.getchief&divisionid=123

      Are you passing this to a cfc or a cfm page? There are many ways to return the data – as html, as json, etc.

      And for debugging – Firebug, Firebug, Firebug!!! http://getfirebug.com/

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>