Monday 22 Sep 2014   
Add Comment

ColdFusion jQuery Introduction Part 2

ColdFusion Tutorial #43

This is part 2 of a 3 part series.
Now that you’ve hopefully got a good handle on getting JSON data via jQuery, let’s look at using ColdFusion to provide that data.

learncf_jquery.cfc

I’ve put together a CFC that returns a list of football teams, and a list of players by team. For the sake of simplicity, I didn’t want to involve a database. For that reason, the CFC includes a cffunction that manually creates and returns a ColdFusion query. This is a private method and will not be accessed externally. The only methods that our jQuery page will interact with are getAllTeams() and getPlayersByTeam().

Note that the access attribute of both of these methods is set to “remote”. This is very important. However, nothing else about the cffunction is particularly unique. The returntype is still query, and no returnformat needs to be specified. This is because, as with the Twitter example, we’re going to be specifying the return format of JSON in our jQuery call.



html.cfm

And here’s the HTML that we’ll be starting off with.

Pretty straightforward. Notice that we have a <ul> with an id attribute of “teamList”. This is where we will populate the list of teams.

We also have a <ul> with an id attribute of “playerList”. This is where we will populate the list of players for a specified team.

There’s a button input with an id of “showteams”. This is where we’ll get started. We want a click event on that button to load a list of teams from the server.



script.cfm

Let’s start off by adding the following <script> block inside of the <head> section of our page.



demo.cfm

As with the Twitter example, we’re going to load the jQuery library from Google. This saves us from having to download it.

The next step is to create our $(document).ready(function() { }); This is effectively the same as the old-style JavaScript onload() that tells jQuery the page has been loaded.

Inside of that, we add a click handler for the element with the id of “showteams” (which is our button). jQuery uses CSS-like selectors to identify a specific element within the DOM. The pound symbol indicates an element with a specific ID.

Once a click event occurs, the getJSON() is going to fire. Again, for the sake of simplicity, I’ve named my CFC “learncf_jquery.cfc”, and it resides in the same directory as the .html file that’s calling it.

