Simple ajax php mysql login page

Simple ajax php mysql login page

This tutorial will explain you, how to create a Login Script using Ajax with PHP MySQL.
in this tutorial i am going to create a simple login form using php, mysql and ajax. in this tutorial i will explain you how to validate email and password.
after submitted login detail form values send to main php login page using ajax all the process will done without page refreshing.
you can download the script using download button, let’s start the coding.

Create database connection php file connection.php

<?php
//Database connection

$conn=mysqli_connect("localhost","root","") or die(mysqli_error($conn));
mysqli_select_db($conn, "admin") or die(mysqli_error($conn));


//Create table if not exist

mysqli_query("
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(25) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(255) NOT NULL,
  `lastlogin` datetime NOT NULL,
  PRIMARY KEY (`id`)
)");
?>

Now create login HTML page.

create a new file and save it as login.php with the following code, this is our main login page contains html user friendly login form which will accepts username, password and all kind of validation errors.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple ajax php mysql login page</title>
</head>
<body>
 <div class="panel-heading" id="login_msg"></div>
 <form method="post">
 <input type="text" id="uname" name="uname" class="form-control" placeholder="Your Username " /><br>
 <input type="password" id="pass" name="pass" class="form-control"  placeholder="Your Password" /><br>
 <input type="button" value="Login Now" name="login" class="btn btn-primary" onClick="login_validate()" />
 </form>
</body>
</html>

Java SCript code

JavaScript/jQuery code which is responsible to do all the things silently, first we check all kind of validation, after that call “authentication.php” through ajaxUrl_code and check username or password match within users table is ok then it will redirect to the index.php page, if not it will display appropriate message within “login_msg” div. this script is completed with proper validation, so use this code and enjoy.

<script>

var baseUrl = "http://www.phpkida.com/";


function login_validate()
{
    var uname=document.getElementById("uname").value;
    var pass=document.getElementById("pass").value;
    err="";
    if(uname=="" && pass=="")
    {
        err="Please enter username and password";
    }
    else if(uname=="" && pass!="")
    {
        err="Please enter username";
    }
    else if(uname!="" && pass=="")
    {
        err="Please enter password";
    }
    if(err!="")
    {
        document.getElementById("login_msg").style.color="red";
        document.getElementById("login_msg").innerHTML=err;
    }
    else
    {
           document.getElementById("login_msg").innerHTML="";
        
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            ajaxUrl_code = baseUrl+"authenticate.php?uname="+uname+"&pass="+pass;
            xmlhttp.onreadystatechange = function(){
                    if (xmlhttp.readyState == 4)
                    {
                        msg=xmlhttp.responseText;
                        if(msg=="Authentication Successfull")
                        {
                            document.getElementById("login_msg").style.color="green";
                            document.getElementById("login_msg").innerHTML=msg;
                            window.location=baseUrl;
                        }
                        else if(msg=="Authentication Failed")
                        {
                            document.getElementById("login_msg").style.color="red";
                            document.getElementById("login_msg").innerHTML=msg;
                        }
                    }
            }
            xmlhttp.open("GET", ajaxUrl_code, true);
            xmlhttp.send();
            

    }
    
}

</script>

Now create authenticate.php file.

This file contains only PHP code, this will verify username and password values in users table, this file will work silently at back-end and call via ajaxUrl_code using java script code. if the login was success it gives success message or if fails it will print error message according to values.

<?php
session_start();

require_once("connection.php");



if(isset($uname) && isset($pass))
{
    $uname=$_REQUEST["uname"];
    $pass=$_REQUEST["pass"];
    $pass=md5($pass);

    $sql="select * fro m users where username='$uname' and password='$pass'";
    $res=mysqli_query($conn, $sql) or die(mysqli_error($conn));
    $count=mysqli_num_rows($res);
    if($count>0)
    {
        $today=date("d M Y");
        mysqli_query($conn, "UPDATE `users` SET `lastlogin` = '$today' where username='$uname' and password='$pass'") or die(mysqli_error($conn));
        $_SESSION["uname"]=$uname;
        echo "Authentication Successful";
    }
    else
    {
        echo "Authentication Failed";
    }
}
?>

Now create index.php file.

After successfully login you will redirect on index page means your dashboard page with print welcome message your username and last login date.

<?php
require_once("connection.php");
session_start();
if(isset($_SESSION['uname'])) { 
    $uname=$_SESSION['uname'];    
}
else
{
    header('location:login.php');
    exit;
}

?>
<?php
    $sql="select username,lastlogin from users where username='$uname'";
    $lastlogin=mysqli_query($conn, $sql) or die(mysqli_error($conn));
    $lastloginfet=mysqli_fetch_assoc($lastlogin) or die(mysqli_error($conn));
?>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple ajax php mysql login page</title>
</head>
<body>
<?php echo "Welcome ".$lastloginfet['username']; echo "Last Login : ".$lastloginfet['lastlogin'];?>  
           

<a href="logout.php" class="btn btn-danger square-btn-adjust">Logout</a> </div>
        
</body>
</html>

Now create logout.php file.

so finaly we are creating code of logout script using php, this code execute when you will click on logout button is ok your session will be destroy and you logout successfully.

<?php
session_start();
session_destroy();
header("location:login.php");
?>

Click on Image and download Source Code of This Tutorial

Download source code of Simple ajax php mysql login page

I hope you like this Article. Share with your friends.

About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.