Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

24 Best Practices for AJAX Implementations

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Nettuts+.

Implementing AJAX technology can be a hit or miss thing. Do it well and you'll have users raving over the slickness it provides to the general user experience, while, if you mess it up, you'll be at the receiving end of their wrath. Here are 24 tips to guide through the process of implementing AJAX technology within your web application.


1. Understand What it All Means

First up, you need to understand what AJAX is, what it stands for and how it has revolutionized parts of the internet. You'll need to know what its advantages are before you can make an informed decision

Here is a list of must read articles to get you up to speed.


2. Check for Appropriate Usage Scenarios

AJAX can sound all fine and dandy but there are only so many places you can implement it without it sounding like another bullet point. Do proper research and testing to make sure you are implementing AJAX for the right reasons. Because it sounds nice is not a valid reason.

Proper usage scenarios would be if you have lots of data in the back end and want to update the UI as and when the user needs access to that data or when you want to emulate a proper desktop application and handle everything asynchronously. An extremely bad scenario is when you have each page of a static web site load through AJAX for no reason other than you can. Use your discretion here.


3. Learn to Implement it With Raw Code

Before you delve into writing your code, understand the raw code to do it first. Libraries are great at reducing the time it takes to create browser agnostic code but when it breaks it'd be best if you know how to do it without libraries helping you.

I highly recommend Jeffrey's tutorials on making AJAX requests with raw JavaScript here and here.


4. Use a Library

Once you've mastered the raw JS which handles the AJAX implementations, it's best you shift over to a JavaScript library which provides robust support for AJAX. Any of the major libraries like jQuery, Prototype or MooTools should do.

Libraries not only provide an exhaustive feature set you can make use of but also makes sure your code is compatible with all browsers without you having to do anything extra.

Here are a few of our favorites which encompass proper AJAX functionality:


5. Master the Library

Once you've gotten the hang of making AJAX requests with your library of choice, it's time to take it to the next level and master it. It may sound a little redundant but there is a big difference between the two.

With each library getting bigger, packing more features with each release, the developers hide a huge amount of functionality from the beginner developer. For example, did you know that there are multiple methods in jQuery to make AJAX calls? Or that a number of event triggered methods are only available with the core AJAX call? A lot of people don't know that and thus are unable to leverage the untapped potential of the library.

Here are a few choice resources for your perusal:


6. Provide Feedback

Tutorial Image

On of the main reasons people were against AJAX in the past was they couldn't really tell when the application updates the data it contains. This is also an integral part of the general user experience made even more pertinent with AJAX.

So even for the tiniest thing, remember to provide feedback to the user letting them know their action has been registered. The user has clicked on a button? Let them know!


7. Utilize Proper Events and Callback Functions

Whether you are using raw JS or a library to implement this functionality, you'll have access to the state of the request i.e. whether the request was successful; met with an error and finally whether it has been completed.

Make proper use of these events and their respective callbacks to manipulate the UI for a better user experience. For example, if the request was unsuccessful, you'd want to update the user interface to reflect that their changes weren't successful while if it was successful, you'd want to tell them so. Don't keep the user waiting!

With jQuery, you'd make use of the success and error callbacks. You also get other callbacks such as complete and beforeSend to be invoked for apporopriate use.

$.ajax({
        //Other code
           success: function(msg)
        {
            // Update the UI here to reflect that the request was successful.
            doSomethingClever();
        },
        error: function(msg)
        {
            // Update the UI here to reflect that the request was unsuccessful
            doSomethingMoreClever();
        },
        complete: function(msg)
        {
            // Update the UI here to reflect completion
            doSomethingEvenMoreClever();
        }
});

- Show quoted text -


8. Choose the Right Format for the Job

Just because XML occurs in the abbreviation doesn't mean you are limited to XML for the payload. You are free to choose whatever format strikes your liking. JSON? Sure. XML? Naturally. HTML? Of course. Raw strings? Definitely.

