In registration form mostly in web 2.0, email address is required to register for each user. In registration form we need to check email address from the database using Ajax to avoid the email duplicates, and the form tell the user the email inputted is exist and we need to change the email address.

In this this tutorial, we create a simple registration form for the demo and we use jQuery Ajax to request the email to the database, if already exist.

Why to use Ajax?

We use Ajax instead of plain PHP, because Ajax can able to talk the database without reloading the browser. We can send the data from the registration form and post the data to the request file. Some sites use Ajax in the registration form to verify the user email or username exist.

Download Source

Preview

Check-the-Email-if-Already-Exist-preview

Step 1: Create a Database

First create a database named ’email_exists’ you can change if you want, and create a table named ‘users’ and fields.

CREATE TABLE `users` (
 `first_name` varchar(50) NOT NULL,
 `last_name` varchar(50) NOT NULL,
 `email` varchar(50) NOT NULL
);

Step 2: Create Database Connection

Create file name ‘database.php’ to connect from the mysql database we have assigning the database credentials, MySQL host, user, password and database name the ’email_exists’.

<?php $db = mysql_connect("localhost", "root", ""); // your host, user, password if(!$db) { echo mysql_error(); } $select_db = mysql_select_db("email_exists"); // database name if(!$select_db) { echo mysql_error(); } ?>

Step 3: Creating the Registration Page

Create a file name ‘index.php’ our form page or home page, in home page we have a registration form the user can input ‘first name’, ‘last name’ and ’email’ as our example in this tutorial, and also we need the validate the form using jQuery.

index.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check the Email if Already Exist | istockphp.com </title>
<link href="style/style.css" rel="stylesheet" type="text/css" media="all" /> <!--- include the css file -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script> <!--- include the live jquery library -->
<script type="text/javascript" src="js/script.js"></script> <!--- include the our jquery file -->
</head>

<body>


<div id="wrap"> <!--wrap start-->
    	


<h1>Check the Email if Already Exist</h1>




<form action="" method="post" id="mainform">

<table id="table_data">

<tr>

<td>First Name</td>


<td><input name="fname" type="text" size="30"></td>


<td><span class="fname_val validation"></span></td>

		</tr>


<tr>

<td>Last Name</td>


<td><input name="lname" type="text" size="30"></td>


<td><span class="lname_val validation"></span></td>

		</tr>


<tr>

<td>Email</td>


<td><input name="email" type="text" size="30"></td>


<td><span class="email_val validation"></span></td>

		</tr>


<tr>

<td>&nbsp;</td>


<td><input name="register" type="button" value="Register"> <span class="loading"></span></td>


<td></td>

		 </tr>

	</table>

	</form>

</div>


 <!--wrap end-->
</body>

Below the title tag we include the stylesheet the ‘style.css’ and the live jQuery script from google cdn, and lastly the jQuery script.

style.css

body {
	font-family: Arial, Helvetica, sans-serif;
	font-size:13px;
	color:#464646
}
h1 {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    margin-left: 25px;
}
p {
	margin:10px;
	padding:10px;
	color:#000000;
}
table#table_data {
	margin-left: 25px;
}
form#mainform input[type="text"] {
    border: 1px solid #E5E5E5;
    margin-bottom: 3px;
    padding: 5px;
}
form#mainform input[name="register"] {
    border: 1px solid #BBBBBB;
    border-radius: 12px 12px 12px 12px;
    color: #464646;
    cursor: pointer;
    font-size: 13px;
    margin-top: 10px;
    padding: 3px 8px;
}
form#mainform input[name="register"]:hover {
    border: 1px solid #666666;

}
span.validation {
	font-style:italic;
	color:#B41F2B;
}
span.loading {
    font-style: italic;
    left: 5px;
    position: relative;
}

Step 4: Creating the jQuery Ajax Script

script.js

