A hot trend I have been noticing lately is the ajaxifying of the web. This is especially the case for web applications which have complex frameworks at their core to aid in development. Something else I hade also noticed, however, is that this process is always explained as requiring complex frameworks though in theory, as well as in practice it can be very simple though not completely standard in process. With that said this tutorial aims to explain the mechanism behind this type of websites.

In this tutorial we will be using lots of vanilla javascript (non-framework js), to explain the mechanism, as well as jQuery, which makes asynchronous callbacks a lot easier to manage and explain. For this the first part of this tutorial, I will cover something I find to be core in ajaxifying a web application, and this is attaching javascript calls to your browser’s history. We won’t actually start with any ajax code till Pt II. On the code snippets I will leave comments for any tips, or things to be aware of. If I scare any of you with new terms, please read on…it is actually much simpler than I see it always being explained. I will explain it in a step by step manner.

1.Don’t trigger your page calls based on complex click event logic, but simulate how content is usually opened without Ajax

This means that adding click events to all your ajax calls may not make sense when we can create something substantially more scaleable (In part II I will show how this can make your application more scaleable). This type of thinking will save you lots of time especially on complex dynamic web applications letting you plug in and add new pieces to your interface with less redundancy of code.
Lets start with a simple non ajax example. In this example we will have 10 links, and each linking to a popup with the bio of a different individual.

The most obvious approach for bringing the above example to life, would be to have 10 popups and 10 links on a page. Using javascript we would create a hook to have these links open the relevant popup when clicked.

1
2
3
4
5
6
7
8
9
10
11
12
13
<a href="#" data-popOpener="Andres">Andres</a>
<!--would trigger a url change if clicked
url would become www.domain.com/#bioAndres-->

<a href="#" data-popOpener="James">James</a>
<a href="#" data-popOpener="Bond">Bond</a>
<!--We would have ten links like these right.  
By the way, I highly recommend the use
of data custom attributes for passing data to your Javascript.
Keeps your code a ton more versatile. -->
<!--I also do NOT recommend the inline "onclick" attribute or inline
event handling as a whole, but for simplicities sake I've done just
that-->
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function doSomethingAccordingToPopUpValue(popup){
    //You can run anything here like for example a lightbox script to open a popup.
    //For the sake of keeping our example simple I will just alert the popup's name
    alert(popup);
}

//Using a library like jQuery you can do something like the script commented right below.
//Its also good for more browser support
/*
$('*[data-popOpener]').on('click',function(e){
    e.preventDefault();//Prevent elements default behavior. You may not want links to go to their href attribute
    var popUpName = this.getAttribute('data-popOpener');
    doSomethingAccordingToPopUpValue(popUpName);
});
*/


//If using pure vanilla javascript and if IE support is no concern this is the new way to do the same
var popOpeners = document.querySelectorAll('*[data-popOpener]'),//Collect array of elements
    popOpenersLn = popOpeners.length;//Optimizes looping through elements array

for(var i=0;i<popOpenersLn;i++){
    var eachPopOpener = popOpeners[i];
    eachPopOpener.addEventListener('click',function(e){
        e.preventDefault();//Prevent elements default behavior. You may not want links to go to their href attribute
        var popUpName = this.getAttribute('data-popOpener');
        doSomethingAccordingToPopUpValue(popUpName);
    });
}

While as mentioned this is the most obvious approach, for many many cases, I’d avoid it as it is not versatile enough in some circumstances. What if you wanted to share a popup with someone by sending them a link? For this reason I recommend using url changes as the triggers of the popups, rather than using click events. This lets your links do the job automatically, you can share the popups since they are triggered by what is on the url, and more importantly your javascript calls get stored in the history as you navigate through them, which is very useful for some clever interfaces.

For this the first step, javascript provides us with a powerful tool many javascripters I know are not aware exists. This tool is the hashchange event, which allows javascript to detect when the url’s hash has been changed. It has to be a hash, as otherwise a change in the url would end up reloading our page. This is supported in all modern browsers, including IE 8 and 9. For IE7 support you can always use a variety of plugins. I like to use ben Alman’s hash change plugin for this sort of thing.

Below you can see a sample of some links of some links as well as the javascript required to listen for these changes in the url.

1
2
3
4
5
6
<a href="#bioAndres">Andres</a>
<!--would trigger a url change if clicked
url would become www.domain.com/#bioAndres-->

<a href="#bioJames">James</a>
<a href="#bioBond">Bond</a>
1
2
3
4
5
6
7
8
9
10
11
12
13
function doSomethingAccordingToHashValue(hash){
    //You can run anything here like for example a lightbox script to open a popup.
    //For the sake of keeping our example simple I will just alert the hash value's name
    alert(hash);
}
window.addEventListener('hashchange',function(){
//Triggered when hash changed.
//You may want to use a library like jquery to listen for the hash change to support older versions of IE
  var valueInHash = window.location.hash;
  //If above link was to be clicked this would be 'bioAndres'

  doSomethingAccordingToHashValue('valueInHash'); //Runs function above
});

In the above example you can see standard hash links (recognizable by the “#” in the url the point to), and the barebones javascript which is the heard of our functionality. The ability to detect hash changes is great as we could theoretically detect and run custom scripts depending on the value of the hash link. Since these changes also are triggered and retriggered with the browser’s back and forth history buttons, many possibilities open up.

These links have some limitations but we can create a solution

There is a severe limitation in these hash links. You will immediately see this limitation when hooking up your hash link to an ajax script which could benefit from passing parameters to your server’s backend. In our example function called doSomethingAccordingToHashValue, I mentioned you can do just about anything. If you wanted to have a complex ajax call there, it would be awesome to be able to pass parameters right? What if instead of just 10 bios, you had a huge and unpredictable amount of bios, as well as a huge unpredictable amount of movies, all which you’d want to show in a popup. Now we need something more scaleable. Below is one possibility where having only two types of links will do. If you wanted you could even have only one link, and therefore only one piece of code handle every scenario based on the parameters passed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<a href="#bio/name=andres">Andres</a>
<!--would trigger a url change if clicked
url would become #bio/name=andres/anotherparameter=true-->
<!--we can write a tool so that on hash change this link calls an ajax script
and passed parameters to it-->
<!--with the tool we can have the link therefore do an ajax request to "http://domain.com/bio.php?name=andres"
and then in the javascript you can process whatever is returned into a cool interface design or something-->

<a href="#bio/name=james">James</a>
<a href="#bio/name=bond">Bond</a>

<!--Movie links-->
<a href="#movie/name=super_bad/
<a href="#movie/name=pianist/

The above sample means our links can let us do truly dynamic things. I will explain how to have our links pass parameters in my next article, and for those new to ajax, we will write a bit of ajax in the next part of this article. For the case of modern mobile applications, this means we can create native like web applications that easily wrap in PhoneGap, and truly feel native. In combination with css3 we can create complex interfaces, that animate their content which they get from the server creating a more fluid experience for the user. I thought the example of popups is good for analogy, however, the possibilities that become open, allow for new creative solutions to interface design.

I hope you all enjoy the article above and find much use in it. As usual I look forward to hearing your feedback and suggestions on this topic as well as any tricks you can share. Please feel free to contact me with any questions, or if something is perhaps not clearly explained.

Share this:

Share this page via Email Share this page via Stumble Upon Share this page via Digg this Share this page via Facebook Share this page via Twitter
If you enjoyed this post, make sure you subscribe to my RSS feed!