Previous Page
Next Page

11.2. Building an AJAX Login

Building an AJAX login is a simple process if you're using an AJAX library that supports submitting a form using AJAX. If your library of choice doesn't do that, you have a bit of work to do, but it's only two fields, so grabbing their values by hand isn't too hard. Our first login implementation will use HTML_AJAX and its formSubmit method; this is the simplest AJAX login case, but it may not work in all cases due to its limited flexibility.

Although it's possible to use other methods, the easiest way to create an AJAX login system is to use cookie-based logins. PHP has a system called sessions that makes this easy to do. Before outputting any content, run the session_start() function; if a session ID cookie exists, PHP uses this ID to load any data associated with this ID from where it is stored on the server. If the session ID cookie doesn't exist, PHP generates a random string that identifies this session and adds a header to send to the browser. Other server-side languages offer similar features, either built-in or through standard libraries. The important part of a session-based approach is that it stores only an ID in the browser cookie; all other data is stored on the server.

The AJAX login form works by updating information in the session to say that the user is logged in. Because the data is stored on the server, other pages don't need to be notified that a login has occurred. If the other pages submit any data, the server can check that the user is logged in. Our login form will provide a form with inputs for a username and password. When the form is submitted, PHP code will update the session storing the username for latter use. The PHP page will then generate a logout button, because redisplaying the form doesn't make sense. In review, the workflow of login form is shown in Figure 11-2.

Figure 11-2. Workflow of the AJAX login process using HTML_AJAX

  1. Include a login form in a normal page.

  2. Submit the form over AJAX.

  3. The PHP script processes the login and updates the session.

  4. The contents of the form are regenerated.

  5. The JavaScript code uses innerHTML to replace the contents of the form with the new version.

To start this process, we need a Web page into which we want to log. This page needs to run session_start() before outputting content, and it needs to include the HTML_AJAX JavaScript libraries. Last, it needs to include the login form. A minimal sample page is shown in Listing 11-1.

Listing 11-1. index.php

1  <?php
2  session_start();
3  ?>
4  <html>
5  <head>
6  <title>Sample Page</title>
7  <script src="server.php?client=all"
8    type="text/javascript"></script>
9  </head>
10 <body>
12 <p>
13 This page might contain a blog post, or
14 any other content where a login
15 might be useful.
16 </p>
18  <div id="loginForm" style="
19   border: solid 1px black;
20   width:250px; padding: 2px">
21 <?php
22   include 'SimpleLogin.php';
23 ?>
24 </div>
25 </body>
26 </html>

This sample page could hold any kind of content, but it must meet the requirements for the embedded login form. Line 2 starts the session. Because this command adds HTTP headers to the response, it needs to be done before any content is generated. Lines 78 include the HTML_AJAX JavaScript libraries; you always want to include JavaScript files in the head section of the HTML document because they will slow the display of any HTML that follows the includes. Lines 1820 contain a wrapper DIV for the form. When the form is submitted, the innerHTML of this DIV will be replaced with updated content. Line 11 includes an external PHP file that generates the login form. The basic form could be produced directly in this page, but having the form always generated by the same code helps in its maintenance. The rest of the page could be any HTML content; in this case, it's just a paragraph of text (lines 1216). Finishing the basic login system is the SimpleLogin.php file (see Listing 11-2).

Listing 11-2. SimpleLogin.php

1  <?php
2  if (!session_id()) { session_start(); }
3  $message = "";
4  if (isset($_POST['ajaxLogin'])) {
5    // hard coded login, use the application's
6    // normal login code here
7    if ($_POST['username'] === 'jeichorn' &&
8      $_POST['password'] === 'test') {
9      $_SESSION['login'] = true;
10    }
11    else {
12      $_SESSION['login'] = false;
13      $message = "Login Failed";
14    }
15 }
16 if (isset($_POST['ajaxLogout'])) {
17    $_SESSION['login'] = false;
18    $message = "Logout Complete";
19 }
20 ?>
21 <form method="POST" action="SimpleLogin.php"
22 onsubmit=
23 "return !HTML_AJAX.formSubmit(this,'loginForm');">
24 <?php
25 echo "<p>$message</p>";
27 if (!isset($_SESSION['login'])
28    || $_SESSION['login'] == false) {
29 ?>
31 <b>Login</b><br>
32 <label>Username:
33    <input name="username">
34 </label><br>
35 <label>Password:
36    <input name="password" type="password">
37 </label><br>

38 <input type="hidden" name="ajaxLogin" value="1">
39 <input type="submit" value="Login">
41 <?php } else { ?>
43 Logged in as Test<br>
44 <input type="hidden" name="ajaxLogout" value="1">
45 <input type="submit" value="Logout">
47 <?php } ?>
49 </form>

The first 20 lines of SimpleLogin.php handle processing the form. This code logs the user in or out and creates a $message variable that can be used to tell the user that a login has failed. On line 4, the code checks whether the hidden variable ajaxLogin is set; if it is set, we perform a login. Line 2 starts a session if it hasn't already been; this allows this page to be included in another page or to work stand-alone. The actual login check is hard-coded to a username of jeichorn and a password of test (lines 710). If the login succeeds, we set a flag in the session (line 9). If the username or password does not match, we set the session login flag to false (line 12) and set $message to a failure message (line 13). Lines 1619 contain code for handling logout. If the hidden field ajaxLogout exists, we set the session login flag to false and add a notification message to $message.

The rest of the page generates the login form or the logout form. The form tag is generated on lines 2123. Its method is set to POST, and its action is set to this same page, SimpleLogin.php. When the form submission button is clicked, the onsubmit handler on the form (line 23) calls HTML_AJAX.formSubmit. The first parameter is the form to process; the value this, which means the current form, is used. The second parameter is the ID of the element to update with the results. Line 25 contains PHP code to output the message that was set up during the login processes. Lines 2728 check to see which mode the form is in. If the login flag isn't set at all, or if it's set to false, then we produce a login form (lines 3040). If the login flag is set to true, we produce a logout form (lines 4246). The login forms are minimaljust a login and password field or a logout button. You can see what this basic form looks like in Figure 11-3.

Figure 11-3. Basic login form

Previous Page
Next Page