USING AJAX FOR VALIDATION
BUILDING THE PHP REGISTRATION AND VALIDATION FILE
Photographers who want to share their images and perhaps write articles on photography will need a way to register information with the site that will allow them to log in and gain access to site features not accessible to nonregistered users.
You can create an interaction for this that will appear very slick to the user. With jQuery’s AJAX functionality, you can avoid page reloads or redirections to other pages (Figure 4.1). The AJAX engine will send the requests to the PHP scripts on the server without disruption to the user experience.
Using PHP and jQuery, you’ll create the functions that will support the regis-tration interaction.
1. Open a new text file and save it as chap4/inc/peRegister.php.
NOTE: If you’d like to use the PHP file provided in the download, feel free to skip ahead to “Setting Up the jQuery Validation and Registration
Func-tions” section. Be sure to edit the PHP file with the proper user name, password, and host name for the database connection to match what you have set up on your database server.
ptg
2. Set up the database connection for the PHP function, including a method for returning errors if no connection can be made:
if(!$dbc = mysql_connect(‘servername’, ‘username’, ‘password’)){
echo mysql_error() . “\n”;
exit();
}
Contained in this PHP file are three actions: one to complete registration, one to validate the user name, and a method to allow registered users to log in. The proper function will be called based on the name of the form used in the AJAX function.
3. Use PHP’s switch method to determine which form is submitted and set up the first case for the registration form:
switch($_POST[‘formName’]) { case ‘register’:
FIGURE 4.1
The difference between a typical HTTP request and the XMLHttpRequest utilized by
ptg 4. Check to see if the user name and password are set:
if(isset($_POST[‘penewuser’]) &&
p isset($_POST[‘penewpass’])) {
5. If the user name and password are set, use the data from the form to complete a SQL statement that will insert the new user’s information into the database:
$peuserInsert = “INSERT INTO `photoex`.`peuser` “;
$peuserInsert .= “(`username`, `userpass`, p `userfirst`, `userlast`, `useremail`";
6. Because users can choose a number of photographic interests when they register, you must set up a loop to handle the check boxes that are selected in the registration form:
if(isset($_POST[‘interests’])){
7. The loop used here counts the number of interests selected and properly formats the SQL statement to name those interests. Insert commas in the correct place, and close the initial statement with a closing parenthesis:
$peuserInsert .= “,”;
ptg 8. Place the values from the registration form into the SQL statement in the
correct order:
9. Inserting the correct values includes looping through any interests selected in the form and inserting the value “yes” for those interests:
if(isset($_POST[‘interests’])){
10. Close the SQL statement properly:
$peuserInsert .=”)”;
If you were to print out the resulting SQL statement contained in the vari-able$peuserInsert, it would look something like this:
INSERT INTO `photoex`.`peuser`(`username`, `userpass`, p `userfirst`, `userlast`, `useremail`,`landscape`, p `astronomy`,`wildlife`) VALUES (‘Bob.Johnson’,’ph0t0man’, p ’Bob’,’Johnson’,’[email protected]’,’yes’,’yes’,’yes’,’yes’)
ptg 11. Use the PHP function mysql_query to insert the data into the database, and
the user will be registered:
if(!($peuInsert = mysql_query($peuserInsert, p $dbc))){
echo mysql_errno();
exit();
}
CHECKING THE USER NAME FOR AVAILABILITY
Because the new user will typically fill out the user name first, the password and user name will not be set, so the else statement will be invoked. This is the PHP code that checks the user name to see if it exists in the database.
1. Create a SQL query that selects the user name typed into the registration form from the user database:
} else {
$peCheckUser = “SELECT `username` “;
$peCheckUser .= “FROM `photoex`.`peuser` “;
$peCheckUser .= “WHERE `username` = p ‘”.$_POST[‘penewuser’].”’ “;
if(!($peuCheck = mysql_query($peCheckUser, $dbc))){
echo mysql_errno();
exit();
}
If the name the user entered into the registration form is already in the database, the query will return a row count of 1. If the name is not in the database, the row count is 0.
2. Assign the count of the number of rows returned by the query to the database:
$userCount = mysql_num_rows($peuCheck);
ptg 3. Echo the count value to be returned by the AJAX function for use by jQuery to
determine if the user should enter a new user name in the registration form:
echo $userCount;
}
4. Complete the case statement for the registration form:
break;
CREATING THE PHP FOR USER LOGIN
After registering, the user can log in to the site and begin uploading photos and writing articles. Let’s complete the login section of the PHP file.
1. Set up the case statement for the login code:
case ‘login’:
2. Check to see if the user name and password are set:
if(isset($_POST[‘pename’]) && isset($_POST[‘pepass’])){
3. If they are set, send a query to the database with the user name and pass-word information:
$peLoginQ = “SELECT `username`, `userpass` “;
$peLoginQ .= “FROM `photoex`.`peuser` “;
$peLoginQ .= “WHERE `username` = ‘”.$_POST[‘pename’].”’ “;
$peLoginQ .= “AND `userpass` = ‘”.$_POST[‘pepass’].”’ “;
if(!($peLogin = mysql_query($peLoginQ, $dbc))){
echo mysql_errno();
exit();
}
NOTE: You should always make sure that data visitors enter into forms is cleansed by checking the data rigorously before submitting it to the database.
ptg 4. Set the variable $loginCount to the number of rows returned from the
data-base query. If the user name and password are correct, this value will be 1:
$loginCount = mysql_num_rows($peLogin);
Next, you’ll set up a cookie depending on the user’s preference. A cookie is a small file that is placed on the visitor’s computer that contains information relevant to a particular Web site. If the user wants to be remembered on the computer accessing the site, the user can select the check box shown in Figure 4.2.
5. If the login attempt is good, determine what information should be stored in the cookie:
if(1 == $loginCount){
6. Set up a cookie containing the user’s name to expire one year from the cur-rent date if the “remember me” check box was selected:
if(isset($_POST[‘remember’])){
$peCookieValue = $_POST[‘pename’];
$peCookieExpire = time()+(60*60*24*365);
$domain = ($_SERVER[‘HTTP_HOST’] !=
p ‘localhost’) ? $_SERVER['HTTP_HOST'] : p false;
FIGURE 4.2 The check box a user can click to be remem-bered. The user will not have to log in again until the cookie associated with this action expires or is removed from the computer.
ptg The math for the time() function sets the expiration date for one year from
the current date expressed in seconds, 31,536,000. A year is usually sufficient time for any cookie designed to remember the user. The information in the
$domain variable ensures that the cookie will work on a localhost as well as any other proper domain.
7. Create the cookie and echo the $loginCount for AJAX to use:
setcookie(‘photoex’, $peCookieValue, p $peCookieExpire,
'/', $domain, false);
echo $loginCount;
8. Set a cookie to expire when the browser closes if the user has not selected the remember option:
} else {
$peCookieValue = $_POST[‘pename’];
$peCookieExpire = 0;
$domain = ($_SERVER[‘HTTP_HOST’] !=
p ‘localhost’) ? $_SERVER['HTTP_HOST'] : p false;
setcookie('photoex', $peCookieValue, p $peCookieExpire,
'/', $domain, false);
echo $loginCount;
}
ptg 9. Echo out the login count if the user name and password are not set. The
value should be 0:
} else {
echo $loginCount;
} } break;
With the PHP file ready to go, it is time to build the jQuery AJAX functions.
SETTING UP THE JQUERY VALIDATION AND