This tutorial will explain you, how to create a Login Script using jQuery Ajax with PHP MySQL, well this is my continuation post after Registration post using jQuery and Ajax, so in this tutorial i am going to create a simple login form using Bootstrap. email and password will be validate if user leave it empty after it a form will br submitted using $.ajax() method and send the users value to the main login page all the process will done without page refresh, before proceed you can go through the demo and download the script, let's start the coding.
read also : Ajax Registration Script with jQuery, PHP, MySQL
that's it, we have created here a simple login script with Ajax, jQuery, PHP, MySQL with BootStrap design, well this is a continuation part of my previously posted tutorial. hope you like it.
read also : Ajax Registration Script with jQuery, PHP, MySQL
Database and Table
I have used here the previously created database and table which are used in ajax registration post, use the following code to create table in database "dbregistration"
CREATE TABLE IF NOT EXISTS `tbl_users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(25) NOT NULL,
`user_email` varchar(60) NOT NULL,
`user_password` varchar(255) NOT NULL,
`joining_date` datetime NOT NULL,
PRIMARY KEY (`user_id`)
)
dbconfig.php
Database configuration file, modify username, password and database values as per your need.<?php
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
try{
$db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
Simple User Login Form
To load BootStrap design we have to add following two css bootstrap files just above the closing </head> tag<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen">
create a new file and save it as index.php with the following code, this is our main login page contains html user friendly login form which will accepts email, password and of course validation is must so validation is there. <div class="signin-form">
<div class="container">
<form class="form-signin" method="post" id="login-form">
<h2 class="form-signin-heading">Log In to WebApp.</h2><hr />
<div id="error">
<!-- error will be shown here ! -->
</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="btn-login" id="btn-login">
<span class="glyphicon glyphicon-log-in"></span> Sign In
</button>
</div>
</form>
</div>
</div>
login_process.php
Contains only PHP code, this will verify email and password values in database, this file will work silently at back-end and call via $.ajax() method using jQuery code. if the login was success it gives ok message or if fails it will print wrong details message.<?php
session_start();
require_once 'dbconfig.php';
if(isset($_POST['btn-login']))
{
$user_email = trim($_POST['user_email']);
$user_password = trim($_POST['password']);
$password = md5($user_password);
try
{
$stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_email=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
$_SESSION['user_session'] = $row['user_id'];
}
else{
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
Script.js
JavaScript/jQuery code which is responsible to do all the things silently, this will call "login_process.php" through $.ajax() method and id "response" is ok then it will redirect to the home page, if not it will display appropriate message within "#error" div. this script is completed with proper validation.$('document').ready(function()
{
/* validation */
$("#login-form").validate({
rules:
{
password: {
required: true,
},
user_email: {
required: true,
email: true
},
},
messages:
{
password:{
required: "please enter your password"
},
user_email: "please enter your email address",
},
submitHandler: submitForm
});
/* validation */
/* login submit */
function submitForm()
{
var data = $("#login-form").serialize();
$.ajax({
type : 'POST',
url : 'login_process.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-login").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(response)
{
if(response=="ok"){
$("#btn-login").html('<img src="btn-ajax-loader.gif" /> Signing In ...');
setTimeout(' window.location.href = "home.php"; ',4000);
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
$("#btn-login").html('<span class="glyphicon glyphicon-log-in"></span> Sign In');
});
}
}
});
return false;
}
/* login submit */
});
home.php
this is our members home page and only members can access it, this file will opened via ajax, and if session is empty it will redirect to the login/index page.<?php
session_start();
if(!isset($_SESSION['user_session']))
{
header("Location: index.php");
}
include_once 'dbconfig.php';
$stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_id=:uid");
$stmt->execute(array(":uid"=>$_SESSION['user_session']));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Form using jQuery Ajax and PHP MySQL</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen">
<link href="style.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Hello '<?php echo $row['user_name']; ?></strong> Welcome to the members page.
</div>
</div>
</div>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
logout.php
destroy the session to logout the user and redirects to the login/index page.<?php
session_start();
unset($_SESSION['user_session']);
if(session_destroy())
{
header("Location: index.php");
}
?>
that's it, we have created here a simple login script with Ajax, jQuery, PHP, MySQL with BootStrap design, well this is a continuation part of my previously posted tutorial. hope you like it.
Thanks for sharing the code. It was helpful to create login script using jQuery Ajax with PHP MySQL. Hire PHP developers from a skilled and experienced PHP web development company which provides excellent PHP development services.
ReplyDeleteThanks for sharing the code. It was helpful to create login script using jQuery Ajax with PHP MySQL. but i get this warning and don't let me register :
ReplyDeleteSQLSTATE[42000] [1044] Access denied for user 'sixoneth_fives'@'localhost' to database '_dbregistration' !
thank you.
Hello Iraj, please check username of your local server
DeleteI keep getting errors http://error404.000webhost.com/cpu-limit-reached.html , pm if u want to use a subdomain on my host.
DeleteDemo link not working, when i try to log in to mine using test, [email protected] i get message email or password does not exist.
ReplyDeleteHello Midas, please make sure you have entered correct details, and also check in your mysql table that details exist or not
DeleteHello sir . I have a same problem with Mr. Midas. I have already check and re-check for a few times , the codes and also my sql table ( all details) and still get this error message "email or password does not exist." . Please help , how to solve it . It mean a lot sir.
DeleteHello sir . I have a same problem with Mr. Midas. I have already check and re-check for a few times , the codes and also my sql table ( all details) and still get this error message "email or password does not exist." . Please help , how to solve it . It mean a lot sir.
DeleteReally nice tut! thanks for sharing.
ReplyDeletethanks for visiting fher
Deletedo visit again :)
Nice tutorial, thank you!
ReplyDeleteHow can i redirect a user to his unique homepage with his email?
like window.location.href = "[email protected]"
Thank you!
Thanks for the tut! How can I redirect every user to his own page, e.g. by ID?
ReplyDeleteThank you!
I can not log in, notification email or password does not exist. ! always appear.
ReplyDeletealthough the email and password is matching. Please Help.
Awesome posts here.
ReplyDeleteBut, I set up the server but continuously getting login error "email or password does not exist. !"
What could be the cause ?
can't sign in I've provided all appropriate details sir
ReplyDeletehello osampas, please let me know actual error, it's not enough to get ...
DeleteThis user mail and password enter for correct only.
ReplyDeleteBut always showing the wrong username password.
Then how to login?
Hi SARATHI B
DeleteI also got this error finally i found the password is in MD5
u have to enter MD5 encrypt password to user_password column in table.
hope this help
This code just is for login/logout after registration. To check whether the code works just insert some data (useraname and password) in the database using phpmyadmin.
DeleteIf you want a registration form you have to do it separately, it is not included in the code.
Yes the validation is looking for an md5 encrypted password . Either use the md5 function to insert encrypted psw into the table or remove md5 in line 10 login_process.php. Better to use encryption if you are using for a live site
DeleteMD5 crypt +1 :) thank's
DeleteThank you for your code. How to register new account?
ReplyDeleteHello Wedotech,
Deletewhat you are looking for, there is tutorial on this blog about ajax registration please go through the posts...
Beautiful tutorial, thanks for sharing
ReplyDeleteyou're welcome, federico :)
DeleteHello.
ReplyDeleteThank you for your tutorial, it helps me a lot.
But I'm facing the problem of signing in. I entered the correct username and password but it still showed the error(email and password does not exist).
I am a beginner, so please guide me. Thank you again.
Hello Nabelle,
Deleteit's not enough to get your error, may be credentials are actually wrong or try to echo sql queries which is used to login, hence it is working code
This comment has been removed by the author.
ReplyDeleteHi!
ReplyDeletethanks for sharing the code, I tested in a localhost and works deluxe but changed to a productive server and send me error 500 my response headers are:
Connection - closed;
accept - */*;
content-type application/x-www-form-urlencoded; charset utf-8;
X-Requested-With XMLHttpRequest
I hope someone can help me. thanks
hi,
ReplyDeletethanks for the tutorial.
i have a problem at if(response=="ok"){...
this just won't get executed.
else{} part of the code works, if info is wrong but if it's ok nothing happens.
i've tried removing the if statement and just put in alert(response) to see
if something will happen, and the alert box does appear correctly for inputting correct and wrong information .
why doesn't the if(...) part work?
php file is ok.
thanks for your help.
hello there,
Deleteit's working code i have tested it, did you make some changes in this script after downloading ...?
change echo ok with echo 1
Deletechange response==ok with response==1
now it works
u ve used mysqli pdo.. can i use only mysql ?? Is it safe to use mysql ?? for mysql what changes i need to do ??
ReplyDeletehi lonee, i have used here only PDO query not MySQLi and it is recommended to use b'coz mysql extensions are now deprecated, so switch-over from mysql to mysqli or pdo, i recommend you to use pdo cause it is safe to use.
Deletei m totally new to pdo .. can u provide me some basic tutorial link .. That ll be a great help :)
ReplyDeletestill get this error message "email or password does not exist." . Please help , how to solve it .
ReplyDeletemay by your database does'nt encrypt with md5
Deletetry to below in login_process.php
//$password = md5($user_password);
$password =$user_password;
you are removing password encryption which is unsafe, md5 shouldnt be used any longer as is easily hacked, crypt() should now be used and is included in php from 5.3 >
DeleteThanks , you are right
Deleteshouldnt be using md5 these days, totally insecure, the crypt() function is miles better and future proof
DeleteHi sir. Thank you so much for this tutorial, but I've got some questions. I have like 3 usertypes in my website: superadmin, admin, member. And I've separted them in different folders. So for instance I have my folder named "Sample" and inside that folder I have SuperAdmin, Admin, Member. How can I have one login page or form for these different users? Btw, my login is in my sample/index.php . I really hope you can help me. Thank you!
ReplyDeleteWith an if statement you can achieve that, you redirect them to the respective page after checking their role, which you have to add to your database
DeleteThanks for sharing this helpful article,
ReplyDeleteAngularJS development Company
The "Sign In" button gets stuck on "sending..." and doesn't ever log in (but also does not return an error). Anyone know what's going on?
ReplyDeletehow do I download this code for mac? there is no application available to open it. I have already tried simply typing out the code on this page but there seems to be A LOT of errors.
ReplyDeleteI finally got this working but I am also having the problem with the email and password not existing? Does anyone know how to fix this?
ReplyDeleteHi! Your tutorial was really helpful, thank you for it!
ReplyDeleteBut I have a problem. I created registration and login functionality and it works. When I login and refresh the page ones it works fine. But when I click on some link or refresh for second time, it automaticaly log me out. I guess session expires somehow but I don't know how to fix it at this point and I would be happy for some help.
Thank you very much!
Great Helpful, I have created another login form using Ajax, jQuery & PHP.
ReplyDeleteHere is demo of Ajax Login Form Using jQuery and PHP
Thank's
ReplyDeletei would revise using md5 as its easily subject to brute force, i would have a read here:
ReplyDeletehttp://php.net/manual/en/faq.passwords.php#faq.passwords.fasthash
In my case line 21 in login_process.php didn't work:
ReplyDeleteif($row['user_password']==$password){
...which I replaced it with:
if(strcmp($row['user_password'], $user_password) == 0){
I suspect it has with different versions of PHP.
Hope that will help someone...
Thx bro
DeleteHello, i have problem with "response", my "respone" is empty.
ReplyDeleteI try to remove the script and use manual action form, and "ok" show.
but when I use the script and use alert to show parameter response, and it still empty, need help pls..
SQLSTATE[HY000] [1049] Unknown database 'dbregistration'
ReplyDeleteNotice: Undefined variable: db_con in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php on line 16
Fatal error: Uncaught Error: Call to a member function prepare() on unknown in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php:16 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php on line 16
!
SQLSTATE[HY000] [1049] Unknown database 'dbregistration'
ReplyDeleteNotice: Undefined variable: db_con in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php on line 16
Fatal error: Uncaught Error: Call to a member function prepare() on unknown in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php:16 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php on line 16
!
Nice post
ReplyDeletethank you!
ReplyDeletethis is a great tutorial!
but, I got a question for you.
How could I read user data by using ajax jQuery?
How do you configure your server/code (I think is the server) so the session never expires and you are always logged in until you log out (like Facebook). In your demo that happens, but when I put it on mine it times out after a while and you have to login again
ReplyDeleteHow do you configure your server/code (I think is the server) so the session never expires and you are always logged in until you log out (like Facebook). In your demo that happens, but when I put it on mine it times out after a while and you have to login again
ReplyDeleteHow do you configure your server/code (I think is the server) so the session never expires and you are always logged in until you log out (like Facebook). In your demo that is what happens, but when I put it on mine it times out after a while and you have to login again
ReplyDeleteThank you for this tus. It help me more to do understand login logout with ajax sql :))
ReplyDeleteWorking fine out of the box. No errors. Implemented in a existing website. Be sure for every php file you have to add
ReplyDeletesession_start();
if(!isset($_SESSION['user_session']))
{
header("Location: index.php");
}
On top to make sure everything is protected.