Ajax Login Script with PHP and jQuery

User Login is a common part of any web project that allows its valid users to access certain pages. In this tutorial you will learn how to create login form using jQuery Ajax and PHP MySQL. So here we have handled login functionality by creating simple login form with Bootstrap.

The user email and password field validated using jQuery validate and login form submission handled using Ajax to perform login process without page refresh and finally displayed welcome page after successful login.

Also, read:

You can view the live demo from the Demo link and can download the full live demo script from the Download link below.

So let’s start the coding


Steps1: First Create MySQL Database Table:

I have used “users” table for this login example. So used below code to create table.

CREATE TABLE IF NOT EXISTS `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(255) DEFAULT NULL,
`pass` varchar(100) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`profile_photo` varchar(200) DEFAULT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `username` (`user`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Steps2: Insert Data into MySQL Table:

Use below code to insert user record to use with login example.

INSERT INTO `users` (`uid`, `user`, `pass`, `email`, `profile_photo`) 
VALUES
(1, 'phpzag', 'test', 'test@phpzag.com', NULL);

Steps3: We include all necessary library files and JavaScript in head tag in main file index.php:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript" src="script/validation.min.js"></script>
<script type="text/javascript" src="script/login.js"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen">

Steps4: Now Create Login Form HTML

Now we will create login form HTML with Bootstarp.

<form class="form-login" method="post" id="login-form">
<h2 class="form-login-heading">User Log In Form</h2><hr />
<div id="error">
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" 
name="user_email" id="user_email" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-default" name="login_button" id="login_button">
<span class="glyphicon glyphicon-log-in"></span>   Sign In
</button>
</div>
</form>

Steps5: Handle Login Form Submit with jQuery Ajax

Now we will handle login form submission using jQuery Ajax and send Ajax request to login.php to process login. If login process is successful then redirect to the users profile page otherwise display error message.

function submitForm() {
var data = $("#login-form").serialize();
$.ajax({
type : 'POST',
url : 'login.php',
data : data,
beforeSend: function(){
$("#error").fadeOut();
$("#login_button").html('<span class="glyphicon glyphicon-transfer"></span>   sending ...');
},
success : function(response){
if(response=="ok"){
$("#login_button").html('<img src="ajax-loader.gif" />   Signing In ...');
setTimeout(' window.location.href = "welcome.php"; ',4000);
} else {
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger">
 <span class="glyphicon glyphicon-info-sign"></span>   '+response+' !</div>');
$("#login_button").html('<span class="glyphicon glyphicon-log-in"></span>   Sign In');
});
}
}
});
return false;
}

Steps6: Process Login at Server end

After login form submission from jQuery Ajax, now we will process user login in PHP script login.php and if user password is correct then print “ok” otherwise error message.


if(isset($_POST['login_button'])) {
$user_email = trim($_POST['user_email']);
$user_password = trim($_POST['password']);
$sql = "SELECT uid, user, pass, email FROM users WHERE email='$user_email'";
$resultset = mysqli_query($conn, $sql) or 
die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if($row['pass']==$user_password){
echo "ok";
$_SESSION['user_session'] = $row['uid'];
} else {
echo "email or password does not exist.";
}
}

Steps7: HTML For Members Page

We will display members page by calling welcome.php when login successful.

<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" 
aria-haspopup="true" aria-expanded="false">
<span class="glyphicon glyphicon-user"></span> Hi <?php echo $row['user']; ?> <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#"><span class="glyphicon glyphicon-user"></span> 
View Profile</a></li>
<li><a href="logout.php"><span 
class="glyphicon glyphicon-log-out"></span> Sign Out</a></li>
</ul>
</li>
</ul>
</div>
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
Hello, <br><br>Welcome to the members page.<br><br>
</div>

Steps8: Handle User Logout

When user will click Logout button, logout.php file called to process logout.

session_start();
unset($_SESSION['user_session']);
if(session_destroy()) {
header("Location: index.php");
}

You may also like:

Demo Download


12 thoughts on “Ajax Login Script with PHP and jQuery

  1. Dear,
    thanks for this code, its use full for me,
    but i need one more help.
    how to change redirect page (welcome.php) after login process is successful.
    i changed here page name but its not working in my project.
    setTimeout(‘ window.location.href = “welcome.php”; ‘,4000);

    1. Thanks for precious comments! Plz check your file location it is on project folder root or elsewhere. I have just checked and its working fine here in demo.

  2. thank you for your tutorial,
    i tried this in my project but i am facing error on the coding.
    database connection all working fine problem is in the function.
    success : function(response){
    if(response!=”ok”)
    {
    $(“#error”).fadeIn(1000, function()
    {
    $(“#error”).html(‘   ‘+response+’ !’);
    $(“#login_button”).html(‘   Sign In’);
    });

    }
    else
    {
    $(“#login_button”).html(‘ Signing In …’);
    setTimeout(‘ window.location.href = “index1.php”; ‘,4000);

    }
    }
    });

    iam getting the error fade only

    kindly helpme on that

    1. I think you have missed defining #error in your html. Check everything carefully with tutorial, it should work.

  3. can you make the complete code available for download, assembling in bits and pieces is difficult.

    1. You can download complete code from download link at the end of tutorial. thanks!

    1. You need to store username as unique to implement login with username instead of emailid. Thanks!

Comments are closed.