ColdFusioning.com
Pronunciation \kold-fy-zhn-ing\ Noun: The actions of one that writes ColdFusion.

Please check out my new site: http://ja.mesbrown.com/

Detecting Java Browser Support Using jQuery

Today we're going to quickly look at detecting Java (not JavaScript) using jQuery. It is actually very simple using the jQuery Browser Plugin. Once you have the plugin loaded, it extends the $.browser object to give you the following:

view plain print about
1$.browser.flash     //Flash
2$.browser.sl         //Silverlight
3$.browser.pdf         //PDF format
4$.browser.java     //Java
5$.browser.qtime     //Quicktime
6$.browser.wmp         //Windows Media Player
7$.browser.shk         //Shockwave
8$.browser.rp         //Realplayer

As you can see, we gain more than just Java detection, but Java detection is the one we're looking for in this example.

You can view a working example on this Java Detection Using jQuery page and the source code is naturally on github.

jQuery Templates with ColdFusion ORM and AJAX

In this post, we'll look at how to use the new jQuery templates in conjunction with ColdFusion and AJAX. If you haven't already, check out this previous post on using jQuery templates without AJAX.

If you want to skip ahead, all of the files are on github (under clienttemplates) and the working examples can be found on this link.

To keep things simple, we're going to use the cfartgallery datasource that comes with ColdFusion and we're going to use simple ORM. If you don't have the sample database installed, this example won't work, but you'll be able to get the idea.

The first thing we're going to do is setup our Application.cfc so we can use ORM:

Application.cfc:

view plain print about
1component{
2    // Application properties
3    this.name = hash(getCurrentTemplatePath());
4    this.sessionManagement = true;
5    this.sessionTimeout = createTimeSpan(0,0,30,0);
6    this.setClientCookies = true;
7    this.datasource = "cfartgallery";
8    this.clientManagement = true;
9    
10    this.ormenabled = "true";
11    this.ormsettings = {
12             logSQL             = false
13             ,dbcreate            = 'update'
14    };
15}

This is pretty straightforward Application.cfc and ORM. The important parts are setting the datasource and setting ormenabled to true. If you aren't familiar with ORM, you should view Introduction to ORM or ColdFusion ORM Presentation.

The next step is to map our ORM object to the existing table:

artists.cfc:

view plain print about
1component    persistent        = true
2            accessors        = true
3            entityname        = 'artists'
4            {
5
6    property name='id'                 column='ARTISTID'         generator='increment';
7    property name='FIRSTNAME';
8 property name='LASTNAME';
9 property name='ADDRESS';
10 property name='CITY';
11 property name='STATE';
12 property name='POSTALCODE';
13 property name='EMAIL';
14 property name='PHONE';
15 property name='FAX';
16 property name='thepassword';
17}

This is the simplest implementation of this object since the datasource and table already exists.

In the next step, we're going to setup our remote cfc call. This is where the power of ColdFusion ORM comes into play:

remote.cfc:

view plain print about
1component {
2    remote string function getArtist(){
3        return SerializeJSON(entityLoad('artists'));
4    }
5}

That's all that is required to load the entire artists table and serialize it to JSON, so we can return it in the AJAX call. Very simple.

Lastly, we're going to repeat a lot of code from the previous jQuery templates post. I won't repost everything here but we'll look at the two key features we're using in this example.

The first key feature is our actual ajax call. We're going to call our remote.cfc to get our JSON. Then we're going to invoke the jQuery template and append it to our empty div in ajax.cfm:

view plain print about
1<script type='text/javascript'>
2$(function(){
3    $.getJSON('remote.cfc?method=getArtist'
4        ,{returnFormat: 'json'}
5        ,function(data){
6            $('#artistTemplate')
7                .tmpl(data)
8                .appendTo('#theContacts');
9    });
10});
11</script>

Lastly, we have our actual jQuery template. We get a little more advanced in this example and introduce an "if" conditional. This causes the phone and fax to only display if they exist in the data returned from our AJAX call. This is extremely powerful and allows us to use logic in our templates without complex JavaScript:

view plain print about
1<script id="artistTemplate" type="text/x-jquery-tmpl">
2    <div>
3        Name: ${ FIRSTNAME } ${ LASTNAME } <br />
4        EMail: ${ EMAIL } <br />
5        Address: <br />
6        ${ ADDRESS } <br />
7        ${ CITY }, ${ STATE } ${ POSTALCODE } <br />
8        {{if PHONE}}
9            Phone: ${ PHONE } <br />
10        {{/if}}
11        {{if FAX}}
12            Fax: ${ FAX }
13        {{/if}}
14    </div>
15</script>

If you view the source code of the example or explore the code on github, you'll see there are a few other sections for formatting, including jQuery and the template JavaScript.

Try running the code and let me know what you think.

Experiments in jQuery Templates with JSON

I've been wanting to work with the new jQuery templates plugin since I first read about it. It allows you to bring your views into jQuery and not rely on server-side languages to generate the html. This provides extreme flexibility and accelerates development. No longer do you need to loop over returned data and try to write your display in JavaScript.

To illustrate this, I've put together a series of posts exploring different options.

The first example we're going to look at doesn't require any ColdFusion or server-side scripting. You can view the jQuery template working example online. Be sure to view the source. There is no server-side processing going on.

We're going to create a struct and then use it to populate our jQuery template.

After including the jQuery and jQuery template JavaScript from the CDN, the first thing we're going to do is create our struct with a dataset we want to ultimately output:

view plain print about
1var bills = [
2        {
3             description:     '$1 1957 Silver Certificate'
4            ,price:         '10'
5        }
6        ,{
7             description:     '$2 1963 Federal Reserve'
8            ,price:         '50'
9        }
10        ,{
11             description:     '$100 1928 Gold Certificate'
12            ,price:         '50.65'
13        }
14    ]

