Update: Moo.Ajax has become deprecated since I originally wrote this article, as its functionality has been incorporated into the new mootools library. I’ve written a follow-up piece that explains this same basic principal using the more current library. I’d suggest checking that out if you’re interested in a dead-simple introduction to ajax.
This is a very basic tutorial which offers a glance at the moo.ajax class from Mad 4 Milk. It doesn’t expand too much on the tutorial that they provide, but I feel that it will help clarify a few things. Don’t let the length of this article frighten you, what you are about to learn is pretty simple. I just use a lot of words to explain it. By the time you’ve worked through this tutorial, you will be able to build a form that interacts with a PHP script and returns data, without refreshing the page. It’s a pretty simple process that can serve as the basis for some very cool applications.
This tutorial should serve as an introduction to using moo.ajax for remote scripting. If you are familiar with the technologies in use—XHTML, JavaScript, and PHP—you should be able to take these founding principals and run with them to create something interesting and perhaps even useful. As a bonus, I’ve thrown in a bit about unobtrusive JavaScript and graceful degradation. These are important principals in the new era of web scripting, and learning about them will help make you a rock star of web development and get you millions of dollars, or at least ensure that your applications are the best that they can be.
Requirements
To complete this tutorial you will need the following:
- 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.
- Prototype.lite.js. This is a stripped down version of the Prototype JavaScript library. It is available from Mad 4 Milk, or in the example source file that I’ve included.
- moo.ajax.js This contains the ajax class that we will use. Along with prototype.lite.js, it does most of the actual work. It’s also available from Mad 4 Milk, or in the example source file that I’ve included.
- That’s about it.
I’ve packaged up the entire example, including the JavaScript files from Mad 4 Milk so that you can follow along at home. You should be able to upload the files to your web host unmodified, and everything should work. When we get to the code I’ll assume that you’ve downloaded it, or at least viewed the example and peeked at the source.
The Example—What’s Going On?
Our example contains a form with one input. When you submit the form, moo.ajax magically submits the input value to a PHP script, which does a little processing and then returns a value to the web page. All this happens without refreshing the page, which is exciting to myself and probably to you as well.
This example expects that you input a number. If you don’t do so, it politely asks you to try again. That’s about all you need to know to use it, so without further delay I’ll teach you how to build it.
Getting Started
At the heart of this whole thing is a simple html page with a simple form on it. I’ll assume you know how (or can figure out how) to tackle that portion of it. If not, you can see mine in the source code. Moving on, we add the follwing to the head of the document:
<script type="text/javascript" src="prototype.lite.js"></script>
<script type="text/javascript" src="moo.ajax.js"></script>
Here we’ve include the scripts that perform the magic. You can look at their contents in your free time. For now, we’ll just include them and hope that they work (don’t worry, they do.)
Get To The Cool Stuff Already!
OK, get ready. The next code snippet is where we do our thing, which is to tell moo.ajax to do it’s thing. Check this action out:
function letsRock()
{
var postString = "thevalue=" + document.getElementById("thevalue").value;
new ajax('data.php', {postBody: postString, update: 'output1', onComplete: itsOver});
}
function itsOver(request)
{
document.getElementById("output2").innerHTML = request.responseText;
}
Well that was anti-climactic. Something as cool as ajax should require impossibly complicated scripts that make your friends jealous, right? Perhaps it should, but fortunately for us, it doesn’t. The cool folks at Mad 4 Milk have made our work easy by providing their tools. So what’s exactly is going on in this little snippet of code?
First, there’s the function letsRock()
. This gets called when you submit the form. The first line of the function declares a variable postString
and builds a string to be passed to the PHP script. If you entered 3 in the input field, the variable would store “thevalue=3
“. This string can store multiple fields; use &
to separate them.
The second line of our function creates a new ajax
object (defined in moo.ajax.js.) The first parameter is the URL of the script we want to access through ajax (you’ll get a look at that script in a moment.) Next comes a list of options. postBody
tells the ajax gods that we want to pass data to our PHP script using the post method (vs. get, just like with a regular form.) postString is the variable we defined on the previous line. Building a string variable might have been overkill here, but if we decide to pass a lot of data to the script it could become quite messy. Using a variable helps us keep the script clean-looking.
The next option calls the update
method, which comes from moo.ajax.js. Specify the an DOM object or the id of an element and the update
method (optional) takes the output of your PHP script and dumps it into that element rather than outputting to a new page as is typically would. In this case the output goes to one of two paragraphs just below the form.
Finally, the onComplete
method (also from moo.ajax.js, also optional) runs a function of our choosing when the request is complete. I’ve chosen to run a function called itsOver
, which just duplicates what already happened with the update
method. I just did this to demonstrate two different ways of handling output. update
is a simple, prebuilt way to display the results of our script call, and onComplete
offers an infinitely flexible way to handle the next step once a request has been completed. Pick whichever one suits your needs best when building your own scripts.
Lets just take a quick peek at itsOver
, since we already know what it’s doing. When the request is complete, the function is fired. The output element of choice is filled with the responseText
(once again, provided by moo.ajax.js) which is the regular screen output of our PHP script. InnerHTML is a pretty good way to display this text, but not the best.
What about that PHP script? Let’s See That.
The PHP script in this example is very simple. All it does is take the value that you enter and multiply it by another number, to prove that it’s interacting with the server. Any PHP script can be used with the ajax call that we’ve made. In our case, we have 1 piece of post data to handle, and we’d like to return some output to display on the example page. Here’s the PHP script in its entirety:
<?
$multiplier = 4;
if ($result = $multiplier * $_POST['thevalue'])
print "The result is " . $result . ". The multiplier that we used was " . $multiplier;
else
print "Please enter a number";
?>
The first line sets a multiplier variable, which will be multiplied by the number that is submitted to the script. The next line is a simple if statement that multiplies the submitted value by the multiplier. If the value is a number, the calculation will be performed successfully and it will return true. Otherwise, the calculation will fail and return false. Again, I’d like to mention that this is a very basic script used only for demonstrative purposes. The sky is really the limit as far as what you can do here. We’re passing post values just like any normal form, so you can do anything here that you would in a normal PHP application.
Executing The Ajax Call
Next, we have a bit of scripting to add this functionality to our form. If you’re already familiar with the concepts of unobtrusive JavaScript, addEvent
, and graceful degradation, you can just skip the rest of this tutorial, smarty-pants. The rest of you, have a peek at the rest of the JavaScript:
function addEvent( obj, type, fn )
{
if (obj.addEventListener)
obj.addEventListener( type, fn, false );
else if (obj.attachEvent)
{
obj["e"+type+fn] = fn;
obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
obj.attachEvent( "on"+type, obj[type+fn] );
}
}
function initializer() {
var testForm = document.getElementById('testform');
addEvent(testForm, 'submit', letsRock);
testForm.onsubmit = function() { return false; }
}
addEvent(window, 'load',initializer);
</script>
The addEvent
function is a pretty common one, that has been written in many different ways. Basically, it adds an event listener (e.g. onclick
or onmouseover
) to an html object. The version that I’m using was grabbed from this post at quirksmode.org. For now, just include it in the file. In the future, you might want to put it in a separate file with other common functions, because you’ll want to use it constantly. "Why not just add and onclick to the form code?" you might ask. The short answer is that it keeps your code clean and easy to maintain–it’s called unobtrusive JavaScript, and it’s the right way to do it. A longer answer can be found via the DOM Scripting Task Force.
After our addEvent function, we have a function called initializer
. This uncreatively named function prepares the form to do it’s ajaxy thing. First, we declare a variable and store a reference to our form, for ease of use in the next two lines. Then we use addEvent
to make the form to execute our letsRock
function (defined above) when it is submitted. Then, we tell the form to return false when it is submitted. This prevents the form from bringing us directly to the PHP page when it the user presses "Submit", and instead allows letsRock
to do it’s work.
Finally, we use another addEvent to attach our initializer function to the onload event handler for the web browser window. This means that once the window loads, and all the elements have been created, the other events will be attached. This prevents errors that can be caused by trying to modify a page element before it is created.
An interesting thing to note about all this JavaScript is that the form will work without it. Don’t believe me? Go ahead and try it with JavaScript turned off. The output isn’t as pretty, but you get the same information. This is what’s meant by “graceful degredation”–whenever possible, you should write applications that will work without JavaScript. This allows your application to be functional to the greatest number of users.
What’s Left?
Not much. All we have to do is build the HTML page. The tricky stuff is over. The rest of the code is available in the file download or the example source, so I won’t bother repeating it here.
In case you missed it before, here’s the example again.
Debriefing
I’d just like to state once more that this is pretty much the ground floor of using ajax. There are better and more complicated ways of doing most of what I’ve done here, and there is no upper limit to the impressive things that you can achieve with the technology and a bit of creativity.
thanks dude!
this helped more than anything else i’ve read on ajax and moo ajax.
I really didnt know that the php script simply needed some printed output which is used as the request data. I thought it was a special variable.
So simple.
Thank you for taking the time.
Bye.
scott, this was an awesome amount of help, and thanks for the work and sharing.
I am interested in understanding more about how to modify the ‘initializer’ to handle more than one button on a form, if possible with the moo.ajax call, and thereby maintain unobtrusive JavaScripting. Other buttons might be “validate” or “check”, in addition to “compute”, for example.
Also, it would be cool if you could suggest the variations or ‘complications’ you had in mind, even if you don’t have time/space/purpose for them here, to get/give a sense of whether ‘simple’ is good enough, :-), or ‘more homework’ is advisable, :-(.
And if we already put that prototype thing to memory why not use it more. Instead of every document.getElementById() there nice and tricky $() function which does same is way shorter.
But still it’s always nice to see somebody doing something for others.
Cheers.
Thanks to all for the feedback.
@Jack: That’s what suprised me about it as well. Once I figured out that you could just return your script’s printed output, I decided to write a tutorial about it, since I felt other tutorials never really showed that part of it.
@A. Friendly: I’ve set up a supplemental example to show one way of handling multiple submit buttons. It might not be the easiest way, but it’s the first thing that came to mind for me. Here’s the example, and here’s the source for it. The easy part was making it work without Javascript; the tough part was getting it to work with javascript!
Also, I’m planning on making an overhaul of the article based on some feedback I’ve gotten (thank you) and also writing a follow-up or two, so I’ll be adding more advanced, complicated, and hopefully useful examples.
I would, of course, recommend doing more homework on what’s available with ajax. However, the simple stuff that I’ve outlined here is enough to do some really cool things. I guess the best way to put it is that if what’s written here offers the solution to your problems, then it’s all you need. If not, then you can always study up. I’ll be providing more material soon.
@Piotrek: Great idea! I had originally planned on only using the ajax object itself for simplicity, but utilizing the other tools available in prototype(lite) would probably make it MORE simple, rather than less. I’ll probably change that when I revise the article.
scott, thanks a bundle for the second example.
I have done a little more homework.
I was able to clip out of prototype.js some bits related to forms, so I can use Form.serialize. I love the size/parsimony of the moo.fx scripts, so I wanted to at least try to keep to that.
With that done, I can use the code as a ajaxy-‘widget’ for most simple forms.
One important caveat, the snippet — call it “formslite.js” — is working with Firefox, but not at all with IE, which seems to want the whole prototype.js. So, in my enthusiasm, I may have taken one step forward, and one step back. LOL.
Cheers and thanks again!
Hello old / new friend. I visited your site for the first time and found this interesting bit of information. It was ingenious, thanks for the information. How have you been?
thanks for the great tutorial, i m trying to implement live comments with moo.ajax in my wordpress theme.
I want to use moo.ajax to load snippets of plain HTML into a div. These are static html files. I must be missing something because it works fine when uploaded to a web server (apache), and not local testing (IIS). I read something about HTTP headers – is this relevant?
I’ve just gotten into AJAX and I’m loving it so far. This little thing’s got me stumped.
Hellmoooo :p
First of all, thank you for the great tutorial you have written on moo.ajax!
I’am looking for a way to use moo.ajax in a contact form in my website. Your tutorial is clear, but what I need is a form with more than one and I have real difficulties with javascript.
So, could you help me in my quest ? 🙂
Thank you!
Thanks so much Scott. Great help.
And oakleaf: putting multiple fields on the form is pretty easy – just pile them up into the postString:
var postString = “thevalue=” + document.getElementById(“thevalue”).value + “&thesecondvalue” + document.getElementById(“thesecondvalue”) + “&thethirdvalue” + document.getElementById(“thethirdvalue”);