Book Image

PHP Ajax Cookbook

Book Image

PHP Ajax Cookbook

Overview of this book

Table of Contents (16 chapters)
PHP Ajax Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Building an AJAX login form using prototype.js


The last JavaScript framework in this chapter is prototype.js. In this task, we will make a simple login form with AJAX functionality. We will have a look at the most frequently used practices for prototype.js with AJAX.

Getting ready

We can download prototype.js from http://www.prototypejs.org/download. Then, just save it in the js folder. To finish this task we will need to have the Apache Server running.

How to do it...

  1. First, let's create our dummy .php file, login.php:

    <?php 
    if($_POST['username']==$_POST['password']){
      echo 'proceed';
    }
    ?>

    Then, we can continue with our HTML layout.

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
      <form id="loginForm">
        <label for="username">Username: </label>
        <input type="text" id="username" name="username" />
        <br />
        <label for="password">Password:</label>
        <input type="password" id="password"  name="password"/>
        <br /><br />
        <input type="submit" value="Sign In" id="submit" />
      </form>
    </body>
    </html>
  2. When the HTML is set, we will define our JavaScript:

    <script src="js/prototype.js"></script>
      
    <script>
      
    $('submit').observe('click', login); 
      
    function login(e) {
      Event.stop(e);
      
      var url = "ajax/login.php"; 
      
      new Ajax.Request(url, {
        method: 'post',
        parameters: { 
          username: document.getElementById('username').value,
          password: document.getElementById('password').value 
        },
        onSuccess: process,
        onFailure: function() { 
          alert("There was an error with the connection"); 
        }
      });
    }
      
    function process(transport) {
      var response = transport.responseText;
      if(response == 'proceed'){
        $('loginForm').hide();
        var my_div = document.createElement('div');
        my_div.appendChild(document.createTextNode("You are logged in!"));
        document.body.appendChild(my_div);
      }
      else
        alert("Sorry, your username and password don't match.");  
    }
    </script>

How it works...

As you can see in the source, we observe a new click event on the button element with ID submit, which is the submit button in our login form. The login() function is triggered by the click event. The default behavior of the submit button was replaced by Event.stop(event), and so triggering the HTTP request was disabled. An AJAX request was created instead. Ajax.Request is the basic class for using AJAX in prototype.js. We are using the post method with two parameters (username and password). If the request was successful and the response text from login.php was proceed we were successfully logged in.

There's more...

prototype.js extends the Ajax.Request object to a few more, as discussed:

  • Ajax.Updater:

    Ajax.Updater is an extension of the Ajax.Request object, which performs an AJAX request and updates the container, based on response text:

    <div id="container">Send the request</div>
    
    <script>
    $('submit').observe('click', login);
    function login(){
      new Ajax.Updater(
        'saladContainer', 'login.php', { method: 'post' }
      );
    })
    </script>
    
  • Ajax.PeriodicalUpdater:

    In the case that we need to update our content at regular intervals, we can use periodical updater:

    new Ajax.PeriodicalUpdater('items', '/items', {
      method: 'get', frequency: 3, decay: 2
    });

    Frequency represents the periodicity (in number of seconds) of updating the content. In the preceding code snippet, our content will be updated every 3 seconds.

  • Ajax.Responders:

    Ajax.Responders represents a repository of global listeners that monitor all AJAX activity on the page:

    Ajax.Responders.register(responder)
    Ajax.Responders.unregister(responder)

    With responders we can easily track how many AJAX requests are active on our page.

    Ajax.Responders.register({
      onCreate: function() {
        Ajax.activeRequestCount++;
      },
      onComplete: function() {
        Ajax.activeRequestCount--;
      }
    });