The Server Side


I know that we have not reached Part V, "Server-Side Interaction," yet, but this object truly requires us to dive into the server-side of the request. With that said, in this section, I do not plan on covering all the ins and outs of PHP or MySQL; rather, I will explain how to make the connection between the server and the client while explaining how to achieve it through the sample. We will create a server-side PHP object, in which we will make XHRs, through another intermediary PHP file that will bridge the gap between JavaScript and PHP. The PHP object will then check a database table for specific data, which we need to validate with our JavaScript object when we receive a response from the server. Let's start by creating the database table. Listing 12.7 shows the SQL code to create the table in your MySQL database.

Listing 12.7. SQL Code to Create a User's Table (awad_users.sql)

CREATE TABLE `awad_users` (   `password` varchar(50) NOT NULL default '',   `username` varchar(25) NOT NULL default '',   `email` varchar(100) NOT NULL default '',   `lastName` varchar(50) NOT NULL default '',   `firstName` varchar(25) NOT NULL default '',   `id` int(11) NOT NULL auto_increment,   PRIMARY KEY  (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

We have already created the Ajax requests in the UserValidation object, so creating the server side will be a breeze. I honestly mean it when I say this: It may seem like a lot of steps to remember, but once you do it, you will be amazed at how simple it really is and how robust an application it can build. As I stated previously, we will need an intermediary PHP file, a PHP object, and a database. The intermediary file is the serviceConnector.php file that we are calling in our UserValidation object's Ajax requests. This file is very simple and is only needed to bridge the gap between the JavaScript and PHP objects. The first thing we will add to this page is a header to set the content type of the returned data to XML for the requesting Ajax object. The file will then include the PHP object called UserManager.class.php, which we will create shortly. This object will then be instantiated with the object variable that we are passing through our request. After the object is instantiated, the method we passed will be fired with the parameters in which we are passing. This file is so abstract that it can virtually be used for any public method, with any parameters passed as a comma-delimited list, in any object that we choose to include in this page. This lends the file quite a bit of power, which is why we will need to add some sort of security to it in Part V, "Server-Side Interaction." Listing 12.8 shows how we accomplish this functionality with this intermediary file.

Listing 12.8. Bridging the Gap Between the Client and the Server (ServiceConnector.php)

<?php header("Content-Type: application/xml; charset=UTF-8"); require_once("classes/UserManager.class.php"); $o = new $_GET['object'](); echo $o->$_GET['method']( $_GET['params'] ); ?>

As I said, this file is extremely simple, yet it packs a lot of power and can basically be used in any situation where you need to make this sort of connection by simply including another object. The object that we are using in this case is for user management, which will be incorporated into our final sample. The methods it contains will look very familiar since we already created the requests in our UserValidation object. The methods this object consists of are listed in Table 12.1.

Table 12.1. The Methods of the UserManager Class (UserManager.class.php)

Methods

Function

constructor

Creates the database connection object

verifyUserInformation

Checks the database to see whether the data passed in as a parameter exists in the database

register

Registers a new user

insertWelcomeMessage

Used by the register method to insert a welcome email in a new user's inbox

login

Logs in an existing user


The Constructor

Before we create the constructor function, we first need to create a private local class variable called dbConnector, which we will use to get the Singleton instance of the database connector object from the DatabaseConnector.class.php in the constructor. After we create this variable and set it to the Singleton object, we fire its init method to make the initial connection and select our database. This object can be used in each of our other methods to connect to the database and make queries. Listing 12.9 shows this code in action.

Listing 12.9. Creating the Object Constructor (UserManager.class.php)

<?php require_once("classes/database/DatabaseConnector.class.php"); require_once("classes/utils/Constants.class.php"); class UserManager {     private $dbConnector;     public function UserManager()     {         $this->dbConnector = DatabaseConnector::getInstance();         $this->dbConnector->init();     } } ?>

Note

A very important thing to remember in order to connect to your database is to change the static variables in Constants.class.php.


These variables look like the code in Listing 12.10.

Listing 12.10. Changing the Database Connection Information (Constants.class.php)

<?php class Constants {     // Datbase connection     static $DB_USER = "USERNAME";     static $DB_PASSWORD = "PASSWORD";     static $DB_HOST = "localhost";     static $DB_NAME = "DB_NAME";     // Database Tables     static $AWAD_EMAIL = "awad_email";     static $AWAD_USERS = "awad_users";     // Password     static $PASSWORD = "TEMPPASSWORD";     // Return Values     static $SUCCESS = "<xml>success</xml>";     static $FAILED = "<xml>failed</xml>";     public function Constants() {} } ?>

These variables should contain the connection information for your database. These are the only items that you will have to modify in Constants.class.php in order to get the sample to work on your server. For security reasons it is also a good idea to put the Constants file in a secure directory that is not accessible from the Web. DatabaseConnector.class.php will never need to be modified because it is configured to connect to any database with this information.

Verifying User Information

All of our XHRs for client-side validation were made to this method. If we take a look back at the Ajax requests that we created in our UserValidation object, they specify the UserManager object, the method name, and the parameters necessary to verify data against the database. After the connection has been made between the client and object, the parameters are used to select the specified data from the database to see whether there is a match. If there is a match, the method returns true; otherwise, it returns false. You will notice we are returning these messages in the form of XML through the Constants.class.php file. This is to make the response a valid DOM object, which will then be accessible via Ajax. See Listing 12.11 for an example.

Listing 12.11. Verifying User Information in the Database (UserManager.class.php)

<?php public function verifyUserInformation($params) {     $param = split(",", $params);     $selector = $param[0];     $selectorValue = $param[1];     $this->dbConnector->connect();     $table = Constants::$AWAD_USERS;     $query = "SELECT * FROM $table WHERE $selector='$selectorValue'";     $result = mysql_query($query);     $this->dbConnector->complete($query);     if(mysql_num_rows($result) == 0)     {         return Constants::$FAILED;     }     else     {         return Constants::$SUCCESS;     } } ?>

Registering and Logging In a User

Although these methods do not have anything to do with Ajax, they do allow us to obtain users on which to run our validation requests. Therefore, I am including them in order to get us started. The first method I am displaying is the register method in Listing 12.12.

Listing 12.12. Registering New Users (UserManager.class.php)

[View full width]

<?php public function register($firstName, $lastName, $email, $username, $password) {     $password = md5($password);     $this->dbConnector->connect();     $table = Constants::$AWAD_USERS;     $query = "SELECT * FROM $table WHERE username='$username' AND password='$password' AND  email='$email'";     $result = mysql_query($query);     if(mysql_num_rows($result) == 0)     {         $query = "INSERT INTO $table (firstName, lastName, email, username, password) VALUES ('$firstName', '$lastName', '$email', '$username', '$password')";         $this->dbConnector->complete($query);         $this->insertWelcomeMessage($username);         return Constants::$SUCCESS;     }     else     {         return Constants::$FAILED;     } } ?>

This method simply takes the data that was entered into the form in our index.php file and adds it to our database.

Note

The register method also fires a method called insertWelcomeMessage, which is not covered in this chapter, but is included in the code sample. This method creates a welcome email by default for new users.


The next method is a login method for existing users (see Listing 12.13).

Listing 12.13. Logging In Existing Users (UserManager.class.php)

<?php public function login($username, $password) {     $password = md5($password);     $this->dbConnector->connect();     $table = Constants::$AWAD_USERS;     $query = "SELECT * FROM $table WHERE username='$username' AND password='$password'";     $result = mysql_query($query);     $this->dbConnector->complete($query);     if(mysql_num_rows($result) == 0)     {         return Constants::$FAILED;     }     else     {         return Constants::$SUCCESS;     } } ?>

These two methods are fired from the index.php file when the form posts back on itself. Listing 12.14 shows the code that needs to be added to the top of our index page to handle registration and login.

Listing 12.14. Handling User Logins and Registration (index.php)

[View full width]

<?php require_once("classes/utils/Constants.class.php"); require_once("classes/UserManager.class.php"); $uManager = new UserManager(); $error = ''; if($_GET['mode'] == 'Register') {     if($_POST['firstName'] !='' && $_POST['lastName'] != '' && $_POST['email'] != '' &&  $_POST['username'] != '' && $_POST['password'] != '')     {         $response = $uManager->register($_POST['firstName'], $_POST['lastName'],  $_POST['email'], $_POST['username'], $_POST['password']);         if($response == Constants::$SUCCESS)         {             header("Location: mail.php?username=". $_POST['username']);         }         else         {             $error = 'The username or password that you have choosen is in use.';         }     }     else     {         $error = 'Please complete all of the form fields.';     } } else {     if(isset($_POST['username']) && isset($_POST['password']))     {         $response = $uManager->login($_POST['username'], $_POST['password']);         if($response == Constants::$SUCCESS)         {             header("Location: mail.php?username=". $_POST['username']);         }         else         {             $error = 'The username and password that you have entered do not match any records.';         }     } } ?>

When the form is posted, it posts back on itself and runs the PHP at the top of the page. It first sets the error variable for later use and then checks the mode of the form. If the mode is equal to register, it runs the register code; otherwise, it runs the login code. In the registration code, it verifies that all the fields were completed and then registers the user through the UserManager object. If the fields are not completed, we set an error message to display to the user. In login mode, we verify that the Username and Password fields are completed and, if they are, we log in the user through the UserManager object. After we receive a successful response, we redirect the user into the application. We set an error message again if there are any failures during this process.

Now that we have created this code, we can really use it for any web application. This reusability is the great thing about writing server-side classes and client-side objects.



Ajax for Web Application Developers
Ajax for Web Application Developers
ISBN: 0672329123
EAN: 2147483647
Year: 2007
Pages: 129
Authors: Kris Hadlock

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net