I’m requesting the method (the cffunction) getAllTeams, and specifying the returnformat to be JSON. I could have omitted the returnformat from here, and included it as an attribute to the cffunction itself. However, by doing it this way, the cffunction is a bit more reusable. E.g. it can be called by a page that doesn’t want the data returned in JSON. The last attribute being passed in is “queryformat=column”. This tells ColdFusion to format the JSON with 3 entries: the number of rows, an array of column names, and an object where each key is a column name and each value is an array with the column data (see: http://livedocs.adobe.com/coldfusion/8/htmldocs/ajaxdata_09.html).

The response that comes back looks like:

{"ROWCOUNT":4,"COLUMNS":["TEAM"],"DATA":{"team":["Dallas Cowboys","NY Giants","Philadelphia Eagles","Washington Redskins"]}}

This is what is passed to our callback function as “data”.

Within the callback function, we loop over the elements of data.DATA.team, which in this case is the 4 teams that are listed above. For each iteration of the loop, we create an <li> element that contains an <a href> element, both wrapped around the value of ‘team’. That data is then appended to the <ul> with the id value of “teamList”.

Once the loop finishes, the element with id “teams”, which was previously hidden (see the css declaration at the top of the .html page), is displayed via $(‘#teams’).show(). This is a built-in jQuery method that displays a hidden element.

The actual <ul> that contains the team names has an id attribute of “teamList”, and is also hidden by default. Using jQuery’s built in fadeIn() method, we fade the list of team names in, over a course of 1200 ms.

The last thing that happens is that we disable the “Show Teams” button. We don’t need to refer to it by ID, since it’s the element that triggered this particular piece of jQuery. It can be referenced as $(this). The attr() method is used here to set the “disabled” attribute of the button to the value “disabled”.

This is the complete file which concludes part 2 of this 3 part series. In the next installment, we'll make something happen when we click on a team name. We'll also address the issue of how clicking the "Show Teams" button multiple times displays the data multiple times. Stay tuned...



Demo

See this code running!


Download

Download this code as a zip!


Comments

Demo doesn't work....
Francesco @ Thursday 31 Dec 2009 - 07:29:35 AM

@Francesco: Can you clarify how it doesn't work? Which browser/OS?
Thanks!
Charlie Griefer @ Thursday 31 Dec 2009 - 09:40:47 AM

Hi Charlie,
Great tutorials! I have been wanting to learn jQuery/Ajax in conjunction with CF and the tutorials really helped.
I am having a problem with the 2nd jQuery module.
I can see that there is data being returned from the getALLX function:
//{"ROWCOUNT":43,"COLUMNS":["HOMENAME"],"DATA":{"homeName":["Arcadia","Borderland","Brookside","Clearview","County Line","Dauphin","Gibble","Gibraltar","Granada","Grant","Green Hill"...]}}
But for some reason, the function that builds the list is not being populated. Here is the modified code that I used:
function(data) {
$.each(data.DATA.homeName, function(i,homeName){
$('#homeList').append('<li><a href="#">' + homeName + '</a>');
});
Any ideas?
Thanks again,
Steve
Steve Hanzelman @ Wednesday 13 Jan 2010 - 12:11:21 AM

Hi Steve:
Does the browser indicate any JavaScript error?
Charlie Griefer @ Wednesday 13 Jan 2010 - 04:22:35 AM

Hi Charlie,
Thanks for the response.
No, I do not see any JavaScript error. I have that enabled in Firebug, but see no errors.
The same thing occurs if I use the tutorial code from part 3 of the jQuery series. It displays the button and returns data to the Firebug console but does not display it.
Is there something bizarre on our end with the function that builds the 'teamList'?
Steve Hanzelman @ Wednesday 13 Jan 2010 - 04:30:10 AM

Quick and dirty way to isolate where the error is...
can you throw an alert() into your callback function?
So just have function(data) { alert('Hi'); };
If that works, we know the callback is at least getting... um... called. If that's the case we'll start dissecting the code inside it.
Charlie Griefer @ Wednesday 13 Jan 2010 - 04:40:39 AM

Hi Charlie,
I changed the JavaScript to add the alert. The data is still passed back, but there is no Alert box or message that appears.
$(document).ready(function(){
$('#showhomes').click(function() {
$.getJSON('learncf_jquery.cfc?method=getAllHomes&returnformat=JSON&queryformat=column',
function(data) {
alert('Hi');
});
});
});
</script>
Steve Hanzelman @ Wednesday 13 Jan 2010 - 05:25:47 AM

Hey Steve...
At this point, I might suggest trying .ajax() instead of .getJSON(). While I was writing this post, I ran into some issues where the callback method wasn't firing because proper data wasn't being returned.
It was suggested that I try .ajax(), for which .getJSON() is simply a convenience wrapper.
See the thread at http://groups.google.com/group/jquery-en/browse_thread/thread/01b09921ed8db0b7. The first response to my initial question lays out the syntax pretty well. Let me know if that works.
Charlie Griefer @ Wednesday 13 Jan 2010 - 05:45:00 AM

Hi Charlie,
Solution solved.
It was due to the // being passed as a prefix from CF. I made the change in CFAdmin and it worked.
Since this was my first real crack at using JSON or jQuery, I didn't even know that setting existed.
Thanks for the help!
Steve
Steve Hanzelman @ Wednesday 13 Jan 2010 - 06:26:23 AM

My dreamweaver CS5 says there's a syntax error in the script. It says at line 14, but that's the last line of the script in script.cfm
There are no // at all in the script as it's downloaded in the zip file so I'm not sure what the comment by Steve has to do with it.
The demo files in the zip file wont work for me when I unpack them into the same directory together. Nor when i cut and paste the contents of Scripts.cfm into the head of the httm.cfm file.
Mike Kear @ Saturday 28 Aug 2010 - 08:44:29 PM

Demo does not work on Chrome. When you click on the team, nothing happens.
ColdFusion Coder @ Tuesday 15 Jan 2013 - 06:27:38 PM

@ColdFusion Coder Seams to work fine for me pull in a list of teams
Paul @ Tuesday 15 Jan 2013 - 07:56:45 PM

zxcvzxcv
sdfda @ Friday 09 May 2014 - 01:26:05 PM

Click button to add a comment


Author

Charlie Griefer


Published

Thursday 10 Sep 2009

Tags

cfargument  cfcomponent  cffunction  cfquery  cfqueryparam  cfreturn  cfset