How to make Registration page with Email confirmation and Jquery Ajax PHP SQL



How to make Registration page with Email confirmation and Jquery Ajax PHP SQL



During registration, most websites require you to verify your email mostly to avoid spam and more other reasons
This is actually a good practice.
In this tutorial, am going to show how to make a Registration page with email confirmation and Jquery Ajax. Let’s get started
NB:
This tutorial assumes you already have basic knowledge of PHP, SQL, JavaScript and HTML
****This Article is for tutorial purposes ****
***Any bad practice were either mistakes, outdated or intentionally kept there!**

Step 1: Setup Database
First, we will need to setup our database.
If you already have a database and tables you can skip this step
Create a database, in this tutorial we’re using a database name “reg”
Copy and paste this SQL code;
CREATE TABLE users(
    id INT AUTO_INCREMENT PRIMARY key,
    name varchar(255),
    email varchar(255),
    verified varchar(255)
    )

Step 2: Create database connection file
Create a PHP file called database.php
Copy and paste the following;
<?php
//Database Details
$host="locathost";             //Database host (mostly localhost)
$dbuser="root";                // Database username
$dbpass="";                    //Database password
$dbname="reg";                 // Databasde name
 
$mysqli=new mysqli($host,$dbuser,$dbpass,$dbname);
if($mysqli->connect_error){
        exit("Error connecting to database");
}
?>
Save as database.php
Step 3: Create HTML registration page
Create a file register.html or whatever you’ll like to name it
Copy and paste the following;
<!DOCTYPE html>
<html>
<head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <!-- You can you your own style sheet instead of bootstrap -->
        <!-- Required Bootstrap Style Sheet -->
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
        <!--Required Jquery file -->
        <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
        <title>Registration | Mycodehive</title>
 
</head>
<body>
        <div class="container">
               <!-- Start Form code -->
               <form class="form-group">
                       <input type="text" id="name" placeholder="Name">
                       <input type="email" id="email" placeholder="Email">
                       <!-- Display Errors in div -->
                       <div id="display-error"></div>
                       <input type="submit" id="submitform" value="Register">
               </form>
               <!-- End Form code -->
 
               <!-- Jquery Ajax Code for form submission -->
               <script type="text/javascript">
              $(document).ready(function(){
                //When Submit button is clicked
              $('#submitform').click(function(e){
                  $("#submitform").attr("disabled","disabled");
                  $("#submitform").attr("value","Processing...");
                  e.preventDefault();
                  var email = $("#email").val();
                  var name = $("#name").val();
 
                  if(email=='' || name==''){
                    alert("All fields are Required");
                  }
                  else {
                  $.ajax({
 
                      type: "POST",
 
                      url: "sendemail.php",
 
                      cache: false,
                      
                      dataType: "json",
 
                      data: {
                          email:email,
                          name:name
                      },
 
                      success : function(data){
                         if (data.code == "200"){
                               $("#submitform").attr("value","Submitted");
                               alert("Verification Email sent, please check your mailbox");
 
                          } 
                          else {
                                       $("#submitform").removeAttr("disabled");
                                       $("#submitform").attr("value","Login");
                                       $("#display-error").html("<ul>"+data.msg+"</ul>");
                               $("#display-error").css("display","block");
 
                          }
                        
 
                      }
 
                  });
                }
 
 
              });
 
              });
               </script>
        </div>
</body>
</html>
Save the file any name you like.

Step 4: Backend PHP file
This is the Part that sends the email and registers the users partially
Create a file sendemail.php
Copy and paste the following;
<?php
//Send Email file
include'database.php';
 
if(isset($_POST['email'])){
        if(empty($_POST['email'])){
               $msg="<li>Email is required</li>";
        echo json_encode(['code'=>404, 'msg'=>$msg]);
        }
 
        if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
    $msg="<li>Invalid email format</li>";
    echo json_encode(['code'=>404, 'msg'=>$msg]);
}
        $address=mysqli_real_escape_string($_POST['email']);
 
$stmt = $mysqli->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->bind_param("s", $address);
    $stmt->execute();
    $result = $stmt->get_result();
    //check if user exists
    if($result->num_rows !== 0){ 
        $msg = "<li>Username / Email Already taken</li>"; 
        echo json_encode(['code'=>404, 'msg'=>$msg]); 
    }
    else {
    $put = $mysqli->prepare("INSERT INTO users (email) VALUES(?)");
    $put->bind_param("s", $address);
    $putresult = $put->execute();
    $id=$mysqli->insert_id;
 
 $iid=base64_encode(base64_encode($id));
 
    // Content
    $subject = 'Site Email Confirmation';
    $message = "Hey $name, \n
Please use the link below to confirm $address is yours ::: $siteurl/confirmemail.php?email=$iid \n
** You recieved this email because your email was used to signup on our site";
 
$oya=mail($address, $subject, $message);
    if(!$oya){
        $mgs="error";
        echo json_encode(['code'=>404, 'msg'=>$msg]);
    }
    else {
        $msg="successful";
        echo json_encode(['code'=>200, 'msg'=>$msg]);
    }
 
}
 
}
?>
SAVE THE FILE AS sendemail.php

Step 5: Confirm Email file
Create a file and name confirmemail.php
Copy and paste the following
<?php
//confirmemail.php
//used to confirm users email
//edit with care!
 
if(isset($_GET['email'])){
include'database.php';
$yes="yes";
$email=base64_decode(base64_decode(mysqli_real_escape_string($mysqli,$_GET['email'])));
$update= $mysqli->prepare("UPDATE users SET verified = ? WHERE id = ?");
  $update->bind_param("ss",$yes, $email);
  $update->execute();
  if($update){
        echo "<script>
        window.alert('Email confirmed! Click ok to redirect');
        //window.location.replace('Uncomment and replace this with the file to complete their registraion');
        </script>";
  }
 }
 ?>
Save file as confirmemail.php
And that’s all,
The rest lies to you
Create a file to for the user to complete the registration, or you can redirect them to the dashboard. However you please.
****This Article is for tutorial purposes ****
***Any bad practice were either mistakes, outdated or intentionally kept there!**




Comments