Create an Ajax Login with jQuery

Posted on Friday July 20, 2012 / by Eric Potvin

This modern Web 2.0 way to build forms improved drastically in the last few years. One of these kinda cool feature is the Ajax Login.

This Ajax Login allows the user to shows without refreshing the web page any invalid username/password credential. Once, the credential are valid, you can either redirect to a specific page or simply fade everything in to display the user page.

One detail you have to take in consideration. This Ajax Login is prone to attacks since the ajax call is independent from the login page. You can fix this by adding a validation that allows the script to be executed from an ajax call and from your domain/ip only for example. In addition you can add a token generated in the front end saved to the user session and then use this token in the login script.

In this demo, we will use a fade in login page effect (no redirection).

The Login Form

<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
  <meta charset="UTF-8">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script type="text/javascript" src="/path/to/login.js"></script>
</head>
<body>

<section>
  <h1>Login Form</h1>
  <form>
    <div>
      <label for="user">Username: </label>
      <input type="text" name="user" id="user" />
    </div>
    <div>
      <label for="pass">Password: </label>
      <input type="pass" name="pass" id="pass" />
    </div>
    <div>
      <input type="button" id="login" name="login" value="Login" />
    </div>
  </form>
  <div id="message"></div>
</section>

</body>
</html>

The Javascript/jQuery code

$(document).ready(function() {
  $("form input:button").click(function() {
    $.ajax({
      type: "POST",
      url: 'login.php',
      data: $('form').serialize(),
      dataType: 'json',
      success: function(data) {
        $('section').fadeOut('fast', function() {
          $('section').html('Welcome ' + data.name).fadeIn('fast', function() {
            $('body').css({'backgroundColor': '#' + data.background});
          });
        });
      },
      statusCode: {
        403: function(e) {
          $("#message").html(e.responseText);
        }
      }
    });
    return false;
  });
});

The PHP Code

function cleanPost($val) {
  if(!isset($_POST[$val])) {
    $_POST[$val] = NULL;
    return;
  }
  $_POST[$val] = trim(htmlentities($_POST[$val], ENT_QUOTES, 'UTF-8'));
}

function validateUser($u, $p) {
  return $u == 'demo' && $p = 'demo';
}
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
  cleanPost('user');
  cleanPost('pass');

  if(validateUser($_POST['user'], $_POST['pass'])) {
    $userPrefs = array(
      'name' => 'John Doe',
      'background' => 'FFE78D'
    );
    echo json_encode($userPrefs);
  }
  else {
    header('HTTP/1.1 403 Forbidden');
    echo 'Invalid login information provided';
  }
}
else {
  header('HTTP/1.1 404 Not Found');
  echo '404 page not found!'; // well you will have to make it prettier!
}

If you prefer to redirect to another page, simply use the modify the success: function(data) { } code to include the JavaScript redirect code to your user page.

As a reminder, don't forget to add your security and your user validation.