24 Best Practices for AJAX Implementations

24 Best Practices for AJAX Implementations

Tutorial Details
  • Topic: JavaScript, AJAX
  • Difficulty: Intermediate

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

Siddharth is Siddharth on Codecanyon
Add Comment

Discussion 90 Comments

Comment Page 1 of 21 2
  1. Thanks for the tut. very useful for me

  2. kewalter says:

    Typo?

    “You’ll need to know what it’s advantages are and what it’s advantages are”

  3. App Sheriff says:

    I had some issues with the implementation in my college projects.
    2, 4, 8,11,17 were a heads up for me. :)

    Thanks Sid. :)

  4. Thank you for this tut… it’s really nice

  5. Nick Parsons says:

    Excellent – I love these best practices posts :) I especially like that you said to start with learning raw code and then use/master a library. They aren’t mutually exclusive, and in fact are both quite essential. Good job!

  6. insic says:

    a very detailed article. a good read.

  7. David Kaneda says:

    Don’t forget Ext JS in your frameworks list — There’s the MIT open source Ext Core which has all the AJAX functionality of the others-

  8. Ivan says:

    Add PHPDesigner on your IDE list, supports jQuery autocomplete (very useful)

  9. Would like to add Sublime Text to the Windows IDE section

  10. rodge says:

    I just simply love ajax!

  11. Can Aydoğan says:

    Thanks for this tuts! Realy nice.

  12. must says:

    Nice tutorial. I’m gonna keep the advices in mind and apply them later :D

  13. thanks alot,
    jquery best way to using ajax

  14. Rachelle says:

    I’m really new to actually building a lot of things with JQuery, so thanks for this article! Always looking for suggestions!

  15. Very Helpful !

    I have learned a lot from your article.
    Thank you

  16. #16 is a terrible idea. You must have never worked on large scale websites before.

    • Kazim Parkar says:

      Just making a sweeping criticism does not help anyone. You might want to elaborate on the reasons why you think it is a ‘terrible’ idea? It helps the rest of us make informed judgements about the pros and cons.

    • Steve says:

      It’s definitely a best practice. If you have a dropdown with 100 options your performance will TANK in comparison to doing one edit to the DOM.

      It’s a bad example of a best practice.

    • Louis says:

      I wholeheartedly agree.

      Code usability and practicality should generally always come before performance. I can’t fathom using that method even in a small instance.

      That being said, I think this was a good article with some decent points. Thanks, Siddharth.

    • Drew says:

      And what would you personally have done differently in this case? Try to be more constructive with your feedback.

    • It’s called AHAH, and developers do it all the time. Creating or grabbing large chunks of HTML, and injecting it all at once does improve performance on the client-side. As for your comment about working on large scale websites, I’ve worked on multi-million dollar transactional websites, and this continues to be the best approach. When you’ve got thousands of pages, all with rich dynamic content, fiddling around with every DOM element node by node is a poor decision.

      • Steve Flee says:

        “Code usability and practicality should generally always come before performance.”

        You have obviously never worked on large scale websites :P

      • Krishnanath says:

        Updating the dom with HTML string is best way to improve the performance and it DOES matter in websites or web application small or large. There is no issue in code reusability or maintenance if you do like what is suggested by Siddharth. Indeed thats the best method. Because the users use the web application more often than the developers do code maintenance and hence the performance is very important

    • I have to agree with Brian. If done right, it is the best approach to dynamically updating the page.

      • Siddharth says:
        Author

        Thanks for backing me up on this, guys. :)

      • Brian Egan says:

        Miles, you wily troll, you’re wrong in this instance. I agree with Louis that code readability is important, but performance should be balanced with readability.

        Siddharth’s method is especially useful in large loops / with lots of moving parts. For example, say you need to generate 100 divs (I have a jQuery plugin that does exactly this). It is NOT efficient to have your loop inject on each iteration. Instead, it’s much faster to add each DOM element to a string, and then inject it once.

        Ex:

        (function oneInjectionTest() {
        myHTML = “”;

        for (i = 0, j = 100; i < j; i++) {
        myHTML += 'Tile ‘ + i + ”;
        }

        $(‘#container’).html(myHTML);

        })();

        In fact, I’ve proven it’s faster =P Here’s a JSFiddle (God I love that tool) which first creates and injects the spans into the page using Siddharth’s method, then overwrites them using the method Miles and Louis prefer.

        http://jsfiddle.net/cMHzS/1/

        If you using your console & profiling tools within Firebug or the Web Inspector, you’ll notice that the oneInjectionTest function is faster, and also uses less cpu. Remember, with the “easier to read method”, you’re not only getting dinged for calling the .html() method, but you’re also getting a performance hit for calling the jQuery constructor $() as well for each element.

        Performance matters, people! And that code really isn’t too much harder to read.

      • hoppster says:

        Brian, I like your impirical approach, but I think having your second function rely on the output from the first has muddled the test. I rewrote your single test as two independant tests and the difference in execution time was even more dramatic.

        http://jsfiddle.net/Gcqbn/

        http://jsfiddle.net/CCHh4/

      • Brian Egan says:

        Thanks, Hoppster!

        Great feedback… I think you may be right.

        My first written tests were to look at exactly how Siddhart’s code up above would have executed, which was a mixed example, and perhpas led to some of the confusion in the comments. I actually did a similar test on my blog with append as well (although I didn’t split them up, which you are probably correct isn’t quite as accurate), and got similar results!

        Thanks again.

    • JGarrido says:

      This was also the one point that caught my eye as being potentially problematic. Frequently, you’ll have multiple interactions going on within your DOM, so it would be very difficult to determine what classes are currently assigned, what inline styles might be applied, etc. You couldn’t simply replace the current element with one hardcoded in a function.

      An alternative might be to grab the container of the elements you’d like to modify in one fell swoop (if one exists), iterate over the contents of it to replace what needs replacing, and then inject it back into the page. Of course, depending on the specific scenario, this may wind up being just as resource intensive as making the individual calls would be.

      So, I guess the real answer is… it depends…

      • Krishnanath says:

        Updating DOM with HTML String will definitely improve the performance and its proven long time back and also it was again proven by Brian. The guys who are against the idea/tip #16 should understand that the users will use the web application more often than the developers who will maintain it which means performance does matter.

      • JGarrido says:

        Right, that’s true: if you’re creating completely new elements to insert into the DOM, creating a string and inserting it in one step is the obvious choice. But the example given was different; it involved modifying an *existing* element, which is where this method could become a problem.

        If you have an element which is being acted on by some other script(s) (such as a jQuery accordian plugin, for example), you can’t just blindly replace the element with your newly created one; you would have to first check the state of that element and transfer over any properties of it to your new version that you’re creating (and hope that the element is not currently in a state of flux, such as an animation).

        Does that make sense?

  17. Evangelia says:

    The approach you use for #16 is horribly wrong. You should NEVER update the DOM this way. In fact, the way you tell them NOT to do it is how it should be done.

  18. David Fitzgibbon says:

    Thanks! As ever, a great tutorial.

  19. Julius says:

    This is tutorial of AJAX, we should know first the best practices before diving into the code. That is true…

  20. Atif Majid says:

    Thanks.
    JQuery history plugin was new for me. As I had always been thinking for how to achieve this.
    Once again thanks for such informative tutorial.

  21. ESN says:

    Thank you for great tips! I agree with everything except for the code example for changing the DOM.

  22. Daniel says:

    Awesome article… And I’d like to add:
    25 – Write a tutorial and get the feedback:

    To write a tutorial it’s how you get the results of your learning in the “real world”.
    I think that the users feedback is the most important thing if you want to improve your coding and writing skills.

    :D good job

  23. David Moreen says:

    What is really interesting is that I only know how to send ajax calls with jQuery’s $.ajax function thingie. Look at that I don’t even know what type of object it is :/ There are like 15,000 other ways to make asynchronous calls as well…

  24. Ignas says:

    Hey dude! This is tut?! It is only notes and it isn’t really useful. Everyone know that using good IDE is great, or read as much book, tuts is great… It is really waste of time to read this. One of the worst articles here in nettuts…

    • ShadowAssassin says:

      You took the words right out of my month.

      Honestly, this is NOT a tutorial, I would love to see a proper tutorial on ajax and stuff :)

      This isn’t useful.

      • Siddharth says:
        Author

        This is, indeed, a tutorial. It gives you 24 points to keep in mind aimed at beginners wanting to implement AJAX functionality into a web site/web app.

        Not everything here is intended for advanced programmers, mind you, and not everything has to be a build an ubercool widget tutorial. I’m sure the readers really appreciate the occasional best practices articles too.

        Thanks for reading. :)

      • Stephen Flee says:

        Given the range of programming talent that visits this site, it’s safe to say that
        every tut here isn’t going to be useful for EVERY developer.

        These “best practice” tutorials are fantastic for those beginner developers that are doing things they’re learned from other sites but don’t quite understand the “why”.

        Breaking bad habits before they start..that’s what these types of tutorials are about!

      • Ryan says:

        Sorry dude, it’s not a tutorial. It’s a list of best practices.

        re: ” I’m sure the readers really appreciate the occasional best practices articles too.” We do, but that doesn’t make this a tutorial.

  25. Timothy says:

    Decent list. Glad you gave some attention to MooTools rather than just focusing on jQuery, like most people do.

    Would have liked to seen some warning about cross-site scripting / injection. These malicious attacks can happen during Ajax requests, often when the script is requesting raw HTML to be placed on the page (which could include malicious JavaScript).

  26. Those are all very excellent suggestions, it should be noted also that AJAX is not necessarily the most secure means of transmitting information.

  27. audi says:

    what about the search engine problems

  28. SeanJA says:

    #19. Use a Proper IDE

    Netbeans supports jQuery (and possibly others…?)

  29. bryant says:

    Good list!

    #3 though … Although I agree with the principle behind it, and I think that learning the raw javascript in some cases is not a pre-req. to implementing ajax. Yes, it is always good to know whats going on, and knowing how it works will always help, BUT I don’t think its absolutely necessary in some cases.

    AJAX is becoming such a de-facto thing in many websites now, that someone starting to develop, or a designer who is starting to take on more code should not be concerned with having to learn the behind the scenes of whats going on with ajax calls in many of these well structured libraries.

    In a perfect world, I would agree, but in reality, meh…

  30. nXqd says:

    Very nice list . This one helps me a lot :)
    Thanks my friends ;)

  31. Very thorough, I like seeing AJAX and javascript related tuts here. If you could write how to clone and validate input fields I would be indefinitely grateful.

  32. hoppster says:

    “For my fruit flavored brethren”

    that line cracks me up. good tut.

  33. jmarreros says:

    thanks Siddharth I really appreciate your information

  34. Ben says:

    Implementing ajax with raw javascript is pointless and very inefficient in a real scenario.

    Oh it’s ok because we can use a library anyway.

    Commenting code, especially useful when it comes to ajax. And using an IDE. And playing a part in a community. And asking questions.

    Did you struggle for that magic 24?

  35. Chaitanya Pramod says:

    very helpful for new developers!

  36. mehmet says:

    I really liked your site, tutorials bla bla
    thanks for all

  37. babloo says:

    Hi Buddy!!!

    How the Ajax live long trend in this era..???any reason is there??? reply me ASAP.. meet again.

  38. What is a good IDE to use for web programming, for PHP and the jQuery library? I would like it have snippets like Dreamweaver does and have it finish tags. And a validator built it would be nice. I know I sound picky :) but sometimes its all about productivity.

    I use Dreamweaver MX, whichs works well, but I have a feeling that I’ve been using it for far too long.

    Also, I love the tuts and your site, I subscribed to the feed and check it every couple days in my Windows Mail.

  39. imawake says:

    NetBeans is pretty good.

  40. Ahmed says:

    Hi buddy,

    Thank you a lot for this useful artical

    I have a question please but maybe it’s out of this artical
    Which is best Ajax or Flex?

    Best regards

  41. Danny says:

    Excellent Article! Cant wait to try some of these ideas..

  42. Hemant says:

    Really good-one yar!

  43. You have an awesome site!

  44. admire says:

    Hi , this was really usefull information , it helps us write code we are proud of , thanks !!!!!!!1

  45. Nice article! Let’s start making our webdesigns more interactive, the Status Indicators people often forget in the website, what makes it look like a bug!

  46. Did anyone else notice the “post date” is Dec 2010 but the comments go as far back as Feb 2010?

    :)

    Good post though, useful tips and good to use as a checklist when developing.

  47. data says:

    Use a Library, if your a novice

Comment Page 1 of 21 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.