Dj Techblog

A blog on web development

Simple login form in ajax and php using mobile number

Published on Oct 10, 2020
Mobile number verification using OTP SMS with TextLocal
Hello friends, hope all are doing well.

In this login form, I have made two inputs fields, mobile number, and the password. In place of a mobile number, you can also take a username, but logic will remain the same. User inputs two values and clicks on the Login button. On clicking the button a javascript function is called. The function receives the mobile number and password from the login form and makes an ajax request to the server. The server then checks the database for mobile number and password. If the mobile number and password both match, the user automatically redirected to the home page, otherwise gets a login error message.

We use JavaScript to retrieve data from the login form and send it to the server via ajax call. So we need not refresh every time a user enters the wrong credentials. Hence this is a fast and effective way of implementing a login form.

Also read, mobile number verification by otp sms in php.

So, lets start the coding procees for login.

  1. Design your index.html page.
  2. Write your javascript function script.js.
  3. Calls login.php file in the server making an ajax call.
  4. Receives the response from the server and gives message to the user accordingly.
  5. Redirects to Home page on successful regstration.



Landing page : index.php

<!DOCTYPE html>
<html>
<head>
<title>Login form using Php and Ajax</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="script.js"></script>
</head>
<body>
<div class="success"></div>
<div class="container w3-card">
  <div class="error"></div>
  
    <div class="mobile-heading">User Login form using Mobile Number</div>
    <div class="mobile-row">
      
      <input type="number" id="mobile" class="mobile-input" placeholder="Enter the mobile number">
      <br><br>
      <input type="password" id="password" class="mobile-input" placeholder="Enter your password">
    </div>
    <div id="loading-image"><img src="ajax-loader.gif" alt="ajax loader"></div>
    <br>
    <input type="button" class="mobileSubmit" value="Login" onClick="userLogin();">
  </form>
</div>
</body>
</html>
landing page form

Explaination :

When the user clicks on the Login button, a javascript function is called. The function checks for valid input details. If given inputs are not valid it shows an error message. If both the inputs are valid then function makes an ajax call to the server.

script.js

function userLogin() {
$(".error").html("").hide();
var number = $("#mobile").val();
var password = $("#password").val();

if (password.length !=0 && number.length == 10 && number.length != 0 ) {
  var input = {
    "mobile_number" : number,
    "password" : password,
    "action" : "user_login"
  };
  $("#loading-image").show();
  $.ajax({
    url : 'login.php',
    type : 'POST',
    data : input,
    success : function(response)
    {
      if(response == 1)
        window.location.href = "home.php";
      else
        $('.error').html("Login failed. Try Again.").show();
    },
    complete : function(response){
      $("#loading-image").hide();
    },
    error : function(response){
      $('.error').html(response.message).show();
    }
  });
  
} 
else {
  if(number.length == 0 || number.length != 10){
    $(".error").html('Please enter a valid number!');
    $(".error").show();
  }
  else{
    $(".error").html('Please enter password!');
    $(".error").show();
  }
}
}
The login.php file takes the inputs sent via ajax call save it in two variables. After that, it establishes a database connection and searches for the mobile number and password provided by the user. If it is found then the mobile number and username of the user are saved in two session variables. If a mobile number match is not found, ajax call returns.

If returned respose is 1, javascript function redirects the user to the home page. If it is 0 , it prints an error to the screen without reloading the page.

We only need to reload once when it is needed to redirect the user to the home page if login is successful. If login fails we need not reload the page to print an error message because ajax successfully prints an error message on the screen without reloading it.

login.php

<?php
session_start();
error_reporting(E_ALL & ~ E_NOTICE);

class Login
{
  function __construct() {
      $this->userVerification();
  }
  function userVerification()
  {
      switch ($_POST["action"]) {
        
          case "user_login":
            $db = mysqli_connect('localhost' , 'root' , '' , 'bncacade_regd');
            $mobile_number = $_POST['mobile_number'];
            $password = $_POST['password'];
            $user_check_query = "SELECT fname FROM reg_user WHERE mobile='$mobile_number' AND password='$password' LIMIT 1";
          $result =  mysqli_query($db, $user_check_query);
          if ($result === FALSE) {
            die(mysqli_error($connect));
        }
          //$user = mysqli_fetch_assoc($result);
          $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
          if ($row) 
          {
            echo 1;
            $_SESSION['mobile'] = $mobile_number;
            $_SESSION['user_name'] = $row['fname'];
          }
          else 
            echo 0;
          
          break;
      }
  }                      
}

$login = new Login();

?>
                           
When the user redirected to the home.php page, we start a session and checks whether the session variable is set or not. If it is not set the user will be redirected to the landing page. If the session variable is set it will print a "Hello" message to the user.

home.php

<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body class=" w3-container w3-center w3-green"><h1>Home</h1></body>
<?php  
session_start();
  if(!isset($_SESSION['user_name'])){
    header("location:index.html");
    die();
    }
  else
      echo "Hello " . $_SESSION['user_name'];  ;

?>
</html>
User home page after login
If you face any issue while implementing the code, you can contact me. Thanks for patient reading.

Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.