Search

Play School: Easy Ajax – load

Posted on 13th January 2009 — Ajax is made incredibly simple with jQuery. There’s a number of helper functions to get in to the nitty gritty of Ajax, but if you want something that’s quick and simple to get going with the .load function is the best place to start.

.load will pull a URL from your server and load it in to the selector you specify.

Watch

Watch the jQuery Ajax load screencast (Alternative flash version)

QuickTime version is approximately 20Mb, flash version is streaming.

View the demo used in the screencast (view the source)

Search Example

Our example has a simple search field and works initially without JavaScript enabled.

We’re going to then apply jQuery, and when the users enters a key in the search field it fires off an Ajax request.

jQuery

The jQuery required to hijax the page so that live searching can occur is very simple.

The steps required are:

  1. Trigger some code when the user keyup on the search field.
  2. Send the search string to the server and insert the contents in the DOM.

The load function takes 3 parameter, only the first is required:

load(url, data, callback)

In the screencast we change the PHP script so that it only returns the HTML fragment, such as:

<li>Times</li>
<li>Times New Roman</li>

And our jQuery was simple:

$(function () {
  $('#name').keyup(function () {
    $('#results ul').load('load-example.php', { name : this.value });
  });
});

Note that the parameters for the Ajax call are passed in separately as an object. When the parameters are passed in, the Ajax call is performed as a POST (not a GET).

Alternative Version

The final example, we decide to use the feature that allows us to load a URL and run the selector on the result.

So we call the url followed by the selector that contains the content that we’re interested in:

$(function () {
  $('#name').keyup(function () {
    $('#results ul').load('load-example.php #results ul li', { name : this.value });
  });
});
Update: It’s worth noting that as of jQuery 1.3, the load function can take a string instead of an object if so required.

Finally: Optimisation

It’s worth noting that every time the user presses a key, there’s an Ajax hit. We wouldn’t want to do this in a real situation, unless we knew our server could take the traffic.

We could run this code when the form is submitted (remember to cancel the browsers default action by return false) or we could use a delay trick to ignore a quick succession of key presses (which you can see in the Ajax to validate forms example).