The MooTools JavaScript library provides us with the Request class. This class wraps the XmlHttpRequest object and allows us implementing ajax in a much simpler way.

The following code sample shows how simple it is to use the MooTools Request class. It includes two files.

The first file is the HTML file that includes code in JavaScript that uses the MooTools library in order to send an asynchronous HTTP request to the server.

<!DOCTYPE html>
<html>
<head>
    <title>ajax demo</title>
    <script type="text/javascript" src="mootools.js"></script>
</head>
<body>
    <script type="text/javascript">
        new Request({
            url: 'ajaxdemo.php',
            method: 'get',
            data: {
                name: 'dave',
                id: 12341323,
                average: 92
            },
            timeout: 4000,
            onRequest: function() {
                document.writeln("<br>request...");
            },
            onFailure: function(xhr) {
                document.writeln("<br>ajax failed...");
                //getting info about the failure from the xhr object
            },

            onTimeout: function() {
                document.writeln("<br>timeout...");
            },
            onSuccess: function(text) {
                document.writeln("<br>"+text);
            }
        }).send();
    </script>

</body>
</html><!DOCTYPE html>
<html>
<head>
    <title>ajax demo</title>
    <script type="text/javascript" src="mootools.js"></script>
</head>
<body>
    <script type="text/javascript">
        new Request({
            url: 'ajaxdemo.php',
            method: 'get',
            data: {
                name: 'dave',
                id: 12341323,
                average: 92
            },
            timeout: 4000,
            onRequest: function() {
                document.writeln("<br>request...");
            },
            onFailure: function(xhr) {
                document.writeln("<br>ajax failed...");
                //getting info about the failure from the xhr object
            },

            onTimeout: function() {
                document.writeln("<br>timeout...");
            },
            onSuccess: function(text) {
                document.writeln("<br>"+text);
            }
        }).send();
    </script>
</body>
</html>

The second file is the PHP file that receives the HTTP request, retrieves the parameters it includes and returns a reply.

<?php
$id = $_GET['id'];
$name = $_GET['name'];
$average = $_GET['average'];
echo "data ($id,$name,$average) was received";
?>

The following video clip overviews this code sample, shows its execution and explains each and every part of it.

You can find more video clips, presentations and code samples for learning how to use the MooTools JavaScript library in my MooTools Basics course at http://abelski.lifemichael.com.

Leave a Reply

Your email address will not be published. Required fields are marked *