AJAX with jQuery is wicked easy... for real!

Images: 

I haven't had much time to play around with jQuery, but I've always been intrigued by how nicely it is used in Drupal. So, I decided to download it for a quick test. For those of you who might not be familiar with jQuery, it is a Javascript library that lets you create animations, DOM interactions, AJAX connections and more. I've used the YUI tools before which, while functional, are relatively cumbersome to implement. In stark contrast, in less than five minutes, I had downloaded the latest version of jquery and created an HTML page with a working asynchronous request.

1. Download the latest version of jQuery [jquery.com]

2. Read the quick how-to document on creating an AJAX request using the load() function.

3. Create an html file for the test with a function to call load(), which only requires one argument, though you can add key/value request variable pairs if you want to call a PHP script. You can also specify a callback function to perform after the request. We'll keep this simple for the time being:

<html>
<head>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
  function loadtest() {
    $("#loadtest").load("load.html");
    return null;
  }
  </script>
</head>
<body>
<a onClick = "loadtest();">Click here to test</a>
<div id = "loadtest">TEXT</div>
</body>
</html>

This sends a request to load.html and then populates the block id=loadtest with the response.

4. Create load.html

<strong>UPDATED TEXT</strong>

5. Seriously, that was it. Here's the working test

Now, this is obviously quite a rudimentary test lacking error checking and without proper callbacks, but I was shocked at how easy it was to implement. If you can get it up and running in five minutes, imagine what you could do in a day! The possibilities are vast!