/*
	author: istockphp.com
*/
jQuery(function($) {
	var val_holder;

	$("form input[name='register']").click(function() { // triggred click

		/************** form validation **************/
		val_holder 		= 0;
		var fname 		= jQuery.trim($("form input[name='fname']").val()); // first name field
		var lname 		= jQuery.trim($("form input[name='lname']").val()); // last name field
		var email 		= jQuery.trim($("form input[name='email']").val()); // email field
		var email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // reg ex email check

		if(fname == "") {
			$("span.fname_val").html("This field is empty.");
		val_holder = 1;
		}
		if(lname == "") {
			$("span.lname_val").html("This field is empty.");
		val_holder = 1;
		}
		if(email == "") {
			$("span.email_val").html("This field is empty.");
		val_holder = 1;
		}
		if(email != "") {
			if(!email_regex.test(email)){ // if invalid email
				$("span.email_val").html("Your email is invalid.");
				val_holder = 1;
			}
		}
		if(val_holder == 1) {
			return false;
		}
		val_holder = 0;
		/************** form validation end **************/

		/************** start: email exist function and etc. **************/
		$("span.loading").html("<img src='images/ajax_fb_loader.gif'>");
		$("span.validation").html("");

		var datastring = 'fname='+ fname +'&lname='+ lname +'&email='+ email; // get data in the form manual
		//var datastring = $('form#mainform').serialize(); // or use serialize

		$.ajax({
					type: "POST", // type
					url: "check_email.php", // request file the 'check_email.php'
					data: datastring, // post the data
					success: function(responseText) { // get the response
						if(responseText == 1) { // if the response is 1
							$("span.email_val").html("<img src='images/invalid.png'> Email are already exist.");
							$("span.loading").html("");
						} else { // else blank response
							if(responseText == "") {
								$("span.loading").html("<img src='images/correct.png'> You are registred. redirecting...");
								$("span.validation").html("");
								$("form input[type='text']").val(''); // optional: empty the field after registration

								setTimeout(function(){ // deley

								window.location = 'step-2.php?email='+email; // redirect

								},1500); // 1,5 sec
							}
						}
					} // end success
		}); // ajax end
		/************** end: email exist function and etc. **************/
	}); // click end
}); // jquery end

In the jQuery script we create the simple validation form first for user fails to input the data. In the Ajax there are 4 parameters… type, url, data and return success.

Step 5: The Ajax Request File

<?php require_once("database.php"); // require the db connection /* catch the post data from ajax */ $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $query = mysql_query("SELECT `email` FROM `users` WHERE `email` = '$email'"); if(mysql_num_rows($query) == 1) { // if return 1, email exist. echo '1'; } else { // else not, insert to the table $query = mysql_query("INSERT INTO `users` (`first_name` ,`last_name` ,`email`) VALUES ('$fname', '$lname', '$email')"); } ?>

We connect to mysql database first then, after sending the data via Ajax, we catch the post data and process to the MySQL query and send back a request and Ajax catch again the request.

Step 6: Step page template

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check the Email if Already Exist | istockphp.com </title>
<link href="style/style.css" rel="stylesheet" type="text/css" media="all" /> <!--- include the css file -->
</head>

<body>

<div id="wrap"> <!--wrap start-->

<h1>Step 2 or Home page</h1>

		<b>Registered:</b> <?php echo $_GET['email']; ?>
		Modify if you want.....
	</div>

	 <!--wrap end-->
</body>
</html>

After successfully registered, we will be redirect to this page, the Next page or Home page, you can modify the process registration if you want .

Done

Were done, we creating the check email exist using jQuery Ajax. Let’s have a look at what we’ve achieved:

  • We’ve set up a mysql database.
  • We’ve create a simple form registration form.
  • We’ve write the jQuery Ajax script to able to talk the database without reloading the broswer.
  • We’ve write the request file from jQuery Ajax, to get the response of PHP script.

If you enjoyed this article, please consider sharing it!