Sunday, November 12, 2017

Live Username Availability Check using PHP, jQuery and AJAX

In this tutorial we are going to build Live Username Availability Check using PHP, JQuery and  AJAX. This is a most common and popular feature in most of the website. Mostly this feature is integrated in Login and Registration page.

In the Registration page, When user entered the desire username in username text field and just after that AJAX call will send the request to PHP page to get the availability status of username in MySQL database. The PHP page find the exact match in the database and returns the result message based on the username availability.
Our Script returns the below message based on username availability :
  1. When Username availability match found in database, it will return message "Username is available".
  2. When Username availability match not found in database, it will return message "Username is not available".
Live Username Availability Check using PHP, jQuery and  AJAX
Live Username Availability Check using PHP, jQuery and  AJAX

First Create "user" Database Table
CREATE TABLE `user` (
  `UID` int(3) NOT NULL,
  `USERNAME` varchar(100) NOT NULL,
  `EMAILID` varchar(100) NOT NULL,
  `PASSWORD` varchar(100) NOT NULL,
  `JOINDATE` varchar(100) NOT NULL
);

Once you have created the database table, Then insert the valid details in user table.

config.php
Consists of database configuration details to establish database connection.
<?php
/* DATABASE CONFIGURATION */
define('DB_SERVER', 'localhost');
define('DB_DATABASE', 'skptricksdemo');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');

?>

controller.php
Controller work is to control the flow of execution. Here when user completely enter the username and focus out of the username text field, Then JQuery script send request to "controller.php" page and it will process the request and return response to be displayed.
<?php
include("DAO.php");
if(isset($_POST["search-data"])){
 
 $searchVal = trim($_POST["search-data"]);
 $dao = new DAO();
 echo $dao->searchData($searchVal);
}

?>

DAO.php
This DAO class helps to establish the database connection and populate/fetch the records from MySQL database on AJAX call using JQuery. This DAO Class find the username availability in the MySQL database and send the result back to "controller.php" page.
<?php
include("config.php");
class DAO{
public function dbConnect(){
$dbhost = DB_SERVER; // set the hostname
$dbname = DB_DATABASE ; // set the database name
$dbuser = DB_USERNAME ; // set the mysql username
$dbpass = DB_PASSWORD;  // set the mysql password
try {
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); 
$dbConnection->exec("set names utf8");
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function searchData($searchVal){  
try {
$dbConnection = $this->dbConnect();
$stmt = $dbConnection->prepare("SELECT * FROM `user` WHERE `USERNAME` = :searchVal");   
$stmt->bindParam(':searchVal', $searchVal , PDO::PARAM_STR);   
$stmt->execute();
$Count = $stmt->rowCount(); 
//echo " Total Records Count : $Count .<br>" ;
$result ="" ;
if ($Count  > 0){    
$result = "Match Found" ;
}else{
$result = "Match Not Found" ;
}
return $result ;
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
} 
}
?>

index.php
This page consists of Jquery, AJAX, PHP and HTML code, which helps to fetch records form MySQL database when user enter the text in username text field.
  1. JQuery script helps to call liveUsernameSearch() function when user completely entered the username in text field and focus out of it.
  2. AJAX Code helps to fetch records from database and display the result in "index.php" page without page refresh.
<html>
<head>
<script src="jquery-3.2.1.min.js"></script>
<style>
#search-data{
padding: 10px;
border: solid 1px #BDC7D8; 
margin-bottom: 10px; 
display: inline;
width: 50%;
float:left;
 
}
#preloader-gif{ 
width:50px;
float:left;
margin-top:-6px;
display:none;
}
#search-box-container:after {
 content: ".";
 display: block;
 height: 0;
 clear: both;
 visibility: hidden;
}

</style>
<script>
$(document).ready(function() {
$('#search-data').blur(function(e) {
    var value = $(this).val();
    liveUsernameSearch(value);
         
});
});

function liveUsernameSearch(val){
 $('#preloader-gif').show(); 
 $.post('controller.php',{'search-data': val}, function(data){
   
  if(data == "Match Found")
     $('#search-result-container').html("<span style='color:green;font-weight:bold;'>Username is available</span>");
        else    
     $('#search-result-container').html("<span style='color:red;font-weight:bold;'>Username is not available</span>");
  $('#preloader-gif').hide();
 }).fail(function(xhr, ajaxOptions, thrownError) { //any errors?     
        alert(thrownError); //alert with HTTP error         
 });
}


</script>
</head>
<body>
<div style="width: 700px;margin:40px auto;">

<div id="search-box-container"  >
<label > LIVE Username availability check using AJAX : </label><br><br>
<input  type="text" id="search-data" name="searchData" placeholder="Enter your Username" autocomplete="off" />
<span id="preloader-gif"> <img src="preloader.gif" width="50px;" height="50px"/>  </span>
</div>

<div id="search-result-container" style="font-size:18px;padding:5px;width:200px; "></div>

</div>

</body>

</html>

No comments:

Post a Comment