Create Registration Form with Ajax PHP jQuery - onlyxcodes

Thursday 16 May 2024

Create Registration Form with Ajax PHP jQuery

Hi, In this tutorial I will show how to create a registration form with Ajax PHP and jQuery and I have also covered form validation with JavaScript before submitting the form request to the server,


Sign-up forms are a common task for online applications. They allow you to gather user information, manage access, and create personalized experiences.


By removing the need for page reloads, using AJAX with PHP to create submission forms provides a smooth and effective user experience. Users are less dissatisfied and are kept engaged by this seamless connection.


This tutorial is much simpler; it describes everything in-depth, especially the Ajax codes.


Create Registration Form with Ajax PHP jQuery

Table Content

1. Create Database and Table

2. Database Connection

3. Create Registration Form

4. Implementing Ajax and jQuery Code

5. Implementing Server code

6. Test Application


Create Database And Table

In this example, I used "ajax_registration_db" named database, but you can assign a different name whatever you like and I created a user table within this database.


CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Database Connection

This is the "dbconfig.php" file, in this file I have set up the MySQL database connection with PDO extensions.


<?php

$db_host="localhost"; 
$db_user="root";	
$db_password="";	
$db_name="ajax_registration_db";	

try
{
	$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
	$e->getMessage();
}

?>

Create Registration Form

This is the "index.php" file, and I used the Bootstrap package to create a registration form in it. I have three fields in this form: password, email, and username, and also a submit button.


<form id="registraion_form" class="form-horizontal">
					
	<div class="form-group">
	<label class="col-sm-3 control-label">Username</label>
	<div class="col-sm-6">
	<input type="text" id="txt_username" class="form-control" placeholder="enter username" />
	</div>
	</div>
				
	<div class="form-group">
	<label class="col-sm-3 control-label">Email</label>
	<div class="col-sm-6">
	<input type="text" id="txt_email" class="form-control" placeholder="enter email" />
	</div>
	</div>
				
	<div class="form-group">
	<label class="col-sm-3 control-label">Password</label>
	<div class="col-sm-6">
	<input type="password" id="txt_password" class="form-control" placeholder="enter password" />
	</div>
	</div>
				
	<div class="form-group">
	<div class="col-sm-offset-3 col-sm-6 m-t-15">
	<button type="submit" id="btn_register" class="btn btn-success">Register</button>
	</div>
	</div>
				
	<div class="form-group">
		<div id="message" class="col-sm-offset-3 col-sm-6 m-t-15"></div>
	</div>
			
</form>

Sign-up form UI:


create registration form using bootstrap package

Implementing Ajax and jQuery Code

We'll need the jQuery library before we go into the Ajax programming. Look, I've already added this library to the combination.


To register new user records, we will send the above registration form request using the jQuery Ajax code below.


The click() method caused and triggered a button click event when the users hit the submit button. The id attribute value of the register button is #btn_register.


The JavaScript checks the form validation before continuing to the $.ajax() method.


The JavaScript validation check ensures that no fields are left blank. Usernames must be typed in alphabetical order, emails must be in a proper format, and passwords must be at least six characters long.


The $.ajax() function is then called if no JavaScript validation is performed. This function's responsibility is to use the HTTP POST method to send a form request to the process.php file and obtain a response from the server without reloading the page.


<script src="js/jquery-1.12.4-jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
	
<script>
	
	$(document).on('click','#btn_register',function(e){
		
		e.preventDefault();
			
		var username = $('#txt_username').val();
		var email 	 = $('#txt_email').val();
		var password = $('#txt_password').val();
			
		var atpos  = email.indexOf('@');
		var dotpos = email.lastIndexOf('.com');
			
		if(username == ''){ // check username not empty
			alert('please enter username !!'); 
		}
		else if(!/^[a-z A-Z]+$/.test(username)){ // check username allowed capital and small letters 
			alert('username only capital and small letters are allowed !!'); 
		}
		else if(email == ''){ //check email not empty
			alert('please enter email address !!'); 
		}
		else if(atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length){ //check valid email format
			alert('please enter valid email address !!'); 
		}
		else if(password == ''){ //check password not empty
			alert('please enter password !!'); 
		}
		else if(password.length < 6){ //check password value length six 
			alert('password must be 6 !!');
		} 
		else{			
			$.ajax({
				url: 'process.php',
				type: 'post',
				data: 
					{newusername:username, 
					 newemail:email, 
					 newpassword:password
					},
				success: function(response){
					$('#message').html(response);
				}
			});
				
			$('#registraion_form')[0].reset();
		}
	});

</script>

My Guide:


The username text box's id attribute value is #txt_username and I used the val() method to retrieve the value of the username text field. 


The email text box's id attribute value is #txt_email and I used the val() method to retrieve the value of the email text box.


The password text box's id attribute value is #txt_password and I used the val() method to retrieve the value of the password text field.


I have used the reset() function to clear the form data after the sign-up process is complete.


Implementing Server Code

This is the "process.php" file, which communicates via the $.ajax() method and is responsible for silently registering new user data into the user table on the back-end using PHP PDO code and successfully relaying the register successful message.


<?php

require_once "dbconfig.php";

if(isset($_POST["newusername"]) && isset($_POST["newemail"]) && isset($_POST["newpassword"]))
{	
	$username = $_POST["newusername"];

	$email = $_POST["newemail"];

	$password = $_POST["newpassword"];
	
	$stmt=$db->prepare("INSERT INTO tbl_user(username,
											 email, 
											 password)
										VALUES
										    (:uname,
											 :uemail,
											 :upassword)"); 
	
		
	$stmt->bindParam(":uname",$username);
	$stmt->bindParam(":uemail",$email);
	$stmt->bindParam(":upassword",$password);
		 		
	if($stmt->execute())
	{
		echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">&times;</button> 
					Register Successfully  
			 </div>';		
	}	
	else
	{
		echo  '<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">&times;</button> 
					Fail to Register  
			   </div>';		
	}
}

?>

Test Application

The output of the above registration example is as follows:


Filled data in the registration form.


enter username, email and password data in the registration form.

The message "register successfully" is displayed with a bootstrap success box.


The message register successfully is displayed with a bootstrap success box

Look at the user data that is also saved in the table once the registration method is completed.


Look at the user data that is also saved in the table once the registration procedure is completed.

Download Codes

No comments:

Post a Comment

Post Bottom Ad