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.
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.
read also : Submit Form without Page Refresh using jQuery
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.
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
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 :)
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> 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> 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> Sorry email already taken !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
else if(data=="registered")
{
$("#btn-submit").html('<img src="btn-ajax-loader.gif" /> 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> '+data+' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> 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> 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> Sorry email already taken !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
else if(data=="registered")
{
$("#btn-submit").html('<img src="btn-ajax-loader.gif" /> 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> '+data+' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> 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> 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 :)
Nice article with great content and helpful information to know.Thanking you.
ReplyDeleteyou're welcome , pramod
Deletekeep visiting :)
your links to demos is down buddy
Deletenice tutorial
ReplyDeleteThank you' Rahul :)
DeleteThank for your tutorial, I really appreciate your works. Keep up.
ReplyDelete:D
you're welcome Mohammad :)
DeleteHi, i cant download this script
ReplyDeleteHello Muneesh... get it from this link : download here
Deletehow to download?
ReplyDeleteHello Rahmat, download the code again.
DeleteThanks for this tutorial!
DeleteThanks a lot!
Deleteyou're welcome, prabal, glad you liked it.
Deletehii 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 !
ReplyDeleteHello Saikat, make sure you have provided correct mysql details username,passwords,host,db given by your host provider.
DeleteHi Pradeep Khodke,
DeleteI 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.
fantastic tutorials! how do i redirect to login page after succesful register?
ReplyDeletefantastic tutorials Pradeep! how do i redirect to login page after succesful registration?
ReplyDeletewp plugin Ajax login/registration bar free download from here.
ReplyDeletethank 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.
ReplyDeleteI'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
ReplyDeletetest 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?
How to validate and check available of email and username in database without refresh page?
ReplyDeleteany idea?
thanks.
I installed the files and made a table in my database. When i want to register the buttons says 'sending' and nothing happens
ReplyDeletewhen i want to register the button keeps sending and nothing happens
ReplyDeleteThank 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!
ReplyDeletehi, don't mind my previous question, i was able to do it. thanks so much for this tutorial!
ReplyDeletewhat about file uploading
ReplyDeleteThank you so much. your script has really help me many project.
ReplyDeleteLive Demo is not working
ReplyDeletegood information, but please can you tidy up the code. It's very ugly to look at.
ReplyDeleteGood tutorial, but may I know how can I connect the registration page to my homepage?
ReplyDeletevery nice tutorial i will use your tutorial to my learning. Great man.
ReplyDeletegreat i can follow your tutorial for my mini project. thanks a lot developer.
ReplyDeletekeeps sernding
ReplyDeleteit keeps sending
ReplyDelete