Introduction to Ajax with Mootools

This is a basic tutorial that offers an introduction to the Ajax component of the mootools javascript library. At the end of this tutorial you’ll be able to use an HTML form to send requests to a PHP script and return a response without refreshing the page. This basic process is the foundation for most of the ajax that you see littered around the internet today. Mootools offers a simple way to get your feet wet with this technology, and plenty of room to grow once you know what you’re doing.

This tutorial is something of a followup to one that I wrote some time ago, describing the same basic process using the moo.ajax class, a precursor to mootools. That article still gets a fair number of visits on my site, but since moo.ajax has been deprecated it isn’t very useful. This tutorial expands on that one a little, but is essentially an update. By now everyone has heard of ajax, so there’s no need to repeat the introduction. Let’s get started.

What You’ll Need

  • Some way to run PHP scripts. Many web hosts offer this. You can also set up a web server on your personal computer, which will make the development process much more simple.
  • A copy of the mootools library. I’ll show you how to get a customized version that meets all of our requirements.

Downloading mootools

Go to the mootools download page to grab the required files. The core component will already be selected. Find the Ajax component under the Remote section and select that. It will automatically select a handful of other components that mootools needs to run the Ajax component. I’ve also checked Window.DomReady, which selects the event component and will allow us to add Ajax to a form unobtrusively (that is, without making a mess of the HTML.) Click on Choose Compression to select the preferred level of compression for your customized mootools library, which you can then download. I chose no compression because I’m creating a tutorial. You can choose whatever suits you. For live sites I’d recommend using the JavaScript Packer compression to decrease file size (from 90KB to 20KB in this case.) I’ve included the uncompressed version along with the example files. You can develop with the uncompressed version and then switch in the packed version when you make the code live. You won’t have to change any of your code to take advantage of the reduced file size.

You can follow along with this tutorial by either viewing source on the example page or downloading the full source below.

The Example

The example is a super-simple application that accepts two numbers. When you submit the form it will send the values to a PHP script via ajax, multiply them on the server, and return them to the page without refreshing. It will show this value in two places; mootools has the ability to update the contents of an element with your PHP script response or define a custom function to handle the returned data; I’ve chosen to show both. If javascript has been disabled it will simply print the return value out on an unstyled page. Not everyone is browsing with javascript enabled, so it’s important to ensure that they can still use your application without it. I could have done much more to make the non-javascript version nicer to use, but for now it performs its basic function and that’s a good start.

How it works

If you’ve looked at the source, you’ll see a pretty standard HTML page. It has a head section that includes a stylesheet, the mootools javascript file, and the application logic. It also has a body with a form in it. The application logic is the part where the cool stuff happens. Unlike my previous tutorial, I’ve taken advantage of some cool aspects of mootools to make this code clean and compact. I’ll explain these lines along the way.


window.addEvent('domready', function(){
	…
});

This block wraps around the rest of our code and tells the script to run once the DOM has loaded. That means it will run as soon as the document has been read into memory (but before all the images have loaded.) This avoids the delay you get with most javascript solutions. Inside this block, you’ll see another block:


$('testform').addEvent('submit', function(e){
	// stop the default form submit event
	new Event(e).stop();
	…
});

This tells the form “When the user submits testform, don’t perform your normal form action.” $('testform') tells mootools that you’re adding the code to an element with an id of testform (our simple form, as it happens.) Inside this block, we’re going to add instructions for what should happen instead.


var postString = "value1=" + $('value1').value + "&value2=" + $('value2').value;

Here we’re creating a string of data to post to the PHP script. This grabs the data from our form and creates a string like value1=5&value2=6. This step isn’t strictly necessary, but the values will be passed as an option to the ajax request next, and I wanted to keep that request looking pretty clean.


var myAjax = new Ajax('data.php', {
	method: 'post',
	data: postString,
	update: $('output1'),
	onComplete: function(req){
		$('output2').innerHTML = req;
		$('output2').style.background = "#adf";
	}
}).request();

This is the last bit of the script. It creates a new Ajax object called myAjax and sets the URL for the file you want to submit to, assigning some options to the request. The first is a like a form method. Just like any html form, you can submit the data using post and get. If you don’t specify anything, it defaults to post. Next we pass the request data as a string. Here, I’ve used the variable that we set earlier. Next, we use the update option to specify the id of an element. Mootools will automatically update the content of that element with whatever the PHP script sends back. Finally, the onComplete option allows you to specify a function to run when the ajax request is complete. Here I’ve told it to update another element with the same information and to highlight that element, just to show that it’s actually my function and not the update option at work. Now that we’re done setting up the new Ajax object, we call it’s request method to automatically make the request.

So that’s it. Your first steps into the world of ajax. I’ve included the whole script below so you can see how short it really is. In case you missed it above, you can view the example and download the full source.


<script type="text/javascript">
//<![CDATA[
// this is our javascript application logic
	
	// This happens once the DOM has loaded.
	window.addEvent('domready', function(){
		$('testform').addEvent('submit', function(e){
			// stop the default form submit event
			new Event(e).stop();
			
			// create a string of the variables we want to post to the php script
			// this will look like like "value1=5&value2=6"
			var postString = "value1=" + $('value1').value + "&value2=" + $('value2').value;

			// set some parameters for the ajax request...
			var myAjax = new Ajax('data.php', {
				method: 'post',
				data: postString,
				update: $('output1'),
				onComplete: function(req){
					$('output2').innerHTML = req;
					$('output2').style.background = "#adf";
				}
			}).request(); // ...and automatically make the ajax request
		});
	});
	//]]>
</script>

3 thoughts on “Introduction to Ajax with Mootools

Comments are closed.