PHP MySQL Login Form with Jquery AJAX

In this blog, we will learn how can we submit a form without re-loading or redirecting to another page in PHP with Jquery AJAX. Jquery AJAX is very simple and its syntax is very readable. If you have basic knowledge of Jquery you can easily work with AJAX.

In this example, we will work with Login Form. You can work with any form after understanding the functionality of this example form. You can submit form data using POST or GET using ajax and can save this form data into your database.

Now Lets Start.

First create a Database and Table for login credentials. I have Database named 'ajaxtest' and this database has a Table named 'admins'.
My 'admins' Table has 4 fields.

  1. id
  2. username
  3. password
  4. status

Now create a file index.php, write html code for login form in this file.

  
  <h2>Login</h2>

  <form action="" method="">
    <label for="uname">Username:</label><br>
    <input type="text" id="uname" name="uname" value=""><br>
    <label for="passwrd">Password:</label><br>
    <input type="password" id="passwrd" name="passwrd" value=""><br><br>
    <input type="button" value="Login" id="loginInp">
  </form>                          

Now login form is ready. You can see, the action of this form is blank because we are not going to submit this form using submit buttom. We are going to use Jquery AJAX to submit this form. Lets see how.

Now we will validate this form using Jquery and then submit form to new page check_login.php.
When we use Jquery to validate a form, this is called Client Side Validation. Client side validation is Fast and real time validation.

  
  $(document).ready(function(){
    $("#loginInp").click(function(){

      //====== Form Validation
      var uname = $("#uname").val();
      var password = $("#password").val();
      if($.trim(uname)==""){
        alert("Enter Username"); return false;
      }
      if($.trim(password)==""){
        alert("Enter Password"); return false;
      }


      //======= Submit form using AJAX
      var frm = $("#frm").serialize();
      $.ajax({
        url:"check_login.php",
        type:"post",
        data:frm,
        success:function(data){
          if(data.indexOf("SUCCESS")>-1){
            window.location.href="dashborad.php";
          }
          else{
            alert("Please check Username and Password.");
          }
        },
        errror:function(err) {
          alert("Something Went Wrong");
        }
      })
    });
  });
                          

In this Jquery code, first we validate the form fields and then send AJAX request. We use serialize() function to send form data in AJAX request. check_login.php is the page where database queries is written. This page also return 'SUCSESS' or 'ERROR'. We get this return value in a variable, in my case it is data. If the value of variable data is 'SUCCESS', then login is successful and it redirects to dashborad.php.

Now create file check_login.php.

  <?php
$conn = mysqli_connect("localhost","root","","ajaxtest");
if(!$conn)
  die("Connection Error");

$uname = $_POST["uname"];
$pass = $_POST["password"];

if($uname!="" && $pass!=""){

  $sql="select * from admins where username='".mysqli_real_escape_string($conn,$uname)."' and password='".mysqli_real_escape_string($conn,$pass)."' and status='active'";
  $rss = mysqli_query($conn,$sql);

  if(mysqli_num_rows($rss)>0){
    echo "SUCCESS";
  }
  else{
    echo "ERROR";
  }
}
else{
  echo "ERROR";
}
?>                          

In this code, we used PHP MySQLi. First we write code to create Database Connection. Then get POST values from login form.

Here we get matched data from database. If there is found any data, it will return 'SUCCESS' otherwise it will return 'ERROR'.

These return values are used in AJAX to validate if login is successfull and page redirects to dashborad.php.

So, this is the simple example of Login with Jquery AJAX.
In this example, we have used HTML, Jquery, AJAX, PHP, MySQLi.

For more information and use of Jquery AJAX, please read our another blog.