My First AJAX Experience

Feb

22

All in all, I'd have to say I had a very pleasant experience using AJAX for the first time. The most difficult aspect of working with AJAX, was learning how to implement it. Once I found the right documentation, it was relatively smooth sailing.

Getting Started

First off, you should download an AJAX library. I recommend the Prototype javascript library. What is prototype.js anyway?

Prototype is a JavaScript framework that aims to ease development of dynamic web applications. Featuring a unique, easy-to-use toolkit for class-driven development and the nicest AJAX library around, Prototype is quickly becoming the codebase of choice for web application developers everywhere.

Basically, a guy named Sam Stephenson spent, I'm sure, an inordinate amount of time writing this great javascript file in order to make life easier on all of us. Using this file makes writing your AJAX code much easier. As mentioned earlier, the hardest part about getting started was finding documentation. So, in order to make it simpler for you, I'm going to include links to the documentation that I used to get started.

  • Developer Notes for prototype.js - This documentation was exactly what I needed, and could quite possibly be the only thing you'll need. It contains some really great examples in the beginning of the document, and the contains more detailed information later on. After reading the first few paragraphs, I was able to get started, and then used the rest of the document for reference (this part of the document conveniently happens to be named "Reference for Prototype.js") haha.
  • Working With Events In Prototype - How to use prototype with Keystrokes, Mouse Clicks, Mouse Hovers, etc.
  • Eas y Ajax with Prototype

What To Watch Out For

Internet Explorer loves to cache everything. This is particularly a problem when you are using AJAX. What works well in Firefox, may not seem like it's working in IE. I learned this the hard way. The application I implemented AJAX on is my personal online checkbook register. So the idea was to allow a user to stay on one page, add a new transaction, submit it, and have the list show the latest transaction while also changing the account balance all without refreshing the window. This worked great in Firefox, yet nothing seemed to be happening in IE. When in actuality, the database inserts were definitely happening, yet the list and account balance refresh was not. It took me a while to figure out what and why this was happening, but finally figured it out when I came across this article "Ajax IE caching issue". It seems as though IE believes that GET requests (method="get") need to be cached, while POST requests do not. This meant changing all my requests from GETs to POSTs. Finding out how to do this took a bit of research as well, so I'm going to just give this to you here (if you already know how to do this, then feel free to ignore the following). The solution, as you'll see is extremely simple (changes are marked in bold & italic):
Example GET request:

function insertRow() {
  var url = 'ajax_file.cfm';
  var param1 = $F('p1');
  var param2 = $F('p2');
  var param3 = $F('p3');
  var pars = 'P1='
      + param1
      + '&P2='
      + param2
      + '&P3='
      + param3;
  var myAjax = new Ajax.Request(
    url,
    {
      method: 'get',
      parameters: pars,
      onComplete: runNextFunction
    });
}

Example changed to a POST request:

function insertRow() {
  var url = 'ajax_file.cfm';
  var param1 = $F('p1');
  var param2 = $F('p2');
  var param3 = $F('p3');
  var pars = 'P1='
      + param1
      + '&P2='
      + param2
      + '&P3='
      + param3;
  var myAjax = new Ajax.Request(
    url,
    {
      method: 'post',
      postBody: pars,
      onComplete: runNextFunction
    });
}

Well there you have it. The IE issue is fixed, right? Well... Not exactly. This solution only seemed to work part of the time. So, after some more digging, I found the definitive solution. Although not elegant, it fixes the problem. That solution is to add a random number parameter onto the end of the parameters that get passed. "Why would this work?" you might ask. Well this random number will basically fool the browser into thinking it has to return a page from a URL it's never been to before, rather than thinking it has it in cache (learn more).

POST Example with Random Number

function insertRow() {
  var url = 'ajax_file.cfm';
  var param1 = $F('p1');
  var param2 = $F('p2');
  var param3 = $F('p3');
  var pars = 'P1='
      + param1
      + '&P2='
      + param2
      + '&P3='
      + param3;
      + '&rnd='
      + Math.random()*99999;
//using rather large multiplier to ensure uniqueness
  var myAjax = new Ajax.Request(
    url,
    {
      method: 'post',
      postBody: pars,
      onComplete: runNextFunction
    });
}

I feel that the information in this article is exactly what is needed to get your feet wet with AJAX. I plan to create a tutorial that will walk you through a real world working example of AJAX using ColdFusion and a simple MS Access Database.

feedtag thisdigg this

8 CommentsComments

  1. Gravatar must be down david

    Nice write up. I’d recommend, however, to not use the Prototype framework when first learning something like the xmlhttprequest. It seems to over complicate things. Take a look at Apple’s write up on the matter, or have a look at some other ajax articles i’ve put together. More than likely, you’ll find the native xmlHttpRequest and it’s methods to be much simpler than the Prototype AJAX class. That’s just my $0.02.

    Nice CSS btw
    -David

  2. Gravatar must be down Patrick

    David: thanks for the comment. I will definitely take a look at these articles. I’m always up for learning something new. You’re blog entry about the IE caching issues saved my sanity, which is why I wrote this entry. Hopefully this might help someone else who ran into the same issues.

  3. Gravatar must be down James

    Instead of the random number, you can just use the current time in milliseconds (if you don’t expect multiple requests to come in within the exact millisecond)


    + ‘&time=’
    + new Date().getTime()

  4. Gravatar must be down Patrick

    James: Great point. That way, you are gauranteed that the number will always be unique. Unless, however, 2 users are accessing the script at exactly the same moment in time (which is extremely unlikely).

  5. Gravatar must be down James

    Actually, this is addressing the browser cache, so two different users sending a request simultaneously won’t effect each others’ browser caches. The millisecond trick should work as long as the same browser isn’t making multiple requests within the same millisecond (extremely extremely unlikely) :-)

  6. Gravatar must be down Patrick

    Excellent point.

  7. Gravatar must be down Lukas

    I’m trying to use all this, but there seems to be a problem using the ‘post’ method. When I try to intercept the variables with ColdFusion, if I dump the Form variable, it returns an empty struct. If I use ‘get’, everything works fine (when dumping the URL variable).

    Anyone have an idea what may cause this? Thanks!!

  8. Gravatar must be down Arnaud Presles

    thinks for this trick i never think about switch get by post.

    Arnaud

Leave a Comment