Registration Form using Ajax, PHP & MySQL

If you want to create a registration form that will not reload after submitting the registration details. Then you should make the ajax registration form with PHP & MySQL.

The Ajax Registration form is very useful to process the registered data quickly to the database without refreshing the web page. So. It is frequently used in most of web applications to make their registration form userfriendly & attractive.

In this tutorial, I have shared some simple steps to create the registration/signup form using jquery ajax in PHP & MySQL. Once you learn it you can create any type of other registration forms.

Steps to Create Ajax Registration Form with PHP & MySQL

Learn Also –

Ajax File Upload with PHP & MySQL

Check Username availability using ajax, PHP & MySQL

Check if an Email already exists in the Database using Ajax, PHP & MySQL

Now, Let’s start the coding to create the ajax registration form with the following simple steps –

1. Create Registration Form Directory Structure

First of all, You should create the following directory structure to build the registration form.

source-code/
    |__database.php
    |__ajax-script.php
    |__php-script.php
    |__index.php
    |

2. Create MySQL Table

Now, Create a MySQL Database –

Database Name – codingstatus

CREATE DATABASE codingstatus

After that create a table in the database ‘codingstatus’

Table Name – users

CREATE TABLE `users` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `firstName` varchar(50) DEFAULT NOT NULL,
 `lastName` int(50) DEFAULT NOT NULL,
 `gender` int(10) DEFAULT NOT NULL,
 `emailAddress` int(50) DEFAULT NOT NULL,
 `password` int(20) DEFAULT NOT NULL
);

3. Connect PHP to MySQL Database

Now, You have to connect PHP to the MySQL database with the following code

<?php

$hostname     = "localhost";
$username     = "root";
$password     = "";
$databasename = "codingstatus";
// Create connection
$conn = mysqli_connect($hostname, $username, $password, $databasename);

// Check connection
if (!$conn) {
    die("Unable to Connect database: " . mysqli_connect_error());
}
?>

4. Create a Registration Form UI

To create the registration form UI, You have to follow the following points –

  • Create a basic HTML structure
  • Include the bootstrap5 CDN
  • Create a form with id ‘registrationForm’
  • Also, create some input fields for firstName, lastName, gender, email & submit button.
  • Include the jQuery CDN
  • Include the ajax-script.js

File Name – index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-sm-4">

    <!--===== Registration Form ============-->
    <h3 class="mt-3 text-success text-center">Ajax Registration Form</h3>
    <p class="text-center" id="msg"></p>
    <form id="registrationForm" method="post">
      <div class="mb-3 mt-3">
        <input type="text" class="form-control" placeholder="First Name" name="firstName">
      </div>
      <div class="mb-3 mt-3">
          <input type="text" class="form-control" placeholder="Last Name" name="lastName">
      </div>
      <div class="mb-3 mt-3">
        <input type="radio" name="gender" value="male">Male
        <input type="radio" name="gender" value="female">Female

    </div>
      <div class="mb-3 mt-3">
          <input type="email" class="form-control" placeholder="Email Address" name="emailAddress">
        </div>
        <div class="mb-3 mt-3">
          <input type="password" class="form-control" placeholder="Password" name="password">
        </div>
        <div class="mb-3 mt-3">
          <input type="password" class="form-control" placeholder="Confirm Password" name="confirmPassword">
        </div>

      <button type="submit" class="btn btn-primary">Register Now</button>
    </form>
        <!--===== Registration Form ============-->

        </div>
        <div class="col-sm-8">

        </div>
    </div>
 
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="ajax-script.js"></script>
</body>
</html>

 

5. Write ajax code for Registration

Now, We have to write ajax code to process the user Input to the PHP script. So, create a ajax-script.php and write the jquery ajax code. This code will execute when the user submits the form after filling out their registration.

To write an ajax code for registration, you have to follow the following points –

  • Apply the submit event on the form id ‘registrationForm’
  • Define the e.preventDefault to prevent the form from the reloading
  • Implement the next steps within the $.ajax()
  • define the form method post
  • define the PHP file path – php-script.php
  • also, serialize the input data using serialize() method
  • define the success to get the  success response
  • display the success message in the id ‘msg’
  • After the registered successfully, make empty all the input fields.

File Name – ajax-script.js

$(document).on('submit','#registrationForm',function(e){
    e.preventDefault();
   
    $.ajax({
    method:"POST",
    url: "php-script.php",
    data:$(this).serialize(),
    success: function(data){
    $('#msg').html(data);
    $('#registrationForm').find('input').val('')

}});
});

 

6. Write PHP to Insert Registration Data

Now, We have to insert input data into the database, So, create a php-script.php file and write the php code with the MySQL query. The code of this file will run while the ajax code will be executed and sent the post request.

To insert registration data, you have to write PHP code with the following points-

  1. Include the database.php file
  2. and assign connection variable $conn to the $db
  3. Create a custom function registerUser() with two parameters $db and $userData.
  4. write a MySQLi query to insert data into the database,
  5. And then call the created function registerUser()

File Name – php-script.php

<?php

include_once("database.php");
$db = $conn;
define('tableName', 'users');
$userData = $_POST;

registerUser($db, $userData);

function registerUser($db, $userData) {

    $firstName      = $userData['firstName'];
    $lastName       = $userData['lastName'];
    $gender         = $userData['gender'];
    $emailAddress   = $userData['emailAddress'];
    $password       = $userData['password'];
    $confirmPassword = $userData['confirmPassword'];

    if(!empty($firstName) && !empty($lastName) && !empty($gender) && !empty($emailAddress) && !empty($password)){

       if($confirmPassword === $password) {
        $query = "INSERT INTO ". tableName;
        $query .= " (firstName, lastName, gender, emailAddress, password) ";

        $query .= "VALUES ('$firstName', '$lastName', '$gender', '$emailAddress', '$password')";
    
        $execute = $db->query($query);
        echo $db->error;
        if($execute) {
        echo "You are registered successfully";
        }
      } else{
        echo "Wrong Confirm password";
      }
   } else {
      echo "All Fields are required";
   }
}

 

7. Test Ajax Registration Form yourself

Now, You can text the ajax registration form by opening it in the web browser.

When you open the registration form will get the First Name, Last Name, gender, Email, Password & Confirm Password input fields.

After that Enter the required details and submit the form. after that, you will be registered successfully without reloading the web page.