Hi There,
In this tutorial you will learn how to check username availability with PHP/Mysql, Ajax and jQuery.
File Structure:
In this functionality after the user enters the username an ajax request will be sent to php to check the availability of username by comparing the user input with the database and returns the response based on the username availability.
Step1: Create Database connectio
create db.php and copy/paste below script
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=myinfo", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
myinfo.sql
Import below sql to your database.
-- phpMyAdmin SQL Dump
-- version 4.8.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 06, 2020 at 04:40 PM
-- Server version: 10.1.31-MariaDB
-- PHP Version: 7.2.4
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `myinfo`
--
-- --------------------------------------------------------
--
-- Table structure for table `user_master`
--
CREATE TABLE `user_master` (
`id` int(11) NOT NULL,
`username` varchar(60) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='my user info';
--
-- Dumping data for table `user_master`
--
INSERT INTO `user_master` (`id`, `username`, `created_at`) VALUES
(1, 'Stephen', NULL),
(2, 'Saravanan', NULL),
(3, 'Rishi', NULL);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `user_master`
--
ALTER TABLE `user_master`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `user_master`
--
ALTER TABLE `user_master`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Step2: Create User Availability Form.
create index.html and copy/paste below code to index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>www.sleepycoder.com | Check User Availability with PHP and jQuery</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js"></script>
<script src="ajax.js" type="text/javascript"></script>
<style type="text/css">
.label {
width: 100px;
text-align: right;
float: left;
padding-right: 10px;
}
#submit_form label.error,
.output {
color: #fb3a3a;
font-family: "Segoe UI";
font-size: 13px;
margin-top: -10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Check User Availability with PHP, Ajax and jQuery</h2>
<br />
<form action="#" id="submit_form" method="POST" enctype="application/x-www-form-urlencoded">
<div class="form-group">
<label for="dob">Enter Username:</label>
<input type="text" class="form-control" id="dob" placeholder="Enter Username" name="username" />
<div id="message" style="display: none;"></div>
</div>
<input type="submit" class="btn btn-primary" name="submit_btn" value="Submit" />
</form>
<div id="loading" style="display: none;">Checking availability...</div>
<br />
</div>
</div>
</div>
</body>
</html>
Step3:jQuery AJAX Handler For User Availability Check with validation
Create ajax.js and copy/paste below script to ajax.js
$("#loading").hide();
// When the browser is ready...
$(document).ready(function () {
// Setup form validation on the #signup element
$("#submit_form").validate({
// Specify the validation rules
rules: {
username: {
required: true,
},
},
// Specify the validation error messages
messages: {
username: {
required: "Please enter username",
},
},
submitHandler: function (form) {
$("#loading").show();
$.ajax({
type: "POST",
dataType: "JSON",
url: "check_username.php",
data: $("#submit_form").serialize(),
success: function (json_data) {
var msg = json_data.msg;
var flag = json_data.flag;
if (flag == 1) {
$("#loading").hide();
$("#message").html(msg).show();
$("#submit_form").trigger("reset");
} else {
$("#message").html(msg).show();
$("#submit_form").trigger("reset");
}
},
});
},
});
});
Step4: Write mysql query to check user availability.
create check_username.php and copy/paste below code.
<?php
require "db.php";
$username = $_POST['username'];
$check_username = $conn->prepare("SELECT * FROM user_master where username = :username");
$check_username->bindParam(":username", $username);
$check_username->execute();
if ($check_username->rowCount() > 0) {
header('Content-Type: application/json');
echo json_encode(["flag" => 1, 'msg' => "<font style='color:red;'>$username already taken</font>"]);
exit();
} else {
header('Content-Type: application/json');
echo json_encode(["flag" => 1, "msg" => "<font style='color:green;'>$username is available</font>"]);
exit();
}
?>
GitHub: Download Sourcecode
Comments
Post a Comment