So, essentially, whatever floats your boat. You aren't limited to any format. You get to choose whichever format makes the work at hand easier for you and makes the most sense for that specific instance.


9. Read Extensively

AJAX, while old in relative terms, is still very much in flux. Exciting new solutions are created everyday while scarily thorough books covering the subject are often released. Be it web developments blogs (like this one!) or books, keep reading to keep yourself informed of the latest developments.

Here are my most visited and/or read blogs and books:


10. Experiment Continuously

Reading book after book and article after article is awesome but to get a grip on the subject, you'll need to fold up your sleeves and write some code yourselves. Trust me, you'll learn a lot more a lot quicker reading a bit and then writing some code about it than just reading continuously without writing any code to better understand what you've learnt.


11. Utilize Firebug

Tutorial Image

Firebug is arguable the most important tool in every web developer's repertoire. Along with impressive JavaScript debugging and other potent features, it also let's you see each AJAX request as it is made along with a myriad other details about the request including from where it originates, what its payload is and so much more. You can download it right here.

Here are a few more recommended resources:


12. Keep the Users With Old Browsers in Mind

Unless your web application is like Google Maps it's always a good idea to provide users with a fallback so they can still use your application. Case in point would be the numerous web applications which route all their user interactions through AJAX if they have the capability while falling back to a normal HTML version otherwise.


13. Bookmarkability

The tendency to bookmark is a pervasive habit of the average web user and it's imperative your application respects that. With AJAX, the address bar of the browser is not updated which means when a user wants to bookmark a page with content loaded dynamically with AJAX, he/she is going to bookmark the initial page and not the updated page. This presents a huge problem.

Fortunately, there are a few techniques to fix this problem. Here is a selected list of articles intended to help you with that:


14. Use Proper Animations

This is another of those user experience issues which may mar an otherwise spectacular application. Often with an AJAX application, the user may fail to even notice a change has occurred with an element of the user interface or the data it contains. In light of this issue, it's essential that the developer uses non-garish, tasteful animations to draw the user's attention to the fact that the user interface has been updated to reflect the user's actions.

You can read about how to use jQuery to create tasteful, cross browser animations here.


15. Respect the Back Button

The back button is another action that has become part of a normal web user's habits. Make sure your application adheres to this respected paradigm to avoid angering users. Trust me, they will, if suddenly their back button doesn't work as intended.

Here is a list of article which should help you with the matter.


16. Change the DOM Intelligently

Imagine this: your request has succeeded and has returned a chunk of data with which you hope to update your user interface. If this chunk of data has few individual chunks, you can proceed as usual. If instead it has, say, 15 contiguous elements to be updated, it is better to just create the elements, modify their data in memory and replace those in the DOM in one big swoop rather than accessing each element and updating the DOM each time separately.

Modifying the DOM separately leads to worse performance as the number of edits to be made increases.

So, for a chunk of HTML like so:

<div id="container">
<span id="elem1"></span>
<span id="elem2"></span>
</div>

instead of doing this:

$("#elem1").html("Value 1");
$("#elem2").html("Value 2");

Do this:

var updatedText = "<span id=\"elem1\">Value1</span>
<span id=\"elem2\">Value2</span>";
$("#container").html(updatedText);

It might look a lot of work for just two elements but once you extrapolate it to more, the performance alone will be worth it. It'll be faster since you'll be updating the DOM just once irrespective of how many elements you have within the updated HTML. With the usual method though, the number of edits required to the DOM scales linearly to the number of elements which in turn degrades performance.


17. Comment Your Code

This is a no-brainer but comment your code properly. Chances are, your code is going to be looked at by a few hundred people , at least, looking to learn from you and commenting is definitely going to earn your extra rep points and paragon cookies.

You don't necessarily need to comment every tiny bit of your code; commenting just the important bits is sufficient.

This is too much!

