AdSense

Sign Up and Login using jQuery AJAX in PHP Mysql
Hello Friends, In this article we will learn How to create Sign up and login functionality using jQuery AJAX in PHP MySQL. There are a large number of online applications and the registration system must be the most common function among all. The registration form is intended to allow users to purchase a membership to obtain special permissions that vary depending on the application.
The importance of the registration system for application registration is to make the visitor a registered member of the application and to allow visitors to enter the system to verify its authenticity. Based on the authenticity of the registered user, application users are given access to web pages, utilities, and permissions.
Specifically, the login page is a general landing page for administrative web applications. In the WordPress administrator, for example, the entry window is displayed as the target page. The ordering system implements a simple registration to enter online applications as e-commerce software and is very simple.

I have good explain Registration and login Page in PHP Mysql


This Seven steps to implement Signup and Login

1. Create a Database connection 
2. Create a Sign up HTML page
3. Create PHP code for Sign up from database
4. Create a Login HTML page
5. Create PHP code for Login from database
6. Create Student/Users Profile Page after login successful
7. Create Logout Page


1.Create a Database connection
We first need to connect to the database, first create the config.php file. Write the following code in this file.

config.php
<?php
	// Database configuration 
	$dbHost     = "localhost"; 
	$dbUsername = "root"; 
	$dbPassword = ""; 
	$dbName     = "registration"; 
	 
	// Create database connection 
	$con = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
	 
	// Check connection 
	if ($con->connect_error) { 
	    die("Connection failed: " . $con->connect_error); 
	}

 ?>


2.Create a Sign up HTML page
In this file we have code that defines the HTML form that users use to register. If the user click the submit button after completing the form, he sends all the data in a jquery ajax , where the entry is validated and sent to the backend via an AJAX post call.

index.php

<!Doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Sign up using jQuery AJAX in PHP Mysql</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin-top:50px">
<h1 style="text-align:center;">Sign up using jQuery AJAX in PHP Mysql</h1><br>
  <div class="row">
    <div class="col-md-4"></div>
      <div class="col-md-4">

        <!-- alert success and danger message--->
        <span class="message-message"></span>
        
        <form id="signupForm">
          <div class="form-group">
             <input type="text" class="form-control" name="fullname" placeholder="Full Name" required="">
          </div>
          <div class="form-group">
             <input type="text" class="form-control" name="username" placeholder="Username" required="">
          </div>
          <div class="form-group">
             <input type="email" class="form-control" name="email" placeholder="Email" required="">
          </div>
          <div class="form-group">
             <input type="password" class="form-control" name="password" placeholder="Password" required="">
          </div>
          <p>If you have account <a href="loginForm.php">Login</a></p>
          <input type="submit" class="btn btn-primary btn btn-block" value="Sign Up">  
        </form>
      </div>
    </div>
  </div>
</body>
</html>

