PHP Login Form Using Ajax and Jquery Validation


This tutorial is about the login form submission verifying the login details from mysql database. Here we are using Ajax method to pass the form parameters to php file which will execute a php function to check if the login details are valid or not.

We will be working with the following list of file structure for login user functionality.
  • login.php - Includes HTML login form.
  • connect.php - Handles the database connection to MySQL database.
  • post.php - File to excute a login user functionality and return the response to the submitted request.
  • style.css - Handles the form design.
  • script.js - Includes Jquery function to fetch the form data submitted through Ajax to the php post.php file.

Following the steps lets go through each file.

First lets create a database wdl_database. After creating the database lets add the wd_users table to the database.

1) MySQL query to create a database.

				CREATE DATABASE wdl_database;
		

2) MySQL query to add wd_users table to the database. I have also added one user entry to the wd_users table with fields userID(PRIMARY KEY), name, email(username), phone and password(admin@123).

				CREATE TABLE IF NOT EXISTS wd_users (
						userID int(11) NOT NULL,
						name varchar(255) NOT NULL,
						email text NOT NULL,
						phone varchar(20) NOT NULL,
						password varchar(255) NOT NULL,
					) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;


				INSERT INTO wd_users (userID,  name, email, phone,  password, ) VALUES
				(1,  'John Doe', 'johndoe.sample@mail.com', '0123456879',  '38683e18eafaec324f316bd87e1420e6');

				ALTER TABLE wd_users
				ADD PRIMARY KEY (userID);

				ALTER TABLE wd_users
				MODIFY userID int(11) NOT NULL AUTO_INCREMENT;
		
		

3) Adding some classes to style.css


body{
	padding:0;
	font-family: Arial;
	background:#fff;
}

input[type="button"],input[type="submit"]{
	transition:0.5s all;
	-webkit-transition:0.5s all;
	-moz-transition:0.5s all;
	-o-transition:0.5s all;
	-ms-transition:0.5s all;
}

.error{color:red;margin-bottom:12px;clear:both;}

.clearfix{width:100%; height:5px; clear:both;}

.sign-in-wrapper{
	background:#f9f9f9;
}

.graphs {
	padding: 30px 0 50px;
}

.sign-in-form {
	max-width: 400px;
	margin:0 auto;
}

.sign-in-form input[type="submit"] {
	font-size: 16px;
	padding: 8px 0;
	width: 38%;
}
	
.sign-in-form-top{
	display: block;
	padding: 0 0 15px;
}

.sign-in-form-top h1{
	color:#000;
	margin:0;
	font-size:2em;
	font-weight:300;
	text-decoration:none;
	text-align:center;
}

.sign-in-form-top p a{
	color:#fff;
}

.sign-in-form-top p a:hover{
	text-decoration:none;
}

.sign-in-form-top p span{
	color:#8BC34A;
}

.signin {
    padding: 2em;
	position:relative;
	background: #b1e4c0;
}

.log-input:nth-child(1) {
    margin: 2em 0 0;
}

/* .log-input input.user {
    background: url(../images/user.png)no-repeat 8px 10px #fff;
} */

.log-input input[type="text"],.log-input input[type="password"] {
  font-size: 0.95em;
  padding:10px 0 10px 6px;
  width: 98%;
  color: #A8A8A8;
  outline: none;
  border: 1px solid #D3D3D3;
  border-radius: 0px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    -ms-border-radius: 0px;
    -o-border-radius: 0px;
  background: #FFFFFF;
  margin: 0em 0em 12px 0em;
  border-style: solid;
}


.sign-in-form input[type="submit"] {
	font-size: 17px;
    color: #fff;
    background: #01a185;
    border: none;
    padding: 10px 0;
    width: 45%;
    display: block;
    outline: none;
    border-radius: 0;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    -ms-border-radius: 0px;
    -o-border-radius: 0px;
    cursor: pointer;
    margin: 0.5em 0 0 27.5%;
}
.sign-in-form input[type="submit"]:hover {
	 background:#f3c500;
	 transition: 0.5s all;
  -webkit-transition: 0.5s all;
  -moz-transition: 0.5s all;
  -o-transition: 0.5s all;
}

