Ajax PHP Login Page with Shake Animation Effect.
Wall Script
Follow Me:
Tuesday, July 08, 2014

Ajax PHP Login Page with Shake Animation Effect.

I received few tutorial requests from my readers that asked to me how to create Ajax PHP login script, in this post I want to discuss how to create a simple Ajax PHP login with welcome page using MySQL database. This will explain you creating user tables, posting form values and storing and destroying the session values. If you are a PHP beginner take a quick look at this live demo with Username: 9lessons Password: 9lessons. This post has been updated with mysqli.

Ajax PHP Login Page


Download Script     Live Demo

Users Table
User table contains all the users registration details.
CREATE TABLE `users` (
`uid` INT(11) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(45) ,
`password` VARCHAR(100) ,
`email` VARCHAR(45) ,
`friend_count` INT(11) ,
`profile_pic` VARCHAR(150),
PRIMARY KEY (`uid`));

Jquery Code
Contains javascipt code, $("#login").click(function(){}- login is the ID name of the login button. Using element.val() calling username and password input values. If id value is even number if(id(even) % 2) = If(0) false
<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function()
{

$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');},
success: function(data){
if(data)
{
$("body").load("home.php").hide().fadeIn(1500).delay(6000);
//or
window.location.href = "home.php";
}
else
{
//Shake animation effect.
$('#box').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});

}
return false;
});

});
</script>

index.php
Contains PHP and HTML code, If session value exists this will  redirect to home page.
<?php
session_start();
if(!empty($_SESSION['login_user']))
{
header('Location: home.php');
}
?>
//HTML Code
<div id="box">
<form action="" method="post">
Username
<input type="text" class="input"  id="username"/>
Password
<input type="password" class="input"  id="password"/>
<input type="submit" class="button button-primary" value="Log In" id="login"/>
<div id="error"></div>
</div>
</form>
</div>

ajaxLogin.php
Contains PHP code, this will verify username and password values in database.
<?php
include("db.php");
session_start();
if(isset($_POST['username']) && isset($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($db,$_POST['username']);
//Here converting passsword into MD5 encryption. 
$password=md5(mysqli_real_escape_string($db,$_POST['password']));

$result=mysqli_query($db,"SELECT uid FROM users WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $username and $password, table row  must be 1 row
if($count==1)
{
$_SESSION['login_user']=$row['uid']; //Storing user session value.
echo $row['uid'];
}

}
?>

home.php
If user session value is empty, this will redirect to login page.
<?php
session_start();
if(empty($_SESSION['login_user']))
{
header('Location: index.php');
}
?>
//HTML Code
Welcome to Home Page
<a href="logout.php">Logout</a>


logout.php
Cleaning the user session value.
<?php
session_start();
if(!empty($_SESSION['login_user']))
{
$_SESSION['login_user']='';
session_destroy();
}
header("Location:index.php");
?>

db.php
Database configuration file, modify username, password and database values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


29 comments:

  1. data: {
    'username': username,
    'password': password
    },

    ReplyDelete
  2. And is necessary serialize the SESSION var

    ReplyDelete
  3. Please use PDO and indentation.

    ReplyDelete
  4. I have checked that wordpress has used this effect. can you please post here that how can we implement shake effect via custom javascript or jquery?

    ReplyDelete
  5. Pretty niffty...what the registration part to upload profile.

    ReplyDelete
  6. How you add the login and password you want?

    ReplyDelete
  7. Great one! Thanks for sharing with us Srinivas :)

    ReplyDelete
  8. how draw image flow by software? thanks

    ReplyDelete
  9. Why don'y you just do:
    data: $('form').serialize()
    Making string out of field vals is just pain in the azz :)

    ReplyDelete
  10. Very Good Example for login.Will definitely try it.Thanks.

    ReplyDelete
  11. really nice. can you please tell me what this function will do. i am confused cause loading home.php but hiding it as well. bit confusing below line

    $("body").load("home.php").hide().fadeIn(1500).delay(6000);

    thank you in advance

    ReplyDelete
  12. you also using hide function as well

    ReplyDelete
  13. Handling error cases in the success function is just fundamentally wrong. There is an error field for a reason. If the login is was not successful, send a 401 back to the client. Due to this and the points already mentioned in previous comments, I do not recommend this tutorial at all.

    ReplyDelete
  14. how to connect to sql server ,help!

    ReplyDelete
  15. how to validate a user to redirect to different pages ?, examples home_user, home_admin
    please thanks

    ReplyDelete
  16. Error Message Not Showing Up PLZ Help Me.

    ReplyDelete
  17. How can we, on the home page, take back the information like the e-mail and username?

    ReplyDelete
  18. dont work even if i create the users manually, a admin ui to add user would be nice

    ReplyDelete
  19. I downloaded. I m using xampp so i can try it, i created login "db" and there i instert the:

    CREATE TABLE `users` (
    `uid` INT(11) NOT NULL AUTO_INCREMENT ,
    `username` VARCHAR(45) ,
    `password` VARCHAR(100) ,
    `email` VARCHAR(45) ,
    `friend_count` INT(11) ,
    `profile_pic` VARCHAR(150),
    PRIMARY KEY (`uid`));

    after that, i insert username and password client on the tables. Then i changed "db.php" conditions with mine:



    but still is not "sing me in", any help?

    ReplyDelete
  20. Change it in dp.php

    define('DB_DATABASE', 'wall'); //"wall" for "demo" or where you created the table users.

    ReplyDelete
  21. Hey can you make a video TUtorial please because i am stuck on creating tables. So i created a mysql database then i opened it using phpmyadmin. But the problem is i dont know hwhat to do after that

    ReplyDelete
  22. Gracias por el código.

    ReplyDelete
  23. Mihail Llaftiu , Use md5() when you insert the password into MySql, or cut it in the code.

    ReplyDelete
  24. >Mihail Llaftiu , Use md5() when you insert the password into MySql, or cut it in the code.
    >February 25, 2015 at 4:51 PM

    Anonymous, Thank you :)

    ReplyDelete
  25. not working, it always show: Error: Invalid username and password.

    ReplyDelete
  26. Great tutorial and helpful, I have also created a Ajax Login Form Using jQuery and PHP how it is?

    ReplyDelete

Make in India