Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Check Email Already Exists with jQuery Ajax

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 16.1k
    Comment on it

    While loginin website using email address many time you must have seen an error message say's Email already exists, So in this tutorial we will learn how to create a functionality in jQuerywhich checks if the email already exists and if yes then show the message. 

    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.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Check the Email if Already Exist </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-->
            <br />
            <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>
    

    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)

    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.");
                                    $("span.validation").html("");
                                    $("form input[type='text']").val(''); // optional: empty the field after registration
                                }
                            }
                        } // end success
            }); // ajax end
            /************** end: email exist function and etc. **************/
        }); // click end
    }); // jquery end
    

    Step 5: The Ajax Request File(check_email.php)

     

    <?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')");
      }
    
    ?>
    

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: