Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

Applied jQuery: Being Effective with AJAX

jQuery simplifies using AJAX with several shorthand methods for the basic AJAX methods. For most developers and designers, these shorthand methods will be all that they ever need to use. The jQuery AJAX shorthand methods post, get, and load are featured in this chapter.
This chapter is from the book

This chapter is from the book

AJAX, one of the hottest technology combinations to enter the Web development landscape in years, has fueled a surge in interactive Web design with its ability to load new content into an existing DOM structure.

jQuery simplifies using AJAX with several shorthand methods for the basic AJAX methods. For most developers and designers, these shorthand methods will be all that they ever need to use. The jQuery AJAX shorthand methods post, get, and load are featured in this chapter. jQuery also provides a robust feature set, including callbacks, for developers who want to customize their AJAX calls to provide richer interactive experiences. I'll show you how to use several of jQuery's AJAX features to enhance Web sites and applications. Let's start by completing the form validation that you started in Chapter 3.

Using AJAX for Validation

Simply put, AJAX (Asynchronous JavaScript and XML) lets you use JavaScript to send and receive information from the server asynchronously without page redirection or refreshes. You can use AJAX to grab information and update the Web page that your user is currently viewing with that information. Complex requests can be made to databases operating in the background.

When new users register to use the Web site, they need to have unique user names. Their user name will be associated with other information, such as photos they upload or articles they write. It will be the key that lets them update information about the photos they submit.

Make sure that you first set up the database for the Web site by running the SQL file chap4/sql/peuser.sql on your database. Running this script in MySQL or any other database platform will create the Web-site's database, a user for that database, and the table that will be used to store Web-site visitor registration information. You can then start building the PHP file that will respond to the actions the AJAX functions will request.

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.

Figure 4.1

Figure 4.1 The difference between a typical HTTP request and the XMLHttpRequest utilized by jQuery's AJAX methods.

