Learning jQuery: Submit form PHP Mac style Modal window

written by aext on September 5, 2009 in PHP with 22 comments

In my previous post, I show you how to make up the login form likes Mac app DeskShade. Today, this entry is the next part of that post. This tutorial will help you submit that form with PHP handler. Furthermore, with some effects come along, your form will be nicer. I would like to name this post as “Learning jQuery…” in the series of jQuery Learning posts because in each post, I will focus on one or two functions of jQuery, and after reading, I’m sure you’ll be cool. If you’re new to jQuery, you should not miss!

Before start this tutorial, I would like to forward you a link to this demo. You can download this source code to see how simple it is. Default login is username: admin, password: 123456

Learning jQuery: Submit form PHP Mac style Modal window

Maybe you have not read my previous entry that’s first part of this one today. I suggest you read it first before continue because I’m not gonna talk about that again. Check this post Learning jQuery: Click Event with Locked Page likes Mac! then come back later :D

1. HTML & CSS code


I forgot I wont talk about it. Please click here to get the HTML and CSS code. Some update will be below.

2. Javascript


Because I’ve made some changes with javascript code, I will show you the differences. I wrote all the javascript code into one file, and below it’s explaining each javascript code block.

Validate the form:

I just write some code to validate the form if it’s blank. You will see the code how it simple. If you want to check more with this form, you can write yourself with same as below.

                //Validate the Username field if it's blank
                var username = $("input#username").val();
                if (username == "") {
                    $('#message').html("All the fields are required");
                    $("#message").hide().fadeIn(1500);
                    $("input#username").focus();
                    return false;
                }

                //Validate the Password field if it's blank
                var password = $("input#password").val();
                if (password == "") {
                    $('#message').html("All the fields are required");
                    $("#message").hide().fadeIn(1500);
                    $("input#password").focus();
                    return false;
                }

Post File

Let’s set the file that the form will send a simple POST request to.

            // POST handler
            var postFile    =   'bin/doLogin.php'

Submit the form

If the form is valid, then submit it to postFile. At first, I would like to talk about using POST request with jQuery. The $.post will be something likes this:

$.post(url, data, callback, type);
  • url: The URL of the page to load.
  • data: Key/value pairs or the return value of the .serialize() function that will be sent to the server. (Optional)
  • callback: A function to be executed whenever the data is loaded successfully. (Optional)
  • type: Type of data to be returned to callback function: “xml”, “html”, “script”, “json”, “jsonp”, or “text”.(Optional)

In this tutorial, the form will get the doLogin.php page contents which has been returned in json format

      $.post(postFile, { usernamePost: username, passwordPost: password }, function(data) {
          if(data.status==true) {
              //If return data is true, it means username and password are correct
              window.location=data.url;
          } else {
              $("#message").html("Wrong Username or Password");
              $("#message").hide().fadeIn(1500);
              $("input#username").focus();
          }
      }, "json");

      return false;

At the code above, when form was submitted, if return is true, browser will transfer to a destination page. If return is false, it’ll replace the text in span id #message by error message by fadeIn effect. Finally, focus mouse on username text field.

Cancel button was handled by closing the form with fadeOut effect and display the locked icon. I want to mention this part to who has never read previous post.

            // This is example of other button
            $("input#cancel_submit").click(function(e) {
                    $("#loginform").hide();
                    $(".lock").fadeIn();
            });

Some effects that make the form cool
Add more script to add some cool effect to the form. If the form is valid and return with authorized account, login form will go up to the top and change opacity to 0. I dont how you like it but I want it delays 1 second after the form move up then set location for browser to destination. The timer plugin I’m using is jQuery Timer

      $.post(postFile, { usernamePost: username, passwordPost: password }, function(data) {
            if(data.status==true) {
              //If return data is true, it's mean username and password are correct

              //The distance in pixel that the form will move from original location
              var distance = 10;

              //The time that the form take to animate
              var time = 500;

              // This will hold our timer
              var myTimer = {};

              $("#loginform").animate({
                  marginTop: '-='+ distance +'px',
                  opacity: 0
              }, time, 'swing', function () {
                  $("#loginform").hide();
              });     

              // Set the timer for 1 seconds
              myTimer = $.timer(1000,function() {
                  window.location=data.url;
              });
          } else {
              $("#message").html("Wrong Username or Password");
              $("#message").hide().fadeIn(1500);
              $("input#username").focus();
          }
      }, "json");

      return false;

After testing on Firefox and Safari, I decide to choose “marginTop” insted of “top” attribute. Although, this form is set position as absolute, It’s better if using “top” attribute but It’s get bug on Safari when moving likes flashing. So, just make it easier with marginTop. Sorry to IE users that I still have not tested on IE. Who get it with IE please give me some information.

3. PHP


PHP code, the POST handler is:

<?php

    require('config.php');
    require('account.php');

    //Create new account from Account class to verify account was submitted
    $account = new Account;

    //Clean up the form submission
    $username = (!empty($_POST['usernamePost']))?trim($_POST['usernamePost']):false;
    $password = (!empty($_POST['passwordPost']))?trim($_POST['passwordPost']):false;

    //Signin will be here
    $verify = $account->login($username,$password);

    if($verify) {
        //Login Successful
        echo "{'status': true,'url':'".TARGET."'}";
    } else {
        //Failed to login
        echo "{'status': false,}";
    }

    //Destroy
    unset($account);
?>

TARGET value was define in configuration file that will be your URL you want to send browser redirect to.

Account Class
In Account class, you will write code to select data from users table. Login function will return true or false, so set the default return first. It’s always false.

            //Set default return value is false
            $return = false;

Connect to database then select users table. All server, table value was configured in config.php file. You can easy change these value in that file.

            //Connect to the Database
            $this->db = @mysql_connect($config['server'],$config['dbuser'],$config['dbpass']);

            //Can not connect? return false
            if(!$this->db)
                return false;

            //Select Database table
            $opendb = @mysql_select_db($config['dbname'], $this->db);

            //Can not find or open table? Or something else ....Return false
            if(!$opendb)
                return false;

Because in this tutorial, I check username or email for identifying. So, SQL query will check if its has correct username or email will return true. Absolutely, password must be matched.

            $sql = "SELECT * FROM ".$config['dbtable']." WHERE ";
            $sql .= "(username='".mysql_real_escape_string($username)."'";
            $sql .= " OR useremail='".mysql_real_escape_string($username)."')";
            $sql .= " AND userpassword = '".md5($password)."'";

To check if it has valid account entered.

            //Query table
            $rs = @mysql_query($sql,$this->db);     

            //Can not query
            if(!$rs) return false;

            //If result value is number of rows
            if(mysql_num_rows($rs))
                $return = true;

Finally, return to $return value

            //Return to the value of $return aboe
            return $return;

Conclusion:


It’s hard for me to code in PHP because I’m Java guy and not familiar with PHP. If something goes wrong with the code, please give me some advices. You should define some value that prevent direct file access to these PHP file.

Define in your POST handler

    //Prevent dirrect file access
    define('GUARD', true);

And at the beginning of each others PHP file

if (!defined('GUARD')) {
   die('I am sorry, you can not access this file directly.');
   exit;
}

Thanks for reading and feel free to comment, share this post. Suggestions will be appreciated.