AHAH! It’s jQuery!

8/08/2006

This was going to be a post about my first stab at AJAX. But, as technically it’s AHAH, I thought I’d use the lame title above…

This snippet uses jQuery – an excellent little piece of Javascript that makes this sort of trickery relatively simple.

Firstly, have a look at the basic syntax here: jquery.com/docs/ajax

A couple of things that I stumbled on:

  1. Content loaded via the .load call doesn’t have any event handlers attached, so in the Callback function you need to use .find() to look for any elements you want to assign events to.
  2. Getting the ID of the element clicked ended up being pretty simple: this.id
  3. Getting the value of a form field involves a simple walk around the DOM – as the form isn’t actually “Submitted” – use document.GetElementById(”fieldID”).value

Then you should end up with something more-or-less like this:

<script type="text/javascript">
$(document).ready(function(){ // Gets everything set up on page load
	$("#searchbutton").click(function(){
	  // Search button has been clicked - let's do some AJAX, baby!
	  $("#animal_table").load("/includes/catalogue/getlots.php",{
		start: "0", // pass static values
		year: "<?php echo $thispage['year']; ?>", // pass PHP variables
		sire_id: document.getElementById("sire_id").value
		// or pass element values from a form field or similar
		},function(){
	      // search for new "a" elements after .load 
		  // is called so loaded stuff can be clicked,
		  // as stuff loaded this way has no event handlers attached
		  $("#animal_table").find("a").click(function(){
			$("#animal_detail").load("/includes/catalogue/showdetail.php",{
			  lot_id: this.id // pass the ID of whatever link is clicked
			});
			return false; // so the link doesn't actually load a new page
		  });
		});
	});
});
</script>
 

Download this code: ahah-jquery.js

See it in use here: glenfosslyn.com.au/pages/2006-sale (This is a work in progress – it may or may not be working at the time you visit!)

Browse similar topics:

There is 1 comment in this article:

  1. 16/04/2009Ruslan says:

    test of AHAH with internal javascripts

    jQuery http://fullajax.ru/temp/asyncjs/jquery3.png – load page ~ 36.7 second

    Fullajax http://fullajax.ru/temp/asyncjs/flax3.png – load page ~ 3.5 second