Using jQuery and Ajax to load sub-sections of a webpage

OK, so this isn’t really rocket science, but there are a couple of neat uses for this technique:

Ajax powered tab sets

Tabs can; broadly-speaking, be loaded in three different ways:

  • Immediately loaded - i.e. when the webpage has loaded, it is the default selected tab.
  • Later (deferred loading) - i.e. after the user clicks a tab, go off to the server and retrieve the contents of a tab, or
  • Lazy loading - e.g. load in the background before the user clicks a tab.  This enhances the user experience as the contents of a tab are immediately shown, but on the flip side means requires more traffic and the user may never click the tab anyway, effectively wasting bandwidth.

Content panes, portal layouts etc

As with tabs, content panes on a page can be loaded in several ways, although lazy loading is probably not very useful.

Solution

Here’s a javascript (using jQuery) implementation of the above which supports loading now, loading on page load and lazy loading (which takes place after the on page loads):


ajaxLoader : {
    /** A queue of embeds to load on document ready */
    loadQueue: {},

    /** A queue of embeds to load on after the load queue */
    lazyQueue: {},

    /**
     * Called on Document Ready to load all the queued embeds
     */
    init: function() {
        jQuery.each(this.loadQueue, function(id, url) {
            wbHtmlWidgets.embed._load(id, url);
        });

        jQuery.each(this.lazyQueue, function(id, url) {
            wbHtmlWidgets.embed._load(id, url);
        });
    },

    _load: function(id, url) {
        $("#" + id).load(url);
    },

    /**
     * Loads a url into a dom id immediately - ensure that the page has
     * completely loaded before using this method, as manipulating the DOM
     * before it has been created does nasty things in browsers such as IE.
     * If you want to embed the wibl after the page has loaded, use embed.afterLoad()
     * @param {string} id The div id to load the embed into
     * @param {string} url The url to load into the specified div id
     */
    now: function(id, url) {
        this._load(id, url);
    },

    /**
     * Loads a url into a dom id after the onLoad queue has been processed.
     * @param {string} id The div id to load the embed into
     * @param {string} url The url to load into the specified div id
     */
    lazy: function(id, url) {
        this.lazyQueue[id] = url;
    },

    /**
     * Loads a url into a dom id after the page has loaded.
     * If you want to embed the wibl now, use embed.now()
     * @param {string} id The div id to load the embed into
     * @param {string} url The url to load into the specified div id
     */
    afterLoad: function(id, url) {
        if ( $("#"+id).html() == '' ) {
            $("#"+id).html('<image src="/images/spinner.gif" />');
        }
        this.loadQueue[id] = url;
    }
}

To get this to work, ensure that you have an onLoad (document ready) event on your page…


$(document).ready(function(){
    ajaxLoader.init();
});

Then to make the magic work, in your HTML you may want to do something like:


<span id="tab-0"></span>
<script type="text/javascript">
//<![CDATA[
    ajaxLoader.afterLoad("tab-0", "http://your/tab/address");
//]]>
</script>

Simple client-side form validation in javascript using jQuery

I’m new to jQuery (I come from a prototype background), so I quite enjoyed my first little jaunt using jQuery… and I used it to create a simple client-side form validation library.

As we are generating a lot of our forms server side which in turn can be rendered into several different formats, so it’s important for us to have a simple way to attach validation to form elements.

For this method to work, each form element needs to be wrapped up in a container, a li is used in this example. Each container then has a class applied to it to indicate the type of validation required for the form field contained by the wrapper. Here’s the HTML snippet:


<ol>
	<li class="validation required"><label for="name">Contact name</label></li>
	<li class="validation date"><label for="dob">Contact DOB</label></li>
</ol>

Now all that needs to be done is a validation function bound to each input field, that’s easy because each input field is wrapped in a container with the “validation” class. The second class is the type of validation that is required for the input field. To keep it generic, you can just eval the class name as long as there is a function to match, heres the javascript:


init: function() {
	$('li.validation').find(":input").each(function() {
		var validations = $(this).parent().get(0).className.split(' ');
		for (var i=0; i<validations.length; i++) {
			vtype = validations[i];
			if (vtype != 'validation' ) {
				$(this).bind("blur", {element: this}, eval(vtype));
			}
		}
	})
},

required: function(o) {
	var element = o.data.element;
	// do some validation with element.value
},

date: function(o) {
	var element = o.data.element;
	// do some validation with element.value
}

The validation functions can then do whatever you want. I generate a boolean result and an error message (if necessary) and pass these parameters to a generic function which indicates the problem with the field, but equally as important may be to disable the submit button etc.

To stop any nasty conflicts, I’d recommend wrapping that all up in a namespace or similar. Other points worth nothing: this setup validates everything on a blur event (which might be a bit annoying). Also, there is no way of passing any parameters to the validation functions; so special cases need their own validation functions. However, I can’t imagine there will ever be that many different types of validation for it to matter too much.