Using JQuery to make the ajax login form with PHP.

Here is the scenario:
  • Make the login form with html.
  • When we login, if username and password correct, return correct password or do something else
  • If errors happen, it will display error below the login form.
What do we need ?
  • Basic knowledge about HTML and PHP.
  • Import the jQuery to our application.
Step 1: Create an index.php with the html form code
<!DOCTYPE head PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js></script>
<script type="text/javascript" src="login.js></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>

<style>
body{
margin:0 auto;
max-width: 500px;
padding: 30px;
}
</style>
<body>
 <form method="post" action="login.php">
  <table>
   <tr>
    <td>
     <label for="username">Username:</label>
     <input type="text" name="username" id="username" placeholder="Username"/>
    </td>
   </tr>
   <tr>
    <td>
     <label for="password">Password:</label>
     <input type="password" name="password" id="password" placeholder="Password"/>
    </td>
   </tr>
   <tr>
    <td>
     <input type="button" id="btn" name="btn" value="Submit"/>
    </td>
    </tr>
    <span style="color: red;" id="message"></span>
  </table>
 </form>
</body>
</html>

Step2: We will use the jquery to do the ajax login form. Here is the code in login.js file

jQuery(document).ready(function(){
 jQuery('form').submit(function(event){
  event.preventDefault();
  jQuery.ajax({
   url: jQuery(this).attr('action'),
   type: jQuery(this).attr("method"),
   data:jQuery(this).serialize(),
   success: function(data){
    jQuery('#message').html(data);
   }
  });
 });
});

Step 3: Create a file name login.php

$user = 'admin';
$password = 'admin';
if(isset($_REQUEST['username'],$_REQUEST['password']))
{
 if($_REQUEST['username'] == $user && $_REQUEST['password']==$password )
 {
    die ("login successful");
 }
 else
 {
    die ("username or password is not correct");
 }
}

See, it’s simple.