How to Create Registration Form using Ajax in PHP - onlyxcodes

Thursday 14 October 2021

How to Create Registration Form using Ajax in PHP

In this tutorial, I will guide you how to create a registration form using jQuery, Ajax in PHP.


Creating a registration form using Ajax in PHP allows you to store users' data in the database without reloading the page. This enhances the user experience and makes the registration process more seamless.


The jQuery Ajax is a powerful combination approach that makes you to improve your PHP site sign-up form speed dynamically.


In this article, I have explained form validation with JavaScript before submitting the SignUp form request to the server and I have also explained how to communicate with PHP via the Ajax () method.


how to create registration form using ajax in php

Table Content

1. Database And Table Schema

2. Understanding the Basics of Ajax and PHP

3. Database Configuration

4. Create Registration Form

5. Implementing jQuery And Ajax Method

6. PHP Script

6. Test Application


Understanding the Basics of Ajax and PHP

Ajax, which stands for Asynchronous JavaScript and XML, is a technology that allows web pages to be updated asynchronously through the backend exchange of a tiny amount of data.


Form data processing is ideal for PHP, a server-side scripting language. With the combination of these technologies, we can produce a dynamic submission form that reacts instantly to user input.


Database And Table Schema

You need to create a database to hold the user's information. The database name in this project I have used ajax_registration_db, but you can use different name whatever you like.


To store user information, copy and paste the SQL code below into your PhpMyadmin after creating the 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 Configuration

This is the "dbconfig.php" file, which contains database settings with PDO extensions that are required to connect to the MySQL database successfully.


<?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

The index.php file is located here. This file has a bootstrap-based submission form. There are three fields on this form: username, email, and password, as well as a register button.


When a user clicks the Register button after filling out the form data, this form request will be transferred to a PHP file using jQuery and the Ajax procedure.


Look before closing the </form> tag a division tag is here. We'll apply jQuery and the Ajax methods to show the user registration success message in this tag.


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

Look the registration form show below this type.


how to create registration form using jquery ajax in php

Implementing jQuery And Ajax Method

You will 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 register 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.


Within the #message division tag, the success function displays the data register successfully message. The id property value of the div tag is #message.


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

Useful Guide:


The username text box's id attribute value is #txt_username. The val() method retrieves the value of the username text field using this attribute value.


The email text box's id attribute value is #txt_email. The val() method retrieves the value of the email text box using this property value.


The password text box's id attribute value is #txt_password. The val() method retrieves the value of the password text field using this property value.


After the registration procedure was completed, the reset() function was used to clear the form. The id attribute value of the form tag is #registration_form.


PHP Script

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


The bootstrap success box class contains the register successfully message, while the bootstrap alert box class contains the fail message.


The $_POST[] method is used to obtain the newusername, newemail, and newpassword ajax data properties.


<?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

I have already tested this application.


The output of the above registration example is as follows:


Filled data in the signup form.


ajax login form using jquery, php and mysql - registration and login form in php with validation

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


The message "register successfully" is displayed with a bootstrap success box - javascript ajax login

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


user data that was saved in the table once the registration procedure was completed.

Download Codes

No comments:

Post a Comment

Post Bottom Ad