Ajax Registration Script using jQuery with PHP and MySQL | Coding Cage

Ajax Registration Script using jQuery with PHP and MySQL

By
This tutorial will show you how to create Ajax Signup form with jQuery using PHP MySQL and PDO. this will also guide creating a simple registration form using BootStrap, in most of websites you might have seen a registration form which accepts data from users and store into MySQL database without page refresh, this tutorial will also cover an important jQuery Validation part, proper validation using jQuery and database connectivity using PHP, you can look at live demo and try it yourself from the given download link, let's take a look.
Ajax Registration Script using jQuery with PHP and MySQL


I have used Here BootStrap to create registration form with proper form validation using jQuery validation plugin, here we have a simple registration form which will force user to enter all the fields, it will check if users email is exists or not in the database then user will be signup with the message and redirected to the registration page.

Create the database table

Run the following SQL code on your PhpMyAdmin. This is to create our database table. By the way, the database name we have used in this tutorial was named “dbregistration″.

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`)
)

read also : Submit Form without Page Refresh using jQuery

dbconfig.php

simple database connection file, create new file and paste following code inside the file and save it as “dbconfig.php”

<?php


 $db_host = "localhost";
 $db_name = "dbregistration";
 $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

here is our simple registration page which accepts user name, email and password with joining date , it will check in users table that the user email is exists or not, if user email exists it will throw 1 no, and using jquery i have displayed error message in bootstrap alert.

<?php

 require_once 'dbconfig.php';

 if($_POST)
 {
  $user_name = $_POST['user_name'];
  $user_email = $_POST['user_email'];
  $user_password = $_POST['password'];
  $joining_date =date('Y-m-d H:i:s');
  
  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",$user_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();
  }
 }

?>

Let’s start

OK' we have covered our PHP part now it's time for jQuery Validation, Form Submit, BootStrap Form.
First of all we have to create simple HTML User Registration Form with four fields and they are username, useremail, password and retype password with proper jQuery Validation, yes i have used here jQuery form validation, we already have a tutorial about jQuery Form Validation, now let's start.

Registration Form Created with BootStrap

well we are using bootstrap over here it creates neat, clean and responsive interface, the form is below and to create it we have to add bootstrap css file just above the closing </head> tag
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
and the form is here...

<form class="form-signin" method="post" id="register-form">
      
        <h2 class="form-signin-heading">Sign Up</h2><hr />
        
        <div id="error">
        <!-- error will be showen here ! -->
        </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>

jQuery Registration Form Validation

after creating a form we must validate the form to prevent unacceptable data to avoid spam and to get authentic data from the users, to achive this add the following jQuery libraries within closing </head> tag
<script type="text/javascript" src="jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="validation.min.js"></script>
following validations accepts authentic data from the user, means it will force user to enter all the fields with proper data, email validation, password confirmation etc, we can set user defined message for all error, see below code, you can understand it easily.

$("#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: "please enter user name",
            password:{
                      required: "please provide a password",
                      minlength: "password at least have 8 characters"
                     },
            user_email: "please enter a valid email address",
   cpassword:{
      required: "please retype your password",
      equalTo: "password doesn't match !"
       }
       },
    submitHandler: submitForm 
       });

User Registration with jQuery Ajax without Page Refresh

after validation and getting data from the users, the following code will work without reloading the whole "index.php" page and registers a new user with Registration Successful message.

/* 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('<img src="btn-ajax-loader.gif" /> &nbsp; Signing Up ...');
         setTimeout('$(".form-signin").fadeOut(500, function(){ $(".signin-form").load("success.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 */

NOTE : we have to combine these two, validation and form submit part to work, create a new file and paste the above jquery code in this created file and save it as script.js

Script.js

combined jquery code validations and form submit script.js file contains jQuery Code both validation and form submission part, form was submitted using $.ajax() method which send form values to the register.php and returns data to the same page.

// JavaScript Document

$('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: "please enter user name",
            password:{
                      required: "please provide a password",
                      minlength: "password at least have 8 characters"
                     },
            user_email: "please enter a valid email address",
   cpassword:{
      required: "please retype your password",
      equalTo: "password doesn't match !"
       }
       },
    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('<img src="btn-ajax-loader.gif" /> &nbsp; Signing Up ...');
         setTimeout('$(".form-signin").fadeOut(500, function(){ $(".signin-form").load("success.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 */ 

});

index.php

here is our final code for index page contains html form with some jquery,bootstrap and some other necessary links.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration Form using jQuery Ajax and PHP MySQL</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> 
<script type="text/javascript" src="jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="validation.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">
        <!-- error will be showen here ! -->
        </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="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

that's it :)
we have covered here a simple user registration form created with jQuery Ajax using PHP MySQL using as usual PDO extension, we also covered creating a registration form using BootStrap with proper form validations, Hope you Like it,
feel free to ask queries related this tutorial, happy coding :)



34 comments:

  1. Nice article with great content and helpful information to know.Thanking you.

    ReplyDelete
    Replies
    1. you're welcome , pramod
      keep visiting :)

      Delete
    2. your links to demos is down buddy

      Delete
  2. Thank for your tutorial, I really appreciate your works. Keep up.
    :D

    ReplyDelete
  3. Hi, i cant download this script

    ReplyDelete
  4. Replies
    1. Hello Rahmat, download the code again.

      Delete
    2. Thanks for this tutorial!

      Delete
    3. you're welcome, prabal, glad you liked it.

      Delete
  5. hii there i got a error when i put this file to a test this code on my testperpose host.. SQLSTATE[28000] [1045] Access denied for user 'u136366017_users'@'10.1.2.14' (using password: NO) Fatal error: Call to a member function prepare() on a non-object in /home/u136366017/public_html/register.php on line 17 !

    ReplyDelete
    Replies
    1. Hello Saikat, make sure you have provided correct mysql details username,passwords,host,db given by your host provider.

      Delete
    2. Hi Pradeep Khodke,

      I have got the same problem. I'm sure I have provided correct mysql details: username, password, host and so on but it still gives me the same message.

      What's wrong?

      Any help would be welcome,

      Best regards.

      Delete
  6. fantastic tutorials! how do i redirect to login page after succesful register?

    ReplyDelete
  7. fantastic tutorials Pradeep! how do i redirect to login page after succesful registration?

    ReplyDelete
  8. thank you! how can i redirect after logging in? would like to take user to a landing page showing them authenticated in the top of page.

    ReplyDelete
  9. I've been trying to get this code to work, but it will not work for me, i tried running a test push to see if it'll imput the values into the mySQL and when i run the test script it just gives me a blank screen, doesn't post anything to mySQL

    test code i used:

    php

    require_once 'dbconfig.php';


    mysql_query("INSERT INTO users(user_name,user_email,user_password,joining_date) VALUES(test, test, test, test)")
    or die(mysql_error());

    when i run the script it just pops up a blank page

    any help?

    ReplyDelete
  10. How to validate and check available of email and username in database without refresh page?
    any idea?
    thanks.

    ReplyDelete
  11. I installed the files and made a table in my database. When i want to register the buttons says 'sending' and nothing happens

    ReplyDelete
  12. when i want to register the button keeps sending and nothing happens

    ReplyDelete
  13. Thank you for this tutorial, this really helped me a lot. But I just want ask what if I want to check both the user_name and user_email from the database already exists? How will I do it in script.js and register.php? I hope you can reply because I'm just new to ajax. Great tutorial btw!

    ReplyDelete
  14. hi, don't mind my previous question, i was able to do it. thanks so much for this tutorial!

    ReplyDelete
  15. Thank you so much. your script has really help me many project.

    ReplyDelete
  16. good information, but please can you tidy up the code. It's very ugly to look at.

    ReplyDelete
  17. Good tutorial, but may I know how can I connect the registration page to my homepage?

    ReplyDelete
  18. very nice tutorial i will use your tutorial to my learning. Great man.

    ReplyDelete
  19. great i can follow your tutorial for my mini project. thanks a lot developer.

    ReplyDelete