<script type="text/javascript">
  $(document).ready(function(){
      $("#signupForm").on("submit",function(e){
        e.preventDefault();
        var formData = $(this).serialize();
        $.ajax({
            url : "register.php",
            type: "POST",
            cache:false,
            data: formData,
            success:function(response){
              data = JSON.parse(response);
              if (data.error == "0") {
                $("#signupForm").trigger("reset");
                $('.message-message').replaceWith('<div class="alert alert-success alert-dismissible" role="alert">'
                 + data.message + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');
              }else if(data.error == "1") {
               $('.message-message').replaceWith('<div class="alert alert-danger alert-dismissible" role="alert">'
                 + data.message + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');
              }
            }
        });
      });
  });
</script>


3.Create PHP code for Sign up from database
This file contains the code which takes the request sent from AJAX $_POST method to save the information in the database. Initially, it will read the $_POST variable for accessible information and they will be stored in local variables . Than, using mysql statement the data stored in the database.

register.php
<?php
	// include database connectivity file

	include_once('config.php');

	if (isset($_POST['username'])) {
		
	    $fullname = $con->real_escape_string($_POST['fullname']);
	    $username = $con->real_escape_string($_POST['username']);
	    $email 	  = $con->real_escape_string($_POST['email']);
	    $password = $con->real_escape_string(md5($_POST['password']));

	    $query  = "INSERT INTO students (fullname,username,email,password) 
	    	      VALUES('$fullname','$username','$email','$password')";
	    $result = $con->query($query);

            if ($result) {
	         echo json_encode(array('error'=>'0', 'message'=>'Registration successfully Login'));
	    }else{
	        echo json_encode(array('error'=>'1', 'message'=>'Registration Failed try again'));
	    }
	}

?>

Sign Up Output

Sign up or registration using jQuery AJAX in PHP Mysql


4.Create a Login HTML page
In this file we have code that defines the HTML form that users use to login. If the user click the login button after completing the form, he sends all the data in a jquery ajax , where the entry is validated and sent to the backend via an AJAX post call.

loginForm.php

<?php
  session_start();
  if (isset($_SESSION['id'])) {
      header("Location:profile.php");
  }
?>
<!Doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Login using jQuery AJAX in PHP Mysql</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin-top:50px">
<h1 style="text-align: center;">Login using jQuery AJAX in PHP Mysql</h1><br>
  <div class="row">
     <div class="col-md-4"></div>
      <div class="col-md-4" style="margin-top:20px">

        <!-- alert success and danger message--->
        <div class="alert alert-danger alert-dismissible show-message" role="alert" style="display: none;">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          <span class="ajax-message"></span>
        </div>
        
        <form id="loginForm">
          <div class="form-group">
            <input type="email" class="form-control" id="email" placeholder="Email" required="">
          </div>
          <div class="form-group">
            <input type="password" class="form-control" id="password" placeholder="Password" required="">
          </div>
          <p>Are you new user? <a href="index.php">Sign Up</a></p>
          <input type="submit" class="btn btn-info btn btn-block" name="btnSubmit" value="Login">
        </form>
      </div>
    </div>
  </div>
</body>
</html>

<script type="text/javascript">
  $(document).ready(function(){
      $("#loginForm").on("submit", function(e){
        e.preventDefault();

        var email = $("#email").val();
        var password = $("#password").val();

        $.ajax({
            url : "login.php",
            type:"POST",
            cache:false,
            data:{email:email,password:password},
            success:function(response){
              if(response == '1') {
                window.location.replace("profile.php");
              }else if(response=='0'){
                $(".show-message").show();
                $(".ajax-message").text('Email or Password is Invalid');
              }
            }
        });
      });
  });
</script>



5.Create PHP code for Login from database
In this file we have to contains the user login email and password to check which is exists to database or not.

login.php
<?php

    session_start();

    // include database connectivity file

    include_once('config.php');

    if (isset($_POST['email'])) {

	$email 	  = $con->real_escape_string($_POST['email']);
	$password = $con->real_escape_string(md5($_POST['password']));

	$query = "SELECT * FROM students WHERE email ='$email' && password ='$password'";
    
	$result = $con->query($query);
        $row = $result->fetch_assoc();

        if($result->num_rows > 0) {
             $_SESSION['id'] = $row['id'];
	     $_SESSION['fullname'] = $row['fullname'];
             echo 1;
        }else{
             echo 0;
        }
    }

?>


6. Create Student/Users Profile Page after login successful
This file is the user profile page redirect after user login, If user email and password is valid and exists in database than redirect to the profile page.

profile.php

<?php
  session_start();
  if (!isset($_SESSION['id'])) {
      header("Location:loginForm.php");
  }
?>
<!Doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Student Profile Page</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
  <div class="container" style="margin-top:50px">
    <h1 style="text-align:center;">Student Profile Page</h1><br>
    <div class="row">
       <h5>Hello, <?php echo ucwords($_SESSION['fullname']); ?> <small><a href="logout.php">Logout</a></small></h5>   
    </div>
  </div>
</body>
</html>


7. Create Logout Page

logout.php
<?php
    include_once('config.php');
    session_start();
    session_destroy();
    session_unset($_SESSION['id']);
    session_unset($_SESSION['fullname']);
    header("Location:loginForm.php");
?>


Login Output

Login using jQuery AJAX in PHP Mysql


You can always support by sharing on social media or recommending my blog to your friends and colleagues.
If you have any suggestions / problems about this tutorial, please comment on the  form below.😊

Post a Comment

Previous Post Next Post