Friendly AJAX Login Form to be built should have clear aspects such as secure authentication, session control, last-login-time display and so on. Therefore, service providing system can separate existing members from guests, and then help members navigate websites to get what they are looking for.
Creating an AJAX Login Form using jQuery primarily involves both client-site jQuery and server-site PHP scripts, although HTM and CSS are also considered important while designing screen layout.
All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.
Estimated reading time: 9 minutes
EXPLORE THIS ARTICLE
TABLE OF CONTENTS
BONUS
Source Code Download
We have released it under the MIT license, so feel free to use it in your own project or your school homework.
Download Guideline
- Prepare HTTP server such as XAMPP or WAMP in your windows environment.
- Download and unzip into a folder that http server can access.
STEP 1
Authenticate Users
When users complete input, AJAX Login Form have to verify format of input data before sending it out. Once login attemption reaches a website for approval, we need to verify format again, and subsequently connect to database for authentication.
AJAX Login Form – DATA FORMAT CHECKING
function verify(d) {
error="";
// name
if (d.name=="") error += "Your name is required\n";
// email
if (d.email!=undefined) {
var pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!pattern.test(d.email.toLowerCase()))
error += "Please enter a valid email\n";
}
// password
if (d.cpass!=undefined)
if (d.pass.length<6) error += "Passwords must be at least 6 characters\n";
else if (d.pass.length<6 || d.cpass.length<6)
error += "Passwords must be at least 6 characters\n";
else if (d.pass != d.cpass)
error += "Passwords do not match\n";
// report errors
if (error!="") { console.log(error); alert(error); return false; }
else return true;
}
Basic checking here such as non-emtpy name, valid email format, password length limit, and exact likeness of two passwords seems trivial, however, it can reduce website efforts upon nonsense data and also save internet traffic.
AJAX Login Form – USER AUTHENTICATION
function actionLogin ($d) {
global $dbconfig, $tblname;
$error = "";
/* database */
$db = new DB($dbconfig);
$sql = "SELECT * FROM {$tblname} WHERE name=? ";
$stmt = $db->fetch($sql, [$d['name']]);
if($stmt['pass']!=$d['pass'])
$error .= "svr-Password not correct".PHP_EOL;
else if($stmt['emailchk']!='Y')
$error .= "your email not verified".PHP_EOL;
else {
$lastlogin = $stmt['login'];
$sql = "UPDATE {$tblname} SET login=? WHERE name=? ";
$db->execute($sql,[date('Y-m-d H:i:s'), $d['name']]);
if ($db->error != "")
$error .= $db->error . PHP_EOL;
else
$_SESSION['user'] = [ 'name' => $d['name'], 'lastlogin' => $lastlogin, 'login' => date('Y-m-d H:i:s') ];
}
/* response */
echo json_encode([
"sts" => $error=="" ? "succ" : "fail",
"err" => $error
]);
}
We locate all server-site PHP scripts under a specific directory ctrl, in which you can find ctrl-login.php and others. When password is the same as that in database, and email has been verified with a email confirmation link, user authentication has finished. Let us continue on STEP 2.
STEP 2
Record Login Information
On STEP 1, we have fetched one record for authentication from database through a DB Class. By now, recording user login data requires updating the record with simply the login time done in ctrl/ctrl-login.php. In addition, here we will write more about the helpful DB Class.
AJAX Login Form – TABLE SCHEMA
CREATE TABLE `a0002` (
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`emailchk` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Y or N',
`vcode` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'verification code',
`register` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`logout` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `a0002`
ADD PRIMARY KEY `name` (`name`),
ADD KEY `email` (`email`);
field | description |
---|---|
name | user name or identification |
user email address | |
pass | user password |
emailchk | “Y” means user email is verified, otherwise “N” |
vcode | verification code in the sending email |
register | date and time of registration |
login | date and time of login |
logout | date and time of logout |
AJAX Login Form – DB CLASS
It would be more elegant to perform CRUD (Create / Read / Update / Delete) on login data through an DB Object, instead to call PHP functions directly without encapulation. Although a very small DB Class as shown below is suggested, it will help you much. If you want to read more about it, the article Small PHP CRUD Class for OOP using MySQL will teach you for this topic.
<?php
/* A Simple DB Class
e.g.
$conf=array(
'host' => 'localhost',
'dbname' => 'mydb',
'username' => 'myuser',
'password' => '12345678',
'charset' => 'utf8',
);
*/
class DB {
private $conn = null;
public $error = "";
public $rowCount;
function __construct($conf) {
// initiate by connect to db
try {
$str = "mysql:host=" . $conf['host'] . ";dbname=" . $conf['dbname'] . ";charset=" . $conf['charset'];
$this->conn = new PDO($str, $conf['username'], $conf['password'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
]);
return true;
}
catch (Exception $ex) {
print_r($ex);
die();
}
}
function execute($sql, $params=null) {
// insert or update
try {
$stmt = $this->conn->prepare($sql);
$stmt->execute($params);
$this->rowCount = $stmt->rowCount();
return true;
}
catch (Exception $ex) {
$this->error = $ex->getMessage();
return false;
}
}
function fetchAll($sql, $params=null, $all=true) {
// select
try {
$stmt = $this->conn->prepare($sql);
$stmt->execute($params);
$this->rowCount = $stmt->rowCount();
if ($all)
return $stmt->fetchAll();
else
return $stmt->fetch();
}
catch (Exception $ex) {
$this->error = $ex->getMessage();
return false;
}
}
function fetch($sql, $params=null) {
// select
return $this->fetchAll($sql, $params, false);
}
} // DB class
?>
STEP 3
Establish A PHP Session
A session to be established will hold session data across browser and HTTP server, in other words, both side can access the shared data. While opening homepage before login, session control would redirect the user to login page.
On the other hand, if going to browser login page by a user already logged in, the system will switch him to homepage instead. That is a critical feature for session machanisim.
What is a PHP Session?
Refer to the definition from W3Schools.
AJAX Login Form – Session Control
/* start session */
session_start();
$_SESSION['user'] = [ 'name' => $d['name'], 'lastlogin' => $lastlogin, 'login' => date('Y-m-d H:i:s') ];
The script login.php include config.php to start a session. When successful authenticated, AJAX controller prepare session data $_SESSION such as user name name
, last login time lastlogin
, current login time login
to be shared with browser.
In Google Chrome, F12 Developer Tools or say Inspect can see PHP session id. While clicking F12, find menu Application on the top, and on the left panel, Storage > Cookies, then select an URL under it. At this time, all key-value pairs will display and you can get PHPSESSID from them.
A user attempting to navigate the homepage will be directed to a page such as AJAX Login Form in advance. Obviously this is a standard session control. Once he complete all checkings, a homepage will display to serve him.
However, under the established session, if he goes to AJAX Login Form accidentally, session control will kindly move him back to the homepage.
STEP 4
Display Login Information
Homepage usually shows something like service content part and user dara part. The user data may contain last login time and so on. It comes from session variables $_SESSION that we will write about here.
AJAX Login Form – SESSION VARIABLES
As mentioned in STEP 3, the login informatoin recorded in $_SESSION has data including last login time and login time. They can be shown on the top of screen layout. The last login time let users make sure whether he had come here at that time.
AJAX Login Form – LOGOUT
function actionLogout ($d) {
global $dbconfig;
$error = "";
/* duration */
$login=new DateTime($_SESSION['user']['login']);
$logout=new DateTime(date('Y-m-d H:i:s'));
$interval = $logout->diff($login);
//$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
$elapsed = $interval->format('%h hours %i minutes %s seconds');
/* database */
$db = new DB($dbconfig);
$sql = "UPDATE users SET logout=? WHERE name=? ";
$db->execute($sql,[date('Y-m-d H:i:s'), $d['name']]);
if ($db->error != "")
$error .= $db->error . PHP_EOL;
else
unset($_SESSION['user']);
/* response */
echo json_encode([
"sts" => $error=="" ? "succ" : "fail",
"err" => $error,
"msg" => "login duration: ".$elapsed
]);
}
STEP 5
Logout With Lapse Of Time
Table schema contains timestamps for login and logout in the last session. A friendly prompt let users know the time spent on this website.
AJAX Login Form – CLEAR SESSION VARIABLES
When clearing session with related variables and stopping navigation by the codes of unset($_SESSION['user'])
in ctrl/ctrl-login.php, the user will move from homepage to login page.
AJAX Login Form – FLOW CONTROL
/* general */
var ajaxsvr = {
"signUp" : "ctrl/ctrl-register.php",
"signIn" : "ctrl/ctrl-login.php",
"signOut" : "ctrl/ctrl-login.php",
}
var nextstep = { // for success
"signUp":"login.php",
"signIn":"index.php",
"signOut":"login.php",
};
function verify(d) {
error="";
// name
if (d.name=="") error += "Your name is required\n";
// email
if (d.email!=undefined) {
var pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!pattern.test(d.email.toLowerCase()))
error += "Please enter a valid email\n";
}
// password
if (d.cpass!=undefined)
if (d.pass.length<6) error += "Passwords must be at least 6 characters\n";
else if (d.pass.length<6 || d.cpass.length<6)
error += "Passwords must be at least 6 characters\n";
else if (d.pass != d.cpass)
error += "Passwords do not match\n";
// report errors
if (error!="") { console.log(error); alert(error); return false; }
else return true;
}
function sendout(act,d) {
console.log(act);
console.log(d);
$.post( ajaxsvr[act],
{
action:act,
data:d,
},
function(r) {
console.log("recv:"+r);
ret = JSON.parse(r);
if(ret.sts=="succ") {
if (ret.msg!=undefined) alert(ret.msg);
window.location.href = nextstep[act]+"?from="+act;
} else
alert(ret.err);
}
);
}
FINAL
Conclusion
Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!
Suggested Reading
- How Cordova Geolocation Locate Google Map in APP
- Small PHP CRUD Class for OOP using MySQL
- How Cordova Session Data Check If Already Login
TRY IT
Quick Experience
That’s all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.
Try It Yourself
Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.
I am actually pleased to glance at this blog posts which contains tons of valuable data, thanks for providing such
information.
Hope this article helps you well.
Ahaa, its fastidious conversation regarding this paragraph
here at this web site, I have read all that, so now me also commenting here.
This info is priceless. Where can I find out more?
Spot on with this write-up, I really believe that this web site needs a
lot more attention. I’ll probably be back again to see
more, thanks for the information!
You could certainly see your enthusiasm in the article you write.
The world hopes for more passionate writers like you who are not
afraid to mention how they believe. All the time follow your heart.