.log-input-left {
  float: left;
  width: 90%;
}



/*Responsive form handling*/
@media (max-width: 568px){.sign-in-form {width: 90%;}}
@media (max-width: 480px){.sign-in-form {width: 90%;}}
@media (max-width: 360px){.sign-in-form {width: 90%;}}
@media (max-width: 320px){.sign-in-form {width: 90%;}}

4) In login.php we have a HTML for the form with fields username and password.

Under the head tag the list of files are included.

  • style.css - Hold the form design
  • jquery.min.js - Jquery lib file to excute JQuery
  • jquery.validate.min.js - For Jquery Form Validation
  • additional-methods.js - Addtional Rules for custom field validation
  • script.js - Includes form validation and Ajax request

The form is validated by identifying it's attribute id="frmLogin" as a jquery selector in javascript script.js file included in login.php

		
Php Simple Login Script Using Jquery Validation


























5) Javascript script.js includes a callback function "validate" to validate the form and process it for submission by forwarding it to Ajax function.

In validation rules parameters are checked for email and password. For email we have checked whether the email format is valid or not and password as a required field. If the form is validated and there are no errors, the form values are passed to the Ajax call which will forward the form values as parameters in request url to post.php file.

Note : Working with Ajax need a basic knowledge of Ajax function and its parameters.
var base_url = window.location.origin+'/user-login' ;

$(document).ready(function(){

	
$("#frmLogin").validate({
rules: {
		  email: {
				required: true,
				email:true
		  },
		  password:{
				required: true			
			},
        },
		  messages: {
		   email: {
                required: "Please Enter your email.",
				email: "Please Enter valid email."
            },
		    password: {
                required: "Please Enter Password"
            },
},
	submitHandler: function (form) { 
	$('input[type="submit"]').prop('disabled', true);
	$('#logBtn').before('
logo
'); var aUrl = base_url+"/post.php?xAction=loginUser&"+$('form#frmLogin').serialize(); $.ajax({ type: 'post', url: aUrl, success: function(data){ if(data.trim() == "LOGGED"){ $('form#frmLogin')[0].reset(); $('#logBtn').before('
Logging In.....
'); window.setTimeout(function(){window.location.href = base_url+"/login.php";}, 2000); }else if(data.trim() == "WRONG"){ $('.imgLoader').remove(); $('.saveMsg').remove(); $('#logBtn').before('
Please check your username and password.
'); $('input[type="submit"]').prop('disabled', false); } } }); return false; } }); });

6) In post.php request is received using post method followed by Ajax function.

We are using a switch case xAction to make a call to loginUser function. In loginUser function it checks for username and password in wd_users table by executing the select query, so if the login details are valid it will create user session as SITEUSERID,SITEUSERNAME and SITEUSEREMAIL.

In response if the login details are valid it will return $str as LOGGED which will allow an Ajax function to throw message whether the login details are correct or not.

<?php

function loginUser($email,$password){


	$password = md5($password); 
	$str = "ERR";

	$query = "SELECT * FROM wd_users WHERE email='".mysql_real_escape_string($email)."' AND password='".mysql_real_escape_string($password)."'";
	$results = mysql_query($query);

	if (mysql_numrows($results)) {
		$arr = mysql_fetch_array($results);
		$_SESSION['SITEUSERID'] = $arr['userID'];
		$_SESSION['SITEUSERNAME'] = $arr["name"];
		$_SESSION['SITEUSEREMAIL'] = $arr["email"];
		$str = "LOGGED";
	}else {
		$str = "WRONG";
	}
return $str;
}




if($_REQUEST["xAction"]){
	session_start();
	switch($_REQUEST["xAction"]){
	case "loginUser":
	include('connect.php');
	echo loginUser($_REQUEST["email"],$_REQUEST["password"]);
	break;

	}
}

?>