JQuery Ajax with Login Form

From CoderLearner
Jump to: navigation, search

Use jQuery Ajax for login form

Implement Login Form with jQuery Ajax.


  • 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">
              <td class="lb">Email Login :</td>
              <td><input type="text" name="uname" value="" class="required"/></td>
              <td class="lb">Password :</td>
              <td><input type="password" name="pwd" value="" class="required"/></td>
        <tr><td></td><td><label id="error_msg" class="error"/></td></tr>
        <tr><td></td><td><input type="submit" value="Login" /></td></tr>

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.

    $.validator.messages.required = "*";
                url: "login.php",
                type: "POST",
                data: $(form).serialize(),
                dataType: "json",
                success: function(data)
                        window.location = "index.php";
                        if(data.code == -3){
                            $("label#error_msg").html("Failed login attempts");

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.

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

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

     if($auth) {
          $_SESSION['email'] = $auth['lg_email'];
          $_SESSION['full_name'] = $auth['fname'] . ' ' . $auth['lname'];
          $_SESSION['user_id'] = $auth['id'];
     else {
else {

echo json_encode($return);