Ajax Registration Script Using JQuery with PHP and MySQL

In this tutorial, we will look on how to create a registration page using AJAX. We will be using ajax to call the backend in order to avoid page refresh and JQuery to minimize unnecessary validations.

Overview

To continue in this tutorial you will need to create the following files, copy and paste the codes in the respective files and save them in the same directory. The details and purpose of the respective files shall be discussed in later part of the tutorial.

  1. Index.php
  2. Dbconfig.php
  3. Register.php
  4. Script.js
  5. Style.css

After completion, our registration page should look pretty much like so :
Ajax Registration Script Using JQuery with PHP and MySQL

Database Schema

Create a database to store the details of the user. I will name mine “dbreg”. You can name anything you
like. After creating the database, add table to it.

You can use the codes below to add table named `tbl_users`.

MYSQL
123456789

CREATE TABLE IF NOT EXISTS `tbl_users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(25) NOT NULL,
`user_email` varchar(60) NOT NULL,
`user_password` varchar(255) NOT NULL,
`joining_date` datetime NOT NULL,
PRIMARY KEY (`user_id`)
)

Index.php

In this file, we have the code which renders the HTML form which is used by users to register themselves. When a user click on submit button after filling the form it will send all the data to JavaScript file where inputs are validated and send to backend via AJAX Post call.

HTML
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Tutorial-22</title>
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript"
src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js">
</script>
<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="signin-form">
<div class="container">
<form class="form-signin" method="post" id="register-form">
<h2 class="form-signin-heading">Sign Up</h2>
<hr />
<div id="error">
            </div>
<div class="form-group">
                <input type="text" class="form-control" placeholder="Username" name="user_name" id="user_name" />
            </div>
<div class="form-group">
                <input type="email" class="form-control" placeholder="Email address" name="user_email" id="user_email" />
                <span id="check-e"></span>
            </div>
<div class="form-group">
                <input type="password" class="form-control" placeholder="Password" name="password" id="password" />
            </div>
<div class="form-group">
                <input type="password" class="form-control" placeholder="Retype Password" name="cpassword" id="cpassword" />
            </div>
<hr />
<div class="form-group">
                <button type="submit" class="btn btn-default" name="btn-save" id="btn-submit">
                	<span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account
                </button>
            </div>
</form>
</div>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

Dbconfig.php

This file contains all the Database configuration that are needed to create a successful connection with the MySQL database.

PHP
1234567891011121314

<?php
$db_host = "localhost";
$db_name = "dbreg";
$db_user = "root";
$db_pass = "";

try{
    $db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
    $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
    echo $e->getMessage();
}
?>

Register.php

This file contains the code which takes the request sent from AJAX (POST method) to save the data in the database. First, it will read the $_POST variable for available data and they will be stored in local variables. Then, using PDO statements the data is stored in the database.

PHP
123456789101112131415161718192021222324252627282930313233343536373839404142

<?php
require_once 'dbconfig.php';

if($_POST)
{
    $user_name 		= mysql_real_escape_string($_POST['user_name']);
    $user_email 	= mysql_real_escape_string($_POST['user_email']);
    $user_password 	= mysql_real_escape_string($_POST['password']);
    $joining_date 	= date('Y-m-d H:i:s');
	
	//password_hash see : http://www.php.net/manual/en/function.password-hash.php
	$password 	= password_hash( $user_password, PASSWORD_BCRYPT, array('cost' => 11));
    try
    {
        $stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_email=:email");
        $stmt->execute(array(":email"=>$user_email));
        $count = $stmt->rowCount();
        if($count==0){
            $stmt = $db_con->prepare("INSERT INTO tbl_users(user_name,user_email,user_password,joining_date) VALUES(:uname, :email, :pass, :jdate)");
            $stmt->bindParam(":uname",$user_name);
            $stmt->bindParam(":email",$user_email);
            $stmt->bindParam(":pass",$password);
            $stmt->bindParam(":jdate",$joining_date);
            if($stmt->execute())
            {
                echo "registered";
            }
            else
            {
                echo "Query could not execute !";
            }
        }
        else{
            echo "1"; //  not available
        }
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }
}
?>

Script.js

This JavaScript file contains the validation for form data. In order to validate the data we will be using built-in JQuery validation library. Once the data passed through validation script it will make the AJAX call to send data to backend using method POST.

JQUERY
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283

$('document').ready(function()
{
    /* validation */
    $("#register-form").validate({
        rules:
        {
            user_name: {
                required: true,
                minlength: 3
            },
            password: {
                required: true,
                minlength: 8,
                maxlength: 15
            },
            cpassword: {
                required: true,
                equalTo: '#password'
            },
            user_email: {
                required: true,
                email: true
            },
        },
        messages:
        {
            user_name: "Enter a Valid Username",
            password:{
                required: "Provide a Password",
                minlength: "Password Needs To Be Minimum of 8 Characters"
            },
            user_email: "Enter a Valid Email",
            cpassword:{
                required: "Retype Your Password",
                equalTo: "Password Mismatch! Retype"
            }
        },
        submitHandler: submitForm
    });
    /* validation */
    /* form submit */
    function submitForm()
    {
        var data = $("#register-form").serialize();
        $.ajax({
            type : 'POST',
            url  : 'register.php',
            data : data,
            beforeSend: function()
            {
                $("#error").fadeOut();
                $("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; sending ...');
            },
            success :  function(data)
            {
                if(data==1){
                    $("#error").fadeIn(1000, function(){
                        $("#error").html('
<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; Sorry email already taken !</div>
');
                        $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account');
                    });
                }
                else if(data=="registered")
                {
                    $("#btn-submit").html('Signing Up');
                    setTimeout('$(".form-signin").fadeOut(500, function(){ $(".signin-form").load("successreg.php"); }); ',5000);
                }
                else{
                    $("#error").fadeIn(1000, function(){
                        $("#error").html('
<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+data+' !</div>
');
                        $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account');
                    });
                }
            }
        });
        return false;
    }
    /* form submit */
});

Style.css

The CSS codes are used to add some design to the registration form.

CSS
1234567891011121314151617181920212223242526272829303132333435363738394041424344

@charset "utf-8";
/* CSS Document */
body{
	background:#f1f9f9;
}
.form-signin {
    max-width: 500px;
    padding: 19px 29px 29px;
    margin: 0 auto;
	//margin-top:90px;
    background-color: #fff;
    border: 1px solid #e5e5e5;
    -webkit-border-radius: 5px;
       -moz-border-radius: 5px;
            border-radius: 5px;
    -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
       -moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
            box-shadow: 0 1px 2px rgba(0,0,0,.05);
	font-family:Tahoma, Geneva, sans-serif;
	color:#990000;
	font-weight:lighter;
}
.form-signin .form-signin-heading{
    color:#00A2D1;
}
.form-signin input[type="text"],
.form-signin input[type="password"],
.form-signin input[type="email"] {
    font-size: 16px;
    height: auto;
    padding: 7px 9px;
}
.signin-form
{
	//border:solid red 1px;
	margin-top:80px;
}
.navbar-brand{
	font-family:"Lucida Handwriting";
}
#btn-submit{
	height:45px;
}

Thank you for being with me till the end of the tutorial.I hope I was able to help you with the registration system. Feel free to share it with your friends and community. I would love to hear from you and any query you have in the comments.
Here is a post I would request you to check: User registration and login with email verification

Download
  • 24 Comments

    Add Comment
    • Bansari
      helloo... i want to validate a registration form using ajax in PHP that has all fields like firstname, lastname,email,date of birth,gender,role,hobby,profile pic,password,confirm password all are include in it.
    • Jack
      This does't work as intended. The submit button isnt linked to anything. Its also prone to Sql injections.
    • Partha
      Why the normal submit won't work once the validation passes.. I do not want to make a ajax submission, it does not goes with my script.
    • Mukesh singh
      When I submitted first time in the day any data to my database.its not inserting. Values...but given response in echo ...register ..after when I submitted next same values in database ..it's working.... hahaha ...any solution for this.....and it's open challenge....how to slove this problem...
    • Fawad
      waoooo nice thank you so much ......... nice web and script... :)
    • Pammy
      Thank you for giving me the necessary information
    • Irekrut
      its working but i tried adding more input and tried adding validation in script file but its working $("#register-form").validate({ rules: { user_name: { required: true, minlength: 3 }, password: { required: true, minlength: 8, maxlength: 15 }, cpassword: { required: true, equalTo: '#password' }, user_email: { required: true, email: true }, user_add: { required: true, minlenght: 5 }, user_lic: { required: true, minlenght: 5 }, user_con: { required: true, minlenght: 5 }, user_agen: { required: true, minlenght: 5 }, }, messages: { user_name: "Enter a Valid Username", user_add: "Enter a Valid Address", user_lic: "Enter a Valid License", user_con: "Enter a Valid Contact Number", user_agen: "Enter a Valid Agency Name", password:{ required: "Provide a Password", minlength: "Password Needs To Be Minimum of 8 Characters" }, user_email: "Enter a Valid Email", cpassword:{ required: "Retype Your Password", equalTo: "Password Mismatch! Retype" } }, submitHandler: submitForm });
    • Sanjeet Shukla
      how to validation showing in the registration page in lable, please explain the code process
    • Len
      jquery-2.2.0.min.js:4 XMLHttpRequest cannot load file:///C:/xampp/htdocs/registration/register.php. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. send @ jquery-2.2.0.min.js:4 this type of problem?can u help me what im going to do.
      • San Len
        it means you need to point to proper url "http://localhost/registration/register.php" not "file:///C:/xampp/htdocs/registration/register.php"
    • MUNEEB KHAN
      By the way great tutorial it's work for me as well...