Asynchronous JavaScript and XML (Ajax) saves time by updating a page without refreshing it completely. Ajax has been around for a long time, with varied limits of browser support. It is safe to say that Google is most guilty of showing the world how easy it is to use.
Now with the MooTools abstraction layer's Request object, Ajax is child's play.
<script type="text/javascript" src="mootools-1.3.0.js"></script> </head> <body> <form action="" method="get"> <input type="button" id="mybutton" value="Ajax!" onclick="ajax_it();"/> </form> <script type="text/javascript"> var myJax = new Request({ url: '?', onSuccess: function(response) { alert('Success! Here is the response: ' +response); } }); function ajax_it() { myJax.send(); } </script>
Switch the
url
property to that of the script that will process the Ajax request. Like any good recipe, it is important to switch out ingredients as the chef's needs arise, for instance, artificial sweeteners for sugar. In this snippet, the url
variable, or to be more semantically correct, property
of the myJax
object is currently set to ?
. This probably only has purpose in this academic setting. The usage in this case causes this page to request itself, and the result is that the page calls its own URL and displays the resulting source code.
One great example of how to use Ajax to make our web pages more friendly is in conjunction with a user sign-up form. It can be frustrating for users to submit their form only to find out their desired username is in use.
Program the sign-up form's input field to make an Ajax call onkeyup
. The returning value would be a Boolean that could be used to notify the user whether their choice was available or in use.
Chapter 5, Mr. Clean Uses Ajax: Remote Asynchronous Calls is complete with Request(), Request.HTML
, and Request.JSON
examples.