Using PHP and jQuery, you'll create the functions that will support the registration interaction.

  1. Open a new text file and save it as chap4/inc/peRegister.php .
  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: <
    pre>
             switch($_POST['formName']) {
        case 'register':
  4. Check to see if the user name and password are set:
       
             if(isset($_POST['penewuser']) && 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`, `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 .= ",";
                    for($i = 0; $i < count($_POST['interests']); $i++){
                        if($i == (count($_POST['interests']) - 1)){
                            $peuserInsert .= "`".$_POST['interests'][$i]."`";
                        } else {
                            $peuserInsert .= "`".$_POST['interests'][$i]."`, ";
                        }
                    }
                       }
                $peuserInsert .=")";
  8. Place the values from the registration form into the SQL statement in the correct order:
                $peuserInsert .= "VALUES (";
                $peuserInsert .= "'".$_POST['penewuser']."', ";
                $peuserInsert .= "'".$_POST['penewpass']."', ";
                $peuserInsert .= "'".$_POST['pefirstname']."', ";
                $peuserInsert .= "'".$_POST['pelastname']."', ";
                $peuserInsert .= "'".$_POST['email']."' ";
  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'])){
                    $peuserInsert .= ",";
                        for($i = 0; $i < count($_POST['interests']); $i++){
                            if($i == (count($_POST['interests']) - 1)){
                                $peuserInsert .= "'yes'";
                            } else {
                                $peuserInsert .= "'yes', ";
                            }
                        }
                    }
  10. Close the SQL statement properly:

                    $peuserInsert .=")";

    If you were to print out the resulting SQL statement contained in the variable $peuserInsert, it would look something like this:

    INSERT INTO `photoex`.`peuser`(`username`, `userpass`, `userfirst`, `userlast`, `useremail`,`landscape`, `astronomy`,`wildlife`) VALUES ('Bob.Johnson','ph0t0man','Bob','Johnson','photoman@gmail.com','yes','yes','yes','yes')
  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, $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` = '".$_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);
  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 password 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();
            }
  4. Set the variable $loginCount to the number of rows returned from the database 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.

    Figure 4.2

    Figure 4.2 The check box a user can click to be remembered. The user will not have to log in again until the cookie associated with this action expires or is removed from the computer.

  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 current 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'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;

    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, $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'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
                    setcookie('photoex', $peCookieValue, $peCookieExpire,
    '/', $domain, false);
                    echo $loginCount;
            }
  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 Registration Functions

Checking the new user name should be as seamless as possible for the registrant. The form should provide immediate feedback to users and prompt them to make changes to their information prior to the form being submitted. The form input (in chap4/4-1.php) element for the user name will be bound to the blur method:

<label class="labelLong" for="penewuser">Please choose a user name: </label><input type="text" name="penewuser" id="penewuser" size="24" /><span class="error">name taken, please choose another</span>
  1. Bind the form input for the user name to jQuery's blur method:
    $('#penewuser').blur(function() {
  2. Capture the value of the user name in the newName variable:
        var newName = $(this).val();

Next, you'll validate with the post method.

  1. Call the post method with the URL of the PHP script, data representing the name of the form that is being filled out, and the newName variable:

    $.post('inc/peRegister.php', {
            formName: 'register',
            penewuser: newName

    Note that the data passed by the post method is in name: value pairs. The value in each pair is quoted when sending the raw data. Variables such as newName do not need the quotes.

    The results of calling the inc/peRegister.php script will automatically be stored for later processing in the data variable.

  2. Define the callback for the post function and pass the data variable to the function, so that the results can be processed:

        }, function(data){

    The PHP function returns only the row count based on the query that was used to see if the user name was in the database.

  3. Set up a variable to hold the information returned in the data variable:
           var usernameCount = data;
  4. Create a conditional statement that will display or hide the error message based on the data returned by the AJAX method. You'll recognize most of this conditional statement because it is similar to how validation error messages were delivered in Chapter 3:
            if(1 == usernameCount){
                $('#penewuser').next('.error').css('display', 'inline');
            } else {
                $('#penewuser').next('.error').css('display', 'none');
            }
  5. Close out the post function by citing the data type you expect the server-side function to return:

        }, 'html');
    });

    If the PHP function returns a 1, the error span is displayed, as illustrated in Figure 4.3.

    Figure 4.3

    Figure 4.3 The user name FrankFarklestein is already in use by someone else. Who knew there were two of them?

The registration function needs to submit the user's data or let the user know if there are still errors with the submission. If there are errors, the user needs to be prompted to fix the registration.

  1. Start the registration function by binding the registration form to the submit method:

    $('#registerForm').submit(function(e) {

    The variable e holds information about the event object, in this case the submit event.

  2. Because you will be using AJAX to submit the form, you do not want the submit event to perform as it normally would. To stop that from happening, you set the event to preventDefault:
        e.preventDefault();
  3. Serialize the form data. The serializing creates a text string with standard URL-encoded notation. For most forms, this notation is in the form of key=value pairs:
        var formData = $(this).serialize();
  4. Now you can invoke the jQuery AJAX post method by providing the URL to post to and the serialized form data, and setting up a callback function:

       $.post('inc/peRegister.php', formData, function(data) {

    The PHP code will return 0 if the query to add the user is successful. If not, it will return a higher number, indicating that the user could not be added.

  5. Store the information returned by the AJAX function in the mysqlErrorNum variable:

            var mysqlErrorNum = data;

    If an error is returned, you'll want to provide users with a prompt to let them know that they need to correct the information. The information is provided in a modal window as you have done before. Figure 4.4 shows the modal window that you will set up next.

    Figure 4.4

    Figure 4.4 The modal prompt letting users know that they need to correct their registration information. In the background you can see that the user name is already taken; this must be changed.

  6. Test the value of the variable mysqlErrorNum to set up a conditional statement:
          if(mysqlErrorNum > 0){
  7. If mysqlErrorNum is greater than 0, append a modal window to the body of the Web page:
              $('body').append('<div id="re" class="errorModal"><h3>There is an error with your registration</h3><p>Please correct your information and re-submit...</div>');
  8. Calculate and apply the margins for the new modal window just as you did before:
               var modalMarginTop = ($('#re').height() + 60) / 2;
                var modalMarginLeft = ($('#re').width() + 60) / 2;
                $('#re').css({
                    'margin-top' : -modalMarginTop,
                    'margin-left' : -modalMarginLeft
                });
  9. Add the code that will fade in the modal window:
                $('#re').fadeIn().prepend('<a href="#" class="close_error"><img src="grfx/close_button.png" class="close_button" title="Close Window" alt="Close" /></a>');
  10. Provide a method to close the modal window containing the error warning:
               $('a.close_error').live('click', function() {
                    $('#re').fadeOut(function() {
                        $('a.close_error, #re').remove();
                    });
                });
  11. If no error was returned, fade out the registration window and clear the form:
           } else {
                $('#registerWindow, #modalShade').fadeOut(function() {
                    $('#registerForm input[input*="pe"]').val('');
                });
            }
  12. Close the post method by providing the data type that you expect the PHP function to return:
        }, 'html');
    });

Logging in the User

The last step you need to do in the validation procedures is to give users a way to log in to their account.

The jQuery for the login function is nearly a duplicate of the registration, so I'll present it in its entirety:

$('#loginForm').submit(function(e){
    e.preventDefault();
    var formData = $(this).serialize();
    $.post('inc/peRegister.php', formData, function(data) {
        var returnValue = data;
        if(1 == returnValue){
            $('#loginWindow, #modalShade').fadeOut(function() {
                $('#loginForm input[name*="pe"]').val('');
                window.location = "4-2.php";
            });
        } else {
            $('body').append('<div id="li" class="errorModal"><h3>There is an error with your login</h3><p>Please try again...</div>');
            var modalMarginTop = ($('#li').height() + 60) / 2;
            var modalMarginLeft = ($('#li').width() + 60) / 2;
            $('#li').css({
                'margin-top' : -modalMarginTop,
                'margin-left' : -modalMarginLeft
            });
            $('#li').fadeIn().prepend('<a href="#" class="close_error"><img src="grfx/close_button.png" class="close_button" title="Close Window" alt="Close" /></a>');
            $('a.close_error').live('click', function() {
                $('#li').fadeOut(function() {
                    $('a.close_error, #li').remove();
                });
            });
        }
    }, 'html');
});

If the login is successful, the browser loads chap4/4-2.php (Figure 4.5), the user's account page.

Figure 4.5

Figure 4.5 The user's account page is displayed on a successful login.

Now that you are comfortable with basic jQuery AJAX, let's move on to using the jQuery AJAX functions to update content in the browser.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020