skip to Main Content

I have a login form that has two inputs email and password. If a user enters incorrect credentials, I have to show them the error. I have done form validation in PHP, so I need to send data from the form and get a response message without refreshing the page. I’m new to ajax, so I don’t know how to do it

login.php

<form action="register.php" method="POST" autocomplete="off">
              <h1 class="card-title display-4 mt-4 mb-5 text-center">Login</h1>

              <div class="form-group">
                <input type="email" class="form-control" id="email" placeholder="Email" name="email" />
                <div class="email-status"></div>
              </div>

              <div class="form-group">
                <input type="password" class="form-control" id="password" placeholder="Password" name="password" />
                <div class="password-status"></div>
              </div>

              <p class="card-text text-center"><a href="forgotpassword.php">Forgot your password?</a></p>
              <span class="d-flex justify-content-center">
                <button type="submit" class="btn btn-primary mb-4 w-50" style="border-radius: 20px;" name="login_btn" id="login_btn">Login</button>
              </span>
              <div class="success"></div>
            </form>

<script>
    $(document).ready(function() {
      $("#login_btn").click(function() {
        var email = $("#email").val();
        var password = $("#password").val();

        $.ajax({
          url: 'register.php',
          type: 'post',
          data: {
            email: email,
            password: password
          },
          success: function(response) {
            var emailstatus = "";
            var passwordstatus = "";
            var success = "";
            if (response == 1) {
              emailstatus = "required";
              $(".email-status").text(emailstatus);
            } else if (response == 2) {
              emailstatus = "invalid";
              $(".email-status").text(emailstatus);
            } else if (response == 3) {
              emailstatus = "match";
              $(".email-status").text(emailstatus);
            } else if (response == 4) {
              passwordstatus = "required";
              $(".password-status").text(passwordstatus);
            } else if (response == 5) {
              passwordstatus = "match";
              $(".password-status").text(passwordstatus);
            } else {
              success = "sometihg went wrong";
              $(".success").text(success);
            }
          }
        });
      });
    });
  </script>

register.php for form validation

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

  $email = mysqli_real_escape_string($conn, $_POST['email']);
  $password = mysqli_real_escape_string($conn, $_POST['password']);
  $new_password = md5($password);

  $result = mysqli_query($conn, "SELECT * FROM users WHERE email = '$email' OR password = '$new_password' LIMIT 1");
  $row = mysqli_fetch_assoc($result);

  //EMAIL
  if (empty($email)) {
    $email_status = "Email is required";
    echo 1;
  } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $email_status = "Enter valid Email ID";
    echo 2;
  } elseif ($row['email'] != $email) {
    $email_status = "Email doesn't exist";
    echo 3;
  }
  //PASSWORD
  elseif (empty($password)) {
    $password_status =  "Password is required";
    echo 4;
  } elseif ($row['password'] != $new_password) {
    $password_status = "Password doesn't match";
    echo 5;
  } else {
    $query = "SELECT * FROM users WHERE email = '$email' AND password = '$new_password'";
    $results = mysqli_query($conn, $query);
    if (mysqli_num_rows($results) == 1) {
      $rows = mysqli_fetch_array($results);
      $_SESSION['username'] = $rows['username'];
      $_SESSION['success'] = "You are now logged in";
      if (isset($_SESSION['login_redirect'])) {
        header("Location: " . $_SESSION["login_redirect"]);
        unset($_SESSION["login_redirect"]);
      } else if (isset($_SESSION['url'])) {
        $url = $_SESSION['url'];
        header("Location: $url");
      } else {
        header("Location: homepage.php");
      }
      exit;
    } else {
      $success =  "Something went wrong";
      echo 6;
    }
  }
}

If I run the above code, the page gets refresh and I’m not getting any response or validation messages

2

Answers


  1. You have to prevent auto form submit. add an Id or a class to your form element and add this code

    Inside of document ready

    $("#form-id").submit(function(e){
        e.preventDefault();
      });
    

    And in form element add an Id

    <form action="register.php" id='form-id' method="POST" autocomplete="off">
    
    Login or Signup to reply.
  2. Replace your data object of ajax as follows and your current code will work:

    data: {
       email: email,
       password: password,
       login_btn: true
    }
    

    You are checking isset of login_btn value which was not pass through the ajax.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search