Email availability checking is not a difficult task in PHP if you are using Ajax. Yes, this is absolutely right. Using ajax and jQuery, we can check if email exists in the database while creating an account with email. That means the email that is going to be saved in the database is already exists. If yes, then it will not allow you to create the account with that email. But without using Ajax it is not possible to check without form refresh. So, here I am gonna show you the live email availability check. I’ve already shown you the form handling in PHP using Ajax.
Check If Email Exists in PHP
Before moving to the project, let’s see what I’ll cover in this post. I’m going to start with a new project in which I will create a basic registration form using the bootstrap. In that form, I will have some input fields for taking user inputs. When the user will enter the email address for creating a new account, an ajax request will go to the server. For the request handling of the server, I’ll use PHP. In the PHP script, it will check the email address from the database.
If the email address will exist already, then it will return with the error message. Otherwise, it will return with a success message that means the account can be created with that entered email. Also, we’ll learn some sort of form validation using the jQuery. So, let’s move to the project.
Create and Setup MySQL Database
Open phpMyAdmin and create a new database. I am creating a database named phpajaxdemo
.
CREATE DATABASE phpajaxdemo;
Then paste the below code for creating a new table in this database.
CREATE TABLE `registration` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(20) NOT NULL,
`created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
PHP File Upload Using jQuery and AJAX
Create Database Connection
In the project directory, create a new file named db-config.php
and paste the below code. Change your database username and password with the database name.
// db-config.php
<?php
class DBController {
private $hostname = "localhost";
private $username = "root";
private $password = "root";
private $dbname = "phpajaxdemo";
// creating connection
public function connect() {
$conn = new mysqli($this->hostname, $this->username, $this->password, $this->dbname) or die("Failed to connect" . $conn->error);
return $conn;
}
// closing connection
public function close($conn) {
$conn->close();
}
}
?>
After creating the database connection, we’ll create a basic registration form with some input fields.
Dependent Dropdown Filter in PHP Using Ajax
Create a Registration Form
So, create a new file named index.php
. Now, paste this code. I have used the bootstrap CDN for creating some sort of pretty design.
<!-- index.php -->
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<!-- bootstrap cdn -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5 pt-4">
<form method="post" id="regForm">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto shadow p-4">
<div class="form-group">
<label for="name"> Name <small class="text-danger">*</small></label>
<input type="text" name="name" id="name" class="form-control" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="email"> Email <small class="text-danger">*</small></label>
<input type="email" name="email" id="email" class="form-control" placeholder="Enter your email">
</div>
<div class="form-group">
<label for="password"> Password <small class="text-danger">*</small></label>
<input type="password" name="password" id="password" class="form-control" placeholder="Enter your password">
</div>
<div class="form-group">
<label for="c_password"> Confirm Password <small class="text-danger">*</small></label>
<input type="password" name="c_password" id="c_password" class="form-control" placeholder="Re-enter your password">
</div>
<div class="form-group">
<button type="button" id="savebtn" class="btn btn-success btn-md"> Submit </button>
</div>
<div id="result"> </div>
</div>
</div>
</form>
</div>
<!-- Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<!-- custom script js -->
<script type="text/javascript" src="./script.js"></script>
</body>
</html>
In the above code, I have created a simple form using the bootstrap. When you will run, it will look like this.
Drag and Drop Multiple File Upload in PHP Using Dropzone js
Form Validation Using jQuery
Create a script file with the name script.js
and paste the code there. Then include this script file in the index.php after the jQuery CDN.
// script.js
$(document).ready(function() {
// ------------- form validation -----------------
function validateForm() {
// removing span text before message
$("#error").remove();
// validating input if empty
if($("#name").val() == "") {
$("#name").after("<span id='error' class='text-danger'> Enter your name </span>");
return 0;
}
if($("#email").val() == "") {
$("#email").after("<span id='error' class='text-danger'> Enter your email </span>");
return 0;
}
if($("#password").val() == "") {
$("#password").after("<span id='error' class='text-danger'> Enter your password </span>");
return 0;
}
if($("#c_password").val() == "") {
$("#c_password").after("<span id='error' class='text-danger'> Re-enter your password </span>");
return 0;
}
if($("#password").val() !== $("#c_password").val()) {
$("#c_password").after("<span id='error' class='text-danger'> Password not confirmed </span>");
return 0;
}
return 1;
}
});
In the above code, I have created a function named validateForm() inside the jQuery ready function. So, when the form will load, this function will be executed. But, I will require to call this function on click of Submit button.
Now, paste this code before the validate() function. So, that the validate() function can be called after clicking the submit button.
// save button click function
$("#savebtn").click(function() {
// calling validate function
var response = validateForm();
// if form validation fails
if(response == 0) {
return;
}
});
When the response of validateForm() function will be 0 that means the form validation not succeeded. In that case, the next step, will not be executed and it will return the execution here. But if, the response is 1 that means the form validation has succeeded. In that case, I will send a POST request using the AJAX to the PHP server.
Implement jQuery DataTable in PHP MySQL
Send POST Request to PHP Using AJAX
So, after the above, if block (which is shown in the above code), I will send a POST request to PHP for submitting the form.
// getting all form data from input fields
var email = $("#email").val();
var name = $("#name").val();
var password = $("#password").val();
// sending ajax request
$.ajax({
url: './process.php', // sending ajax request to this url
type: 'post',
data: {
'name' : name,
'email': email,
'password' : password,
'save' : 1
},
// before ajax request
beforeSend: function() {
$("#result").html("<p class='text-success'> Please wait.. </p>");
},
// on success response
success:function(response) {
$("#result").html(response);
// reset form fields after submit
$("#regForm")[0].reset();
},
// error response
error:function(e) {
$("#result").html("Some error encountered.");
}
});
In the above code, the ajax request is going to the process.php
file. So, create a new file with this name in which the ajax request will be handled.
POST Request Handling By PHP
Once, the ajax will be sent, we will require to handle that request in PHP. Therefore, paste the below PHP script in the process.php
file.
<?php
// including config file
require_once('config/db-config.php');
// creating object of DBController class
$db = new DBController();
// calling connect function
$conn = $db->connect();
// check if request is post and action is save
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save']) && $_POST['save'] == 1) {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$save = $_POST['save'];
// encrypt password using md5
$password = md5($password);
// insert into table
$sql = "INSERT INTO student (name, email, password) VALUES ('$name', '$email', '$password') ";
$result = $conn->query($sql);
// return success response
if($result) {
echo "<div class='alert alert-success alert-dismissible'>
<button class='close' type='button' data-dismiss='alert'>×</button>
Registration has completed successfully.
</div>";
}
// return error response
else {
echo "<div class='alert alert-danger alert-dismissible'>
<button type='button' class='close' data-dismiss='alert'> × </button>
Whoops! some error encountered. Please try again.";
}
}
?>
Save and execute the project to see what will happen in the result.
In the result, you can see the record has been saved in the database.
Now, I will check if the email exists in the database then the same email won’t be stored here.
Send Ajax Request to Check If Email Exists
At this time, I will be sending another POST request to the server using the AJAX. This request will check if the email exists in the database which is going to be created. If yes, then it will return with the response message and will break the next iteration of the code. So, that the user won’t create the account with the existing email.
In this case, I will use the blur() event. This event is triggered when any element loses the focus. So, when you will be typing the email in the email input field and after focusing on the next input field, the event will be triggered.
// ------------------- [ Email blur function ] -----------------
$("#email").blur(function() {
var email = $('#email').val();
// if email field is null then return
if(email == "") {
return;
}
// send ajax request if email is not empty
$.ajax({
url: 'process.php',
type: 'post',
data: {
'email':email,
'email_check':1,
},
success:function(response) {
// clear span before error message
$("#email_error").remove();
// adding span after email textbox with error message
$("#email").after("<span id='email_error' class='text-danger'>"+response+"</span>");
},
error:function(e) {
$("#result").html("Something went wrong");
}
});
});
In the above code, I have sent the request on the same PHP page that is process.php
. But in the data, I have sent an extra key that is for email check.
Check If Email Exists in the Database
In the next step, move to the process.php and paste this code to check whether the email already exists or not.
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['email_check']) && $_POST['email_check'] == 1) {
// validate email
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sqlcheck = "SELECT email FROM registration WHERE email = '$email' ";
$checkResult = $conn->query($sqlcheck);
// check if email already taken
if($checkResult->num_rows > 0) {
echo "Sorry! email has already taken. Please try another.";
}
}
Here, in this code, I have created a SQL query to check whether the entered email exists in the database or not. If exists, then it will print the message which is defined here.
So, including the above code, the process.php
file will be this.
// process.php
<?php
require_once('config/db-config.php');
$db = new DBController();
$conn = $db->connect();
// check if email is already taken
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['email_check']) && $_POST['email_check'] == 1) {
// validate email
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sqlcheck = "SELECT email FROM registration WHERE email = '$email' ";
$checkResult = $conn->query($sqlcheck);
// check if email already taken
if($checkResult->num_rows > 0) {
echo "Sorry! email has already taken. Please try another.";
}
}
// save records into the database
elseif($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save']) && $_POST['save'] == 1) {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$save = $_POST['save'];
$password = md5($password);
// insert into table
$sql = "INSERT INTO registration (name, email, password) VALUES ('$name', '$email', '$password') ";
$result = $conn->query($sql);
if($result) {
echo "<div class='alert alert-success alert-dismissible'>
<button class='close' type='button' data-dismiss='alert'>×</button>
Registration has completed successfully.
</div>";
}
else {
echo "<div class='alert alert-danger alert-dismissible'>
<button type='button' class='close' data-dismiss='alert'> × </button>
Whoops! some error encountered. Please try again.";
}
}
?>
This is the full script of script.js
file.
$(document).ready(function() {
// form autocomplete off
$(":input").attr('autocomplete', 'off');
// remove box shadow from all text input
$(":input").css('box-shadow', 'none');
// save button click function
$("#savebtn").click(function() {
// calling validate function
var response = validateForm();
// if form validation fails
if(response == 0) {
return;
}
// getting all form data
var email = $("#email").val();
var name = $("#name").val();
var password = $("#password").val();
// sending ajax request
$.ajax({
url: './process.php',
type: 'post',
data: {
'name' : name,
'email': email,
'password' : password,
'save' : 1
},
// before ajax request
beforeSend: function() {
$("#result").html("<p class='text-success'> Please wait.. </p>");
},
// on success response
success:function(response) {
$("#result").html(response);
// reset form fields
$("#regForm")[0].reset();
},
// error response
error:function(e) {
$("#result").html("Some error encountered.");
}
});
});
// ------------- form validation -----------------
function validateForm() {
// removing span text before message
$("#error").remove();
// validating input if empty
if($("#name").val() == "") {
$("#name").after("<span id='error' class='text-danger'> Enter your name </span>");
return 0;
}
if($("#email").val() == "") {
$("#email").after("<span id='error' class='text-danger'> Enter your email </span>");
return 0;
}
if($("#password").val() == "") {
$("#password").after("<span id='error' class='text-danger'> Enter your password </span>");
return 0;
}
if($("#c_password").val() == "") {
$("#c_password").after("<span id='error' class='text-danger'> Re-enter your password </span>");
return 0;
}
if($("#password").val() !== $("#c_password").val()) {
$("#c_password").after("<span id='error' class='text-danger'> Password not confirmed </span>");
return 0;
}
return 1;
}
// ------------------- [ Email blur function ] -----------------
$("#email").blur(function() {
var email = $('#email').val();
// if email is empty then return
if(email == "") {
return;
}
// send ajax request if email is not empty
$.ajax({
url: 'process.php',
type: 'post',
data: {
'email':email,
'email_check':1,
},
success:function(response) {
// clear span before error message
$("#email_error").remove();
// adding span after email textbox with error message
$("#email").after("<span id='email_error' class='text-danger'>"+response+"</span>");
},
error:function(e) {
$("#result").html("Something went wrong");
}
});
});
// -----------[ Clear span after clicking on inputs] -----------
$("#name").keyup(function() {
$("#error").remove();
});
$("#email").keyup(function() {
$("#error").remove();
$("span").remove();
});
$("#password").keyup(function() {
$("#error").remove();
});
$("#c_password").keyup(function() {
$("#error").remove();
});
});
Now, save and execute the project to see the changes in the result.
Load Data From MySQL Database in PHP Using jQuery Ajax
Here, I have entered the same email which has previously created. But this time, It has shown us an error message that email has already taken. It won’t allow me to create the same email again.
Conclusion
Bingo! we have successfully completed the project to check if the email exists. This was a basic form and input to check the only email. Similarly, you can implement it for the more advanced level to check the username, name, and many other input fields as per your requirements. Hope this will help you for validating this kind of form using the jQuery. So stay tuned with us for more advanced tutorials. If you got any trouble related to any steps that have used above, then please let me know. I will keep in touch with you always.
nats says
hy thanks for the work
its saying whoops an error occurred
Umesh Rana says
Hey nats,
Re-check your code and make sure you are passing the correct values for which you have defined the fields inside the database. There will be an issue with the field mismatch while inserting the records.
staci says
hello! great work..
i have tried your code, but instead of email, i used username and it works perfect
but once i put other inputs of the form, it doesnt submit the form saying whoops….
can you please guide me here?
and can i use both email and username available together? if yes can u please guide me in it on how to do it?
thanks!!
Umesh Rana says
You have to apply blur event specific for the input like email or username based on the id, type, name, or class. It seems you applied on all the inputs that’s why it is not submitting without filling up the values.
staci says
hey, your code is not working…
its just giving an error whoops…
it doesnt submit the data to database.. please guide!!
theres no issue with the field mismatch while inserting the records.