Exciting How Easy AJAX Really is to Work With

WebDevel.jpg

I was working on my web app and I needed to have a simple AJAX call to a servlet to hit the back-end database and verify that the provided username was in a table of authorized users for this app. This wasn't going to be using the Google API, so I had to decide if I wanted to code it up on my own, or use one of the AJAX Frameworks. I looked at the code if I rolled it myself, and decided that it was far easier if I did it myself - considering that I did not have to support IE, so I did.

The result was amazingly simple:

  var username = document.bridgeApplet.getUsername();
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "validate?" + escape(username) + "&page=PnLTool");
  xhr.onreadystatechange = function() {
    // if we're not yet done, skip doing anything
    if (xhr.readyState != 4) {
      return;
    }
    // ...otherwise, look at the response for what I need
    if (xhr.responseText != 'YES') {
      // we can't allow unauthorized access
      var tag = document.getElementById('chart_div');
      tag.innerHTML = '<br/><br/><br/><p class="header">'
            + 'Unknown User</p><br/>'
            + '<p class="reason">The user "' + username + '" is not registered '
            + 'on this application. Please contact the Risk Analytics Team '
            + 'about adding your username to the list of known users.</p>'
            + '<p class="reason">Response: ' + xhr.responseText + '</p>';
    } else {
      // this user was valid, so finish the initialization
      initialize();
    }
  }
  xhr.send(null);

in this little bit, I can issue the URL, track it's progress, and then decode the answer. It's absolutely the most elegant solution I've seen in ages. I'm getting hooked on the AJAX way of doing things and while I wasn't a big fan of servlets, I'm getting there as they are a wonderful way to get into the back-end without having an enormous overhead, and subclassing really works there. Have a nice servlet that does all the database work, and subclass a bunch of servlets off that.

I have to admit, this is changing the way I look at web site building. It's also a lot more fun than the old way.