rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

Create an Ajax Login with jQuery

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 of 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>
  <meta charset="UTF-8">
  <script type="text/javascript" src=""></script>
  <script type="text/javascript" src="/path/to/login.js"></script>

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


The Javascript/jQuery code

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

The PHP Code

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

function validateUser($u, $p) {
  return $u == 'demo' && $p = 'demo';

  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 used to 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.