JQuery Ajax with Login Form

From CoderLearner
Jump to: navigation, search

Use jQuery Ajax for login form

Implement Login Form with jQuery Ajax.

Require

  • HTML Form
  • jQuery libraries (jquery.validate.js and jquery standard library)
  • Server Side Script
  • Database
  • Knowledge in JSON data

HTML form

This is just a simple HTML form for user to input password and user name.

<form id="frm_login">
    <table>
        <tr>
              <td class="lb">Email Login :</td>
              <td><input type="text" name="uname" value="" class="required"/></td>
        </tr>
        <tr>
              <td class="lb">Password :</td>
              <td><input type="password" name="pwd" value="" class="required"/></td>
        </tr>
        <tr><td></td><td><label id="error_msg" class="error"/></td></tr>
        <tr><td></td><td><input type="submit" value="Login" /></td></tr>
    </table>
</form>

jQuery to Process the form

In the jQuery script, we validate the user input. When user does not provide the input, the script will add the * at the end of the input field to indicate the errors.

$().ready(function(){
    $.validator.messages.required = "*";
    $("#frm_login").validate({
        submitHandler:function(form){
            
            $("label#error_msg").html("");
            $.ajax({
                url: "login.php",
                type: "POST",
                data: $(form).serialize(),
                dataType: "json",
                success: function(data)
                {
                    if(data.code==1)
                    {						
                       
                        window.location = "index.php";
                        
                    }
                    else
                    {
                        $("input#password").val("");						
                        if(data.code == -3){
                            $("label#error_msg").html("Failed login attempts");
                        }
                        $("label#error_msg").show();
                    }
                }
            });
        }
    });
});

Server Side Script (login.php)

In this example, I create the static Account::verify_login function. When the function returns the result, it means the user name and password is matched in the database. If it is not matched in the database the login is failed.

<?php 
$uname = strtolower(trim($_POST['uname']));
$pwd = trim($_POST['pwd']);

$return = array();
if (!empty($uname) && !empty($pwd)) {
     $auth = Account::verify_login($uname, $pwd);
     session_start();

     if($auth) {
          $_SESSION['email'] = $auth['lg_email'];
          $_SESSION['full_name'] = $auth['fname'] . ' ' . $auth['lname'];
          $_SESSION['user_id'] = $auth['id'];
          $_SESSION['role']=$auth['role'];
          $return['code']=1;
     }
     else {
          $return['code']=-3;
     }
}
else {
    $return['code']=1;
}

echo json_encode($return);
?>