Add AJAX to your PHP Login Form

One good place to sprinkle some AJAX functionality is your login forms. Login forms have two outcomes - either the user gets logged in and taken to protected area of your site or they get an error message. Why keep reloading your login page to show the user login errors when you can do it with Ajax?

We’ll use a simple login form for our example with a hardcoded username and password to keep things short. You’re on your own for adding the code to connect to your database to check login credentials.

First we’ll assume a basic, non AJAX PHP login page with the following code:

<?php
define('Username', 'ADMIN');
define('Password', 'ADMIN');
$strAction = $_GET['Action'];
if (strtoupper($strAction) == 'LOGIN') {
 TryLogin();
}
function TryLogin() {
 global $strUsernameVal, $blnLoginErr;
 $strUsernameVal = $_POST['Username'];
 $strPasswordVal = $_POST['Password'];
 if ($strUsernameVal == Username && $strPasswordVal == Password) {
  // Success
  header('Location: index.php');
 }
 else {
  // Invalid Login
  $blnLoginErr = true;
  return false;
 }
}
?>
<html>
<body>
<?php if ($blnLoginErr) { ?>
<p>Error: Invalid login details. Please try again.</p>
<?php } ?>
<form name="Login" method="post" action="login.php?Action=Login">
Username: <input type="text" name="Username" value="<?php echo htmlspecialchars($strUsernameVal); ?>"/><br/>
Password: <input type="password" name="Password"/><br/>
<input type="submit" value="Login">
</form>
</body>
</html>

This page will submit to itself and check the form login details against the defined username and password. If the credentials don’t check, it sets a global page error which is displayed when the page is displayed.

Now to add the Ajax part, we will be using the Prototype library and its Ajax classes. Download Prototype and include the script in the <head></head> section of your login page. Next add the following Javascript also to the head section of your page:

<script language="Javascript">
function TryLogin() {
 var objForm = document.forms['Login'];
 
 if (!objForm) {
  return true;
 }
 
 var strUsernameVal = objForm.elements['Username'].value;
 var strPasswordVal = objForm.elements['Password'].value;
 
 
 if (strUsernameVal.length < 1 || strPasswordVal.length < 1) {
  var strError = 'Please fill in all required fields.';
  alert(strError);
  return false;
 }
 
 var objParams = {
  method:'post',
  parameters: 'Username=' + strUsernameVal + '&Password=' + strPasswordVal
 }
 var objRequest = new Ajax.Request('ajaxlogin.php', objParams);
 return false;
}
</script>

This script grabs the login details from your login form and uses the Prototype Ajax class to post them to an Ajax login script appropriately named ajaxlogin.php. We will now link your login form to the Javascript TryLogin() function. Add the following code inside your <form> opening tag:

onSubmit="return TryLogin();"

This will direct your form to the Javascript function or fall back on the standard login if the Javascript is not supported.

You will now need to create a new PHP script called ajaxlogin.php with basically the same login function as login.php, only it will output Javascript that will be executed by the Prototype Ajax class. The following code should be the code for ajaxlogin.php.

<?php
define('Username', 'ADMIN');
define('Password', 'ADMIN');
header('Content-type: text/javascript');
TryLogin();
function TryLogin() {
 global $strUsernameVal, $blnLoginErr;
 $strUsernameVal = $_POST['Username'];
 $strPasswordVal = $_POST['Password'];
 if ($strUsernameVal == Username && $strPasswordVal == Password) {
  // Success
  echo("location.href='index.php';");
 }
 else {
  // Invalid Login
  echo("alert('Invalid login details. Please try again.');");
 }
}
?>

If you notice, the two key differences in this script than your original login page is where the ContentType is set to Javascript and the Javascript that is outputted on login success or failure. The Prototype Ajax class will execute this Javascript on your login page. Keep in mind that anything you want to send from this script must be outputted as Javascript.

The new login.php script would look like this:

<?php
define('Username', 'ADMIN');
define('Password', 'ADMIN');
$strAction = $_GET['Action'];
if (strtoupper($strAction) == 'LOGIN') {
 TryLogin();
}
function TryLogin() {
 global $strUsernameVal, $blnLoginErr;
 $strUsernameVal = $_POST['Username'];
 $strPasswordVal = $_POST['Password'];
 if ($strUsernameVal == Username && $strPasswordVal == Password) {
  // Success
  header('Location: index.php');
 }
 else {
  // Invalid Login
  $blnLoginErr = true;
  return false;
 }
}
?>
<html>
<head>
<title>Login</title>
<script language="Javascript" src="prototype.js"></script>
<script language="Javascript">
function TryLogin() {
 var objForm = document.forms['Login'];
 
 if (!objForm) {
  return true;
 }
 
 var strUsernameVal = objForm.elements['Username'].value;
 var strPasswordVal = objForm.elements['Password'].value;
 
 
 if (strUsernameVal.length < 1 || strPasswordVal.length < 1) {
  var strError = 'Please fill in all required fields.';
  alert(strError);
  return false;
 }
 
 var objParams = {
  method:'post',
  parameters: 'Username=' + strUsernameVal + '&Password=' + strPasswordVal
 }
 var objRequest = new Ajax.Request('ajaxlogin.php', objParams);
 return false;
}
</script>
</head>
<body>
<?php if ($blnLoginErr) { ?>
<p>Error: Invalid login details. Please try again.</p>
<?php } ?>
<form name="Login" method="post" action="login.php?Action=Login">
Username: <input type="text" name="Username" value="<?php echo htmlspecialchars($strUsernameVal); ?>"/><br/>
Password: <input type="password" name="Password"/><br/>
<input type="submit" value="Login">
</form>
</body>
</html>

You should now have a working Ajax powered login form. If Javascript is supported, the form will be submitted via Ajax to your ajaxlogin.php script, which will either direct the login user to the protected area of your site or alert them of invalid credentials. If Javascript is not supported, the old, boring login will be the fallback.

From here you will need to add the code to connect to your database for login credentials. You will also want to add the cookies or session code to actually log the user in. The script in its current state simply redirects the user on a successful login or alerts them of an unsuccessful one.

Tags: ,
Posted in: Articles

Write a Comment