$.ajax({
    // Switch off caching
    cache: false,
       
        //Set the type of request
       type: "GET",
       
        // Set the timeout
    timeout: 5000,
       
        // Specify the proper handler
       url: "handler.php",
       success: function(msg)
        {
           // Update the UI here to reflect that the request was successful.
           doSomethingClever();
        },
        error: function(msg)
        {
           // Update the UI here to reflect that the request was unsuccessful
           doSomethingMoreClever();
        }
});

A much better way to add comments since a lot of it is self explanatory.


// Make an AJAX call to handler.php and update the UI
$.ajax({
    cache: false,
       type: "GET",
    timeout: 5000,
       url: "handler.php",
       success: function(msg)
        {
           doSomethingClever();
        },
        error: function(msg)
        {
              doSomethingMoreClever();
        }
});

18. Make an Informed Decision About the Request Type

This is strictly a general web application tip than specifically an AJAX tip but do take special note of the type of request you are making: GET or POST. The XMLHttpRequest object is capable of making both type of requests but it is up to you to decide what kind to make.

As their names signify, a GET request is used to procure data from a source while a POST request is used to submit data to be processed. With an AJAX GET request, as with a normal GET request, you'll have to pass on the query data as part of the URL itself manually as opposed to a POST request where the data is sent automatically. Also note that GET requests are cached automatically while a POST request isn't.


19. Use a Proper IDE

Tutorial Image

When it comes to JavaScript, please don't be an elitist and limit yourself to plain old notepad. Your productivity will spike sharply with the use of a proper IDE, specially one with support for your JavaScript library of choice.

For the PC loyalists

For my fruit flavored brethren


20. Participate in the Community

Getting to be a part of awesome web development communities, like this, will not only expose you to a wider range of ideas but will also lead you to the path of writing better code. By writing and commenting on articles similar to these, you'll not only teach people less knowledgeable than you on the subject but you'll also be able to learn more from the more experienced people who comment on your code.

As Jeff says, you only truly understand something when you've taught it to someone else.


21. Tweak Your Response Times

By response time I mean only one thing: the time before a user triggers an AJAX request. Consider this, you are typing in an input box which uses AJAX to retrieve search suggestions from the server. Response time would be the time duration between the key press and the AJAX call being made. Too fast and you'd have to do multiple requests for each letter of the search phrase. Too slow and you'll have the user twiddling his thumbs wondering as to how he broke the application.

This isn't limited to just the scenario noted above. This applies to each and every non-definite (click) user action. Test rigorously with your users to find the optimum latency.


22. Use Status Indicators

Tutorial Image

This is an extension of a point noted above but just as important. Users coming from the desktop application or a general web application paradigm will be flummoxed when they use an AJAX enabled web application. While notifying the user when a change has been made is good, you'll also need to make sure to let them know that a request has been initiated in the first place.

This is where status indicators come in. These are the little rotating or bouncing GIFs you see in applications. In function these are similar to the hour glass cursor used in desktop operating systems.

Here is a wonderful little tool which lets you create an indicator of your choice.


23. Appreciate JSON-P's Awesomeness

Often, as part of the cross site mashup you're creating, you'd need to access data from other sites through AJAX requests. This flies directly in the face of the cross domain restriction most browsers enforce. In this case, instead of going with exotic solutions like masking and proxying, you could just use JSON-P.

JSON-P, JSON with Padding, essentially lets us circumvent this restriction and lets us obtain data from third party domains. Here is a list of articles to get you started:


24. Ask Questions Freely

Don't be shy to ask questions. Every one of us started as a complete newbie and began by asking questions. There are plenty of placed to clarify your doubts including the comments section of Nettuts+. Never, ever be afraid of asking questions. Just try to be a little polite! It always helps.


That's all folks

And we're done. Twenty four points to keep in mind when implementing AJAX within your site or web application. Hopefully, this has been useful to you and you found it interesting. I'll be closely watching the comments section so chime in there if you have any counter arguments or different perspectives on the matter.

Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!


Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We're looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you're of the ability, please contact Jeffrey at nettuts@tutsplus.com.

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial
Advertisement