how to create a registration page using ajax and php

14/09/2021    By: christoper unum





Creating a Registration page is one of the first things you think of when you intend tobuild a web application. In this tutorial, we will be looking at how we can use this page to create accounts for users using PHP and AJAX. To keep things simple, we will be usingtext files to save and retrieve user information. Let's start by creating two PHP files index.php and register.php and a folder named database.


Now we add our HTML,  CSS, and JavaScript codes in our index.php file. 

HTML

In our Html code, we will be including input options for username, email, and password to be entered twice. 

<div class="forms-out">
  <div class="forms-in">
    <div id="registration-page">
      <h3>Sign Up</h3>
      
      Username <br />
      <input type="text" id="registration-user" maxlength="10"/><br />
      
      Email <br />
      <input type="email" id="registration-email" /><br />
     
      Password <br />
      <input type="password" id="registration-password" /><br />
       Confirm Password <br />
       
      <input type="password" id="registration-password2" /><br />
      <button id="register" onclick="register()">Sign Up</button>
    </div>

  </div>
</div>

After typing our code, our page will look like the image shown below


CSS

Now we add styles to our HTML code to improve the form

.forms-out {
margin0 auto;
font-family"Fira Sans"sans-serif;
padding15px 0;
}

.forms-in {
width93%;
margin0 auto;
colorwhite;
padding15px 0;
}

.forms-in div {
padding30px 20px;
max-width350px;
margin0 auto;
background#168ab8;
border-radius5px;
margin-bottom15px;
}

.forms-in h3 {
text-aligncenter;
}

.forms-in input {
bordernone;
width100%;
margin-bottom15px;
padding10px;
box-sizingborder-box;
border-radius3px;
}

.forms-in button {
bordernone;
padding7px 20px;
background#e8f8ff;
color#168ab8;
border-radius4px;
cursorpointer;
font-weightbold;
}

.forms-in button:hover {
opacity0.7;
}

.hide {
displaynone;
}

#forgot-password {
text-aligncenter;
font-size13px;
cursorpointer;
}

#forgot-password:hover {
opacity0.7;
}

Our page now looks like this


JAVASCRIPT

In our JavaScript code, we first use the register() function to get all the details from the form and validate them to make sure the information passed by user is complete and in the right format. Then we pass it over to the sendRegistrationDetails() function, thats where we pass the data to the backend using Ajax without refreshing the page. If want to learn more about ajax you can visit W3Schoolfor more details on how ot use ajax  connections.

function register(){
    const username = document.getElementById("registration-user").value.toLowerCase().trim();
    const email = document.getElementById("registration-email").value.toLowerCase();
    const password = document.getElementById("registration-password").value;
    const password2 = document.getElementById("registration-password2").value;
    
    //regular expression to prevent wrong email address entry
    const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    
    //regular expression to prevent all special characters in username
    const re2 = /^[^*|\":<>[\]{}`\\()';@&$]+$/;
    
    const noSpace = (username.includes(" "));
    
    const nameLength = username.length<4;
    
      
    if(!re2.test(username) || noSpace || nameLength){
        alert("Username must contain no special characters or space and must be greather than 4");
    }else if(!re.test(email)){
        alert("Please enter correct email address");
    }else if(password.length<8){
        alert("Please enter a 8 or more character password");
    }else if(password != password2){
        alert("Passwords do not match");
    }else{
        sendRegistrationDetails(username, email, password);
    }
}

function sendRegistrationDetails(username, email, password){
    const xmlhttp = new XMLHttpRequest();
  const url = "register.php?username="+username+"&email="+email+"&password="+password;
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        if(this.responseText.trim()!=""){
          
         let response = this.responseText;
         alert(response);
    
        }
      }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

PHP

in our PHP code, the data is received and checked to see if the username already exists by check if the file exists. If a file does not exist with the same name then we go ahead and register the user.

<?php 
    $username = $_REQUEST['username'];
    $email = $_REQUEST["email"];
    $password = $_REQUEST["password"];
    
    
    if(file_exists("database/".$username.".txt")){
        echo "Username already exists";
    }else{
    $file = fopen("database/".$username.".txt","a");
    fwrite($file,$username.PHP_EOL);
    fwrite($file,$email.PHP_EOL);
    fwrite($file,$password.PHP_EOL);
    fclose($file);
    echo "Registration Succesfull";
    }
    
?>

CONCLUSION

We've come to the end of the tutorials and the tutorial for login will be coming soon. click on this link to download the source code of this tutorial.