The next thing we're going to put together is the actual jQuery template. This is a snippet of code that contains 'variables', denoted by ${ VARNAME }, that will be replaced with the actual data:

view plain print about
1<script id="billTemplate" type="text/x-jquery-tmpl">
2    <div>
3        Bill Description: ${ description } <br />
4        Price: $${ price }
5    </div>
6</script>

Don't let the double $$ confuse you. I want to display the price, so the first $ is the money sign and the second is the beginning of the template.

The last important line is the actual invocation of the template replacement code:

view plain print about
1$('#billTemplate').tmpl(bills).appendTo('#myBills');

This tells jQuery to use our template, replace it with our data and then append it to the empty div.

Lastly, we apply some CSS formatting and our standard HTML5 code.

In the next post, we'll look at how to use ColdFusion to load the JSON dynamically. To view this working example, view jQuery template online or for the source, visit my Github.

Full source:

view plain print about
1<!DOCTYPE HTML>
2<html>
3<head>
4    <title>Simple Client Templates Example</title>
5    <style type="text/css">
6        #myBills div {
7            background-color: navy;
8            color: white;
9            margin: 10px;
10            padding: 10px;
11            width: 300px;
12        }
13    </style>
14
15    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
16    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
17    
18    <script type='text/javascript'>
19    $(function(){
20        
21        var bills = [
22            {
23                 description:     '$1 1957 Silver Certificate'
24                ,price:         '10'
25            }
26            ,{
27                 description:     '$2 1963 Federal Reserve'
28                ,price:         '50'
29            }
30            ,{
31                 description:     '$100 1928 Gold Certificate'
32                ,price:         '50.65'
33            }
34        ]
35        
36        $('#billTemplate').tmpl(bills).appendTo('#myBills');
37        
38    });
39    </script>
40</head>
41<body>
42    <div id="content">
43        
44        <div id="myBills"></div>
45        
46        <script id="billTemplate" type="text/x-jquery-tmpl">
47            <div>
48                Bill Description: ${ description } <br />
49                Price: $${ price }
50            </div>
51        </script>
52        
53    </div>
54</body>
55</html>

Using jQuery To Require EULA Checkbox

Today we had a requirement to have a EULA (End User License Agreement) checkbox checked before we could allow a user to click a download button. Let's look how we could do it with jQuery. (I'm going to skip the un-important or self explanatory code.)

You can view the full example on this page.

view plain print about
1<style type="text/css">
2    .disabledObject {
3        opacity: 0.5;
4    }
5</style>

While not required, this is going to make the button a little prettier when disabled.

view plain print about
1<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
2
3<script type='text/javascript'>
4$(function(){
5    // Disabled the buttons if the eula isn't checked
6    $('#eula').click(function(){
7        if ($(this).is(':checked')) {
8            $('#content button').removeAttr('disabled').removeClass('disabledObject');
9        }
10        else {
11            $('#content button').attr('disabled', 'disabled').addClass('disabledObject');
12        }
13    })
14});
15</script>

In the HEADof our document, we're going to include jQuery off the Google CDN. You could use your own server/cdn or use code to prevent your site breaking if Google is unavailable.

The next SCRIPT block is the real core of the functionality. We're setting up a click-binding that will fire every time the EULA checkbox is clicked. We then determine if it is "checked" and then disable or enable the button accordingly.

view plain print about
1<input type="checkbox" value="1" id="eula" name="eula"> I agree to the EULA
2    <p>
3        <button id="downloadNow" class="disabledObject" name="downloadNow" type="button" disabled="disabled">Download Now</button>
4    </p>

In this last section, we output the checkbox and the button. We set it to disabled by default and add a disabled class. You can view the full working example.

jQuery Dynamic Modal Window

Ever needed to display a jQueryUI modal window but you didn't want to (or couldn't) edit the HTML on the page? I was developing a "third-party" JavaScript file where I didn't have control over the HTML page that my library was being included on. However, I wanted to popup a modal window when there was an error.

Well, using the below code, possibly coupled with code from loading jQuery dynamically, you can append code to the and pop-up your window:

view plain print about
1$('<div id="error" title="No Address Matches Found">We could not match the address to any known addresses. Please correct the address and try again.</div>')
2    .appendTo('body')
3    .dialog({
4        modal: true,
5        width: 425,
6        height: 275,
7        buttons: {
8            OK: function(){
9     $(this).dialog('close');
10         }
11     }
12    });

Load jQuery From Google Without Risk of Breaking Your Site

We've all heard the best practices recommendation to load jQuery (or other JavaScript libraries) from a CDN, such as Google's for performance reasons. But what happens if, in the rare chance, Google's network is down or inaccessible? At a minimum, your site would start throwing errors & wouldn't function properly.

Fear not, all is not lost. Using the code below, we can try to load the file from the Google CDN and then quickly test if it successfully loaded. If it did load properly, we don't do anything different. But if it didn't, we can load the file from another location, assumingly our web server. Then our site will function properly and once Google's CDN is re-accessible, visitors will continue to benefit from the use of the CDN.

view plain print about
1<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
2
3<script type="text/javascript">
4if (typeof jQuery === 'undefined') document.write("<scr"+"ipt src='/js/jquery-1.4.2.min.js'></scr"+"ipt>");
5</script>


jQuery: $("#elementID") != document.getElementById("elementId")

Just a quick reminder that in jQuery:

$("#elementID") != document.getElementById("elementId")

They are not the same thing.

If you use $("#elementID") you will return an array. If you want the real DOM element you need to use: $("#elementID").get(0)

Recent Comments

RSS

Subscribe