13. PHP and Ajax

What We Will Cover


Elucidations

Questions from last class?

Questions on the project?

13.1: Forms and PHP

Learner Outcomes

At the end of the lesson the student will be able to:

  • Pass data from HTML forms to PHP scripts
  • Use PHP functions to examine the form data
  • Save data in PHP variables for processing
  • Acquire data from multiple-valued form elements

13.1.1: Coding Forms for PHP Processing

  • Recall that you construct a form using the syntax:
    <form attributes>
        page elements
    </form>
    
  • Where the attributes control how the form is processed
  • Inside the form tags you include various control elements and other page elements such as tables, paragraphs and headings
  • Some important form attributes for PHP include:
    • action: specifies the URL where the form sends the data for processing
    • method: specifies how to send the information
      • The get method appends the information to the URL
      • The post method sends the data within the body of the request
  • For example:
    <form action="formecho.php" method="get">
    </form>
    

Input Elements

  • Most form controls in which users enter data are marked with an input element
  • Syntax of an input element with the key attributes required for PHP:
    <input type="type" name="name">
    
  • Where type is one of the 10 types and name is the identifier for the element
  • The name attribute is required for processing the data using PHP
  • HTML has 10 different input types as shown in the following table
  • Each of them has various attributes that specify their behavior
  • You can view the source to see how some of the attributes are used

Input Types

Type Description Example
type="button" Display a button to perform an action from a script
type="checkbox" Display a check box
type="file" Display a control to locate and select a file
type="hidden" Create a hidden field not viewable in the form
type="image" Display an inline image that can be clicked to submit data
type="password" Display an input box that hides text entered by the user
type="radio" Display an option (radio) button
type="reset" Display a button to clear the form data when clicked
type="submit" Display a button to submit the form data when clicked
type="text" Display an input box that displays text entered by the user

Other Form Elements

  • Forms have other ways for users to enter data
  • These include the text area, which has the syntax:
    <textarea name="name" rows="value" cols="value">
    default text
    </textarea>
    
  • For example, this code produces the text area that follows:

    <textarea name="comments" rows="3" cols="50">
    Your comments here
    </textarea>

  • The name attribute is required for processing the data using PHP
  • Another commonly used form element is the selection list, which we discuss later

13.1.2: Acquiring Form Data in PHP Scripts

  • PHP makes it easy to acquire input data from forms
  • For instance, given the following input element:
    <input type="text" name="fname">
  • We use $_REQUEST with square brackets and the element name like this:
    $firstName = $_REQUEST["fname"];
    print "firstName: $firstName";
    
  • If you only want to accept data passed using the GET method, use $_GET instead:
    $firstName = $_GET["fname"];
    print "firstName: $firstName";
    
  • If you only want to accept data passed using the POST method, use $_POST instead:
    $firstName = $_POST["fname"];
    print "firstName: $firstName";
    
  • These arrays are known as "autoglobals" or "superglobals" because they are automatically global throughout your PHP page

Superglobal Arrays Used with Forms

Array Description
$_GET Access to variables passed via the HTTP GET method.
$_POST Access to variables passed via the HTTP POST method.
$_REQUEST Access to variables passed via both the HTTP GET and POST methods.

13.1.3: Examining Form Data

  • Let us look at an example of form processing using PHP
  • In the form below we include the important attributes for PHP:
    • action: specifies the URL where the form sends the data for processing
    • method: specifies how to send the information
    • name: specifies the name for each form element
    • value: specifies the value for some types of form elements
  • Following form is the script for reading the form data
  • To read the data, the script uses the $_REQUEST array
  • To help debug forms and other data, PHP provides two functions you can use:
    • print_r(): prints a compact form of data about a variable
    • var_dump(): prints detailed information about a variable
  • The script displays the $_REQUEST array using both print_r() and var_dump()
  • The data from the functions is displayed inside of preformatted text elements
  • The pre-tags make the data more readable in a Web page
  • Following these functions are data extracted into single variables
  • Also, the script displays the variables
  • You can view the form here: Simple Input Form

Example Form for PHP Processing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Simple Input Form</title>
</head>

<body onload='document.forms[0].elements[0].focus();'>
<h2>Simple Input Form</h2>
<form method="get" action="formecho.php">
<table border="0" cellspacing="0" cellpadding="5">

<tr>
<td>First Name:</td>
<td><input type="text" name="fname"></td>
</tr>

<tr>
<td>Last Name:</td>
<td><input type="text" name="lname"></td>
</tr>

<tr>
<td class="label">State:</td>
<td>
<input type="radio" name="state" id="s1" value="CA">
<label for="s1">California</label><br>
<input type="radio" name="state" id="s2" value="OR">
<label for="s2">Oregon</label><br>
<input type="radio" name="state" id="s3" value="WA">
<label for="s3">Washington</label>
</td>
</tr>

<tr>
<td class="label">&nbsp;</td>
<td>
<input type="submit" name="submit" value="Send Data">
</td>
</tr>

</table>
</form>

</body>
</html>

Example Script Reading the Form Data

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Form Echo</title>
</head>

<body>
<h2>Form Echo</h2>
<h3>Data Using <code>print_r()</code></h3>
<pre><?php print_r($_REQUEST); ?></pre>

<h3>Data Using <code>var_dump()</code></h3>
<pre><?php var_dump($_REQUEST); ?></pre>

<h3>Data into Single Variables</h3>
<?php
$firstName 
$_REQUEST["fname"];
$lastName $_REQUEST["lname"];
$state $_REQUEST["state"];
$submit $_REQUEST["submit"];

print 
"firstName: $firstName<br>";
print 
"lastName: $lastName<br>";
print 
"state: $state<br>";
print 
"submit: $submit";
?>
</pre>
</body>
</html>

13.1.4: Using the if-else Statement

  • Like JavaScript, you can use an if-else statement to choose between two alternatives based on a test
  • A test is some expression that evaluates to true or false
  • If a test evaluates to true
    • then execute some commands
  • Otherwise it is false
    • so execute other commands
  • The syntax of the if-else statement:
    if (test) {
        statements to execute only if true
    } else {
        statements to execute only if false
    }
    
  • As an example, we can code an if-else statement like this:
    if ($_REQUEST["guess"] == 7) {
        print "<p>*** Correct! ***</p>\n";
    } else {
        print "<p>Sorry, that is not correct.</p>\n";
    }
    
  • As with JavaScript, the else clause is optional
  • For clarity, if and else are written on different lines than the nested statements
  • Also, you indent the statements nested inside the curly braces
  • For an example using an if-else statement, we will write a simple guessing game application
  • We collect a guess from the player with the simple form shown below
  • We then evaluate the form with the test script
  • You can play the game yourself by clicking: Guessing Game

Form Collecting the Players Guess

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Guessing Game</title>
</head>

<body onload='document.forms[0].elements[0].focus();'>
<h2>Guessing Game</h2>
<p>I'm thinking of a number between 1 and 10.<p>
<p>Can you guess it?</p>

<form action="guesstest.php" method="get">
<input type="text" name="guess"><br><br>
<input type="submit" name="submit" value="Check Guess">
<input type="reset" value="Reset">
</form>

</body>
</html>

Script Processing the Form Data

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Guessing Game Response</title>
</head>
<body>
<?php
if ($_REQUEST["guess"] == 7) {
    print 
"<p>*** Correct! ***</p>\n";
    print 
'<a href="guessform.html">Play again</a>';
} else {
    print 
"<p>Sorry, that is not correct.</p>\n";
    print 
'<a href="guessform.html">Guess again</a>';
}
?>
</body>
</html>

More Information

  • if: the PHP Manual
  • else: the PHP Manual

13.1.5: Using Loops

  • Just like JavaScript, loops are used to repeat sections of code
  • The while loop is the simplest loop statement with the syntax:
    while (test) {
        statements to repeat
    }
    
  • A variation on the while loop is the do-while loop:
    do {
        statements to repeat
    } while (test);
    
  • By checking the condition at the end of the loop, the statements to repeat are guaranteed to execute at least one time
  • A more compact repetition statement is the for loop:
    for (start; test; update) {
       statements to repeat
    }
    
  • The following example shows the use of a loop to repeat statements
  • We collect a phrase and amount from the player with the simple form shown below
  • We then process the form with the test script
  • You can try the example yourself by clicking: Repeat After Me

Form Collecting the Repeat Input

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Repeat After Me</title>
</head>

<body onload='document.forms[0].elements[0].focus();'>
<h2>Repeat After Me</h2>
<p>Enter a phrase to repeat and the number of times to
repeat it.</p>

<form action="repeattest.php" method="get">
<label for="phrase">Phrase to repeat: </label>
<input type="text" id="phrase" name="phrase"><br><br>
<label for="amount">Number of repeats: </label>
<input type="text" id="amount" name="amount"><br><br>
<input type="submit" name="submit" value="Repeat">
<input type="reset" value="Reset">
</form>

</body>
</html>

Script Processing the Form Data

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Repeating Phrase</title>
</head>
<body>
<?php
$phrase 
$_REQUEST["phrase"];
$amount $_REQUEST["amount"];

if (isset(
$phrase)) {
    for (
$i 0$i $amount$i++) {
        print (
$i 1).": $phrase<br>\n";
    }
}
?>
</body>
</html>

Using isset()

  • Note the use of the function isset()
  • Function isset() tests whether on not a variable exists
  • This function is sometimes useful when dealing with forms
  • Sometimes form elements do not send a value to the server unless the user chooses a value

More Information

13.1.6: Summary

  • In this section we looked at how you can use forms with PHP
  • Each form control element must have a name assigned to be read by PHP
  • PHP can read the form data using the superglobal array $_REQUEST, $_POST or $_GET
  • For instance, given the following input element:
    <input type="text" name="fname">
  • We use $_REQUEST with square brackets and the element name like this:
    $firstName = $_REQUEST["fname"];
    print "firstName: $firstName";
    
  • You can view the data passed from a form using either:
    • print_r(): prints a compact form of data about a variable
    • var_dump(): prints detailed information about a variable
  • For example:
    print_r($_REQUEST);
  • We looked at the if-else control statement for making decisions
  • In addition, we looked at using loops

Check Yourself

  1. What attribute must a form control element contain to be read by PHP?
  2. What PHP code can you use to read a form element named "lname"?
  3. What PHP functions can you use to view all the values of a form?
  4. How does the if-else statement compare between PHP and JavaScript?
  5. How do loops compare between PHP and JavaScript?

Activity 13.1

Take one minute to read over the Review Questions in the textbook. We will discuss the questions as time permits.

13.2: Introduction to Ajax

Learner Outcomes

At the end of the lesson the student will be able to:

  • Define Ajax and describe its key technologies
  • Discuss the advantages of using Ajax
  • Describe how to make an asynchronous request

13.2.1: Responsive Web Applications

  • Web applications like Amazon or Google have some advantages over desktop applications like Excel:
    • Easy to install - all you need is a Web browser
    • You can reach a large audience quickly
    • Updates are easier to deploy
  • However, classical web applications have some disadvantages for the user
  • Every page request requires a trip to the server and a new page load
  • This request and reload cycle causes a delay in the user's interaction with the application
  • This "click and wait" cycle makes web applications less responsive than desktop applications

Introducing Ajax

  • Ajax (Asynchronous Javascript and XML), or AJAX, is a technique for creating interactive web applications
  • The Ajax technique is to exchange small amounts of data with the web server and avoid reloading an entire page
  • By requesting and reloading data in the background, you can increase a web page's interactivity, functionality and usability
  • You can see a comparison of a "classic web application" with Ajax in the following diagram (from adaptivepath.com)

Comparison of a Classic Web Application with Ajax

Classic web app vs Ajax

More Information

13.2.2: Ajax Technologies and Examples

  • Like DHTML, Ajax is not a technology itself but rather a term that refers to a group of technologies
  • Ajax usually uses a combination of these technologies:
    • HTML or XHTML: for markup
    • CSS: for styling
    • The DOM accessed with JavaScript: to dynamically interact with the page
    • The XMLHttpRequest object: to exchange data with the server
    • XML: sometimes used as a format for exchanging data
  • XML is not required and any data format will work for transferring data including plain text and HTML
  • The core or defining element of Ajax is the XMLHttpRequest object
  • This object gives browsers the ability to exchange data with the server without reloading a web page
  • In some situations and frameworks, an IFrame may be used for exchanging data instead of the XMLHttpRequest object

Examples of Ajax in Action

  • Autocompletion: the words for specific parts of a form may be suggested automatically as the user types. For example: Google Suggest
  • Mashups: Combining data from various sources on an HTML page. For example: Virtual Video Map combines Google Maps with YouTube videos.
  • Real-time form validation: verify some or all form data before the user submits the form. For instance, you may want to determine if a user name is already taken when creating an online account.
  • Rich user controls: trees, menus, data tables, and other widgets allow for better interaction between the user and web pages. For example: iGoogle

Ajax Problems

  • Broken back button: dynamically updated pages do not register with the browser history; thus the back button may not work as the user expects.
  • Broken book marks: dynamic page content means the user cannot bookmark a particular state of a page
  • Response time: Feedback needs to be given to the user during data requests in case of network latency
  • JavaScript support: users may turn off JavaScript or browsers such as Lynx may not support JavaScript
  • More information: Ajax Mistakes
  • As a developer, you must develop solutions for these issues

13.2.3: Making Asynchronous Server Requests

  • With classic web applications, you must send a request to the server using a form or hyperlink
  • The user must click a button or link to make the request
  • Once the server receives the request, it generates a response as a complete HTML page
  • Once the browser receives the response, it displays a new web page
  • With Ajax, you use JavaScript to communicate directly with the server using an XMLHttpRequest object
  • The application can make a request and receive a response asynchronously without reloading the page
  • The request and response sequence is described below

Ajax Request and Response Sequence

Classic web app vs Ajax

  1. When a user generates an event on the client, it calls a JavaScript function in the client.
  2. The JavaScript function creates and configures a JavaScript object that is used to exchange data between the client and web server.
  3. The server processes the data and returns a response, sometimes in XML format, although other formats can be used.
  4. The callback function processes the response and updates what the user sees on the page based on the new data.

13.2.4: Studying the XMLHttpRequest Object

  • For the browser to make asynchronous requests we use the XMLHttpRequest object
  • The original XMLHttpRequest object was developed by Microsoft and introduced in IE 5.0 as an ActiveX object called XMLHTTP
  • Since then the XMLHttpRequest object has been standardized by the W3C and is supported by most modern browsers:
    • Internet Explorer 5.0+
    • Firefox 1.0+
    • Mozilla 1.0+
    • Safari 1.2+
    • Opera 8.0+
  • IE 7 supports the W3C standard but we must use the ActiveX implementation for earlier versions
  • You can see the important features of the XMLHttpRequest object in the tables below

Some XMLHttpRequest Attributes and Properties

Attribute/Property Description
onreadystatechange Event handler that is invoked every time a readystatechange event occurs.
readyState Returns the value of the current state.
status Contains the HTTP status code sent by the server.
statusText Contains the HTTP status message sent by the server.
responseText Contains the text returned from the server after completing the request.
responseXml Contains the XML returned from the server after completing the request.

Some XMLHttpRequest Methods

Method Description
open(method, url, async) Sets the parameters for the request where method is usually GET or POST, url is the URL of the request, and async is true for asynchronous requests and false for synchronous requests.
setRequestHeader( header, value) Set request headers and values. Typically used to set the Content-Type header before calling the send() method.
send(data) Initiates the request and the optional data argument provides the entity body.

More Information

13.2.5: Getting Server Content

  • Let us prepare an application that we can develop into an Ajax application
  • We will start with the following simple form
  • The form contains a single input field and a button
  • When the user presses the form button, the form information will be sent to the server
  • Then the server will return some information which we will display
  • You can try the form yourself by clicking: Get Content
  • Notice that a new page loads when the server returns its information
  • After developing the Ajax, we will display the returned information without reloading the page

Get Content Form (version 1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Get Content</title>
</head>

<body onload='document.forms[0].elements[0].focus();'>
<h1>Get Content</h1>
<form action="getcontent.php" method="post"
  name="getContentForm">
<p>
<input type="text" size="25" name="args">
<br>
<input type="submit" name="button" value="Get Content">
</p>
</form>

</body>
</html>

PHP Script Returning the Content

1
2
3
4
5
6
7
8
9
<?php
sleep(2); // delay 2 seconds to simulate lag
print "Ajax rocks!";
if (isset($_REQUEST["args"])) {
    print '<br>Argument received:
        <span style="color: red">'
        .$_REQUEST['args'].'</span>';
}
?>

13.2.6: Ajax Step by Step

  • In this section we build a function to retrieve data using Ajax
  • We start by writing the header of a function to get the content:
    function getData() {
        // more code here
    }
    
  • In addition, we add an onsubmit handler to the form:
    <form action="" method="post" name="getContentForm"
      onsubmit="getData(); return false;">
    
  • Since we do not want the form to load another page, we remove the URL from the action attribute and have the onsubmit handler return false
  • Also, we add a div to the form to display the returned content:
    <div id="output"></div>
    
  • We can write text to this div using an output() function:
    function output(text) {
        var myDiv = document.getElementById("output");
        myDiv.innerHTML = text;
    }
    
  • Note the use of the innerHTML property
  • Most DOM elements support this property as an easy way to assign any text to an element

1. Constructing the XMLHttpRequest Object

  • Our first step, after setting up the form, is to construct the XMLHttpRequest object
  • We can support most modern browsers using the following cross-browser script:
    var req;
    if (window.XMLHttpRequest){
        // IE7, Firefox, Mozilla, Safari, etc.
        req = new XMLHttpRequest()
    } else if (window.ActiveXObject){
        // Use ActiveX for IE5.x and IE6
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    

2. Setting up the Response

  • The next step in using Ajax is to set up a function to take an action when we get a response from the server
  • We monitor our response through the onreadystatechange attribute of the XMLHttpRequest object
  • When a request is made, the XMLHttpRequest object goes through five states with these numbers:
    1. UNSENT: the initial state after the object is constructed
    2. OPENED: the open() method has been successfully invoked
    3. HEADERS_RECEIVED: all response headers have been received
    4. LOADING: the response entity body is being received
    5. DONE: the data transfer has been completed or something went wrong during the transfer
  • Each time the state changes, a readystatechange event fires
  • We use the onreadystatechange event handler to monitor the request
  • To process the event we assign a function to the handler which reacts to the states as needed:
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                if (request.responseText){
                    output(request.responseText);
                }
            } else {
                alert("Error code: " + request.status);
            }
        } else if (request.readyState == 1) {
            output("Retrieving data...");
        }
    };
    
  • JavaScript lets you assign a function to an event handler
  • Assigning this way calls the function when an event occurs
  • Note that we are assigning an unnamed (anonymous) function to the event handler
  • Since only the event handler needs to call the function, there is no need for a name
  • The function assigned to an event is known as a callback function
  • A callback function is called when something happens
  • In this case, the callback function is called when the readystagechange event occurs

3. Making the Request

  • When the response is set up, we are ready to make the request
  • The following code shows the sequence to follow:
    myUrl = "getcontent.php";
    var args = document.getContentForm.args.value;
    if (args) {
        args = "args=" + args;
    }
    request.open("POST", myUrl, true);
    request.setRequestHeader("Content-Type",
        "application/x-www-form-urlencoded");
    request.send(args);
    
  • The setRequestHeader() method call allows us to send our data to PHP as application/x-www-form-urlencoded
  • We call this method because we are not actually submitting the form data
  • You can see the entire page listed below
  • Also, you can try the Ajax version of the form yourself by clicking: Get Content

Get Content Form with Ajax Requests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Get Content</title>
<script type="text/javascript">
function getData() {
    // Create the request object
    var request;
    if (window.XMLHttpRequest){
        // IE7, Firefox, Mozilla, Safari, etc.
        request = new XMLHttpRequest()
    } else if (window.ActiveXObject){
        // Use ActiveX for IE5.x and IE6
        request=new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("This browser does not support Ajax");
        return false;
    }

    // Set up the response
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                if (request.responseText){
                    output(request.responseText);
                }
            } else {
                alert("Error code: " + request.status);
            }
        } else if (request.readyState == 1) {
            output("Retrieving data...");
        }
    };

    // Make the request
    myUrl = "getcontent.php";
    var args = document.getContentForm.args.value;
    if (args) {
        args = "args=" + args;
    }
    request.open("POST", myUrl, true);
    request.setRequestHeader("Content-Type",
        "application/x-www-form-urlencoded");
    request.send(args);
}

function output(text) {
    var myDiv = document.getElementById("output");
    myDiv.innerHTML = text;
}
</script>
</head>

<body onload='document.forms[0].elements[0].focus();'>
<h1>Get Content</h1>
<form action="" method="post" name="getContentForm"
  onsubmit="getData(); return false;">
<p>
<input type="text" size="25" name="args">
<br>
<input type="submit" name="button" value="Get Content">
</p>
</form>

<div id="output"></div>
</body>
</html>

More Information

13.2.7: Summary

  • In this section we discussed Ajax and why you might want to use it in your Web pages
  • The Ajax technique is to exchange small amounts of data with the web server and avoid reloading an entire page
  • By requesting and reloading data in the background, you can increase a web page's interactivity, functionality and usability
  • Like DHTML, Ajax is not a technology itself but rather a term that refers to a group of technologies
  • Ajax usually uses a combination of these technologies:
    • HTML or XHTML: for markup
    • CSS: for styling
    • The DOM accessed with JavaScript: to dynamically interact with the page
    • The XMLHttpRequest object: to exchange data with the server
    • XML: sometimes used as a format for exchanging data
  • XML is not required and any data format will work for transferring data including plain text and HTML
  • The core or defining element of Ajax is the XMLHttpRequest object
  • This object gives browsers the ability to exchange data with the server without reloading a web page
  • We developed an example Ajax application that retrieved data from a server without reloading the entire page.

Check Yourself

  1. What is Ajax?
  2. Why is Ajax useful?
  3. What technologies are often used in Ajax?
  4. What JavaScript object is used by Ajax to communicate with the server?
  5. What are some typical uses for Ajax?
  6. What problems does Ajax introduce?
  7. Which browsers support the XMLHttpRequest object?
  8. How do you prevent a form from submitting data?

Activity 13.2

Take one minute to read over the following Quick Quiz questions before we discuss them.

Quick Quiz

  1. Ajax applications must use XML for server responses.


  2. The XMLHttpRequest object's ___________ attribute contains the text returned by the server.


  3. The attribute can be accessed through the DOM to update an XHTML elements content without reloading the page.

13.3: Creating Ajax Applications

Learner Outcomes

At the end of the lesson the student will be able to:

  • Use an Ajax library
  • Implement several Ajax applications

13.3.1: Creating an Ajax Library

  • In this section we want to look at several way to use Ajax
  • We will be using the same Ajax code many times in these examples
  • Thus, we should first make an external library of the JavaScript code we will reuse
  • To allow us to reuse the code, we make a function that accepts different parameters
  • The parameters we need are:
    • url: The location of the requested resource.
    • args: The arguments sent to the resource.
    • callbackFunc: Function to call with returned text.
  • We place this function in an external JavaScript file so we can easily reuse it in different applications
  • You can see the file listed below
  • In addition, we change our Get Content form to use the library file
  • You can see the listing of the revised Get Content page below as well
  • Also, you can try the Ajax version of the form yourself by clicking: Get Content
  • Note that the Get Content page still needs two functions:
    • One to set up the call to the loadText() function
    • The callback function to do something with the returned data

Reusable Ajax Function in File: ajax.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
    Requests text from the server at the specified URL
    by sending args and forwarding the returned text
    to the callBackFunction.

    @param url The location of the requested resource.
    @param args The arguments sent to the resource.
    @param callbackFunc Function to call with the
        returned data.
*/
function loadData(url, args, callbackFunc) {
    // Create the request object
    var request;
    if (window.XMLHttpRequest){
        // IE7, Firefox, Mozilla, Safari, etc.
        request = new XMLHttpRequest()
    } else if (window.ActiveXObject){
        // Use ActiveX for IE5.x and IE6
        request = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Browser does not support Ajax");
        return;
    }

    // Set up the response
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                if (request.responseText) {
                    callbackFunc(request.responseText);
                } else if (request.responseXML) {
                    callBackFunc(request.responseXML);
                }
            } else {
                alert("Error code: " + request.status);
            }
        }
    }

    // Make the request
    request.open("POST", url, true);
    request.setRequestHeader("Content-Type",
        "application/x-www-form-urlencoded");
    request.send(args);
}

Get Content Form Using the ajax.js Library

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Get Content</title>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function getText() {
    myUrl = "getcontent.php";

    var args = document.getContentForm.args.value;
    if (args) {
        args = "args=" + args;
    }
    output("Retrieving data...");
    loadData(myUrl, args, output);
}

function output(text) {
    var myDiv = document.getElementById("output");
    myDiv.innerHTML = text;
}
</script>
</head>

<body onload='document.forms[0].elements[0].focus();'>
<h1>Get Content</h1>
<form action="" method="post" name="getContentForm"
  onsubmit="getText(); return false;">
<p>
<input type="text" size="25" name="args">
<br>
<input type="submit" name="button" value="Get Content">
</p>
</form>

<div id="output"></div>
</body>
</html>

13.3.2: Making Suggestions

  • Recall the autocompletion and suggestion shown in Google Suggest
  • Let us look at how you can implement similar functionality using Ajax
  • The key to this feature is the event handler: onkeyup
  • The onkeyup event handler get called when the user releases a keyboard key
  • When the onkeyup event handler gets called, we make the Ajax request for a suggestion
  • The suggestions script shown here is very simple so you can see how it works
  • You can try the Ajax version of the form yourself by clicking: Make Suggestions

Suggestion Form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Make Suggestions</title>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function makeSuggestion(args) {
    myUrl = "ajaxsuggest.php";

    if (args) {
        args = "args=" + args;
    }
    loadData(myUrl, args, output);
}

function output(text) {
    var myDiv = document.getElementById("output");
    myDiv.innerHTML = text;
}
</script>
</head>

<body onload='document.getElementById("fruit").focus();'>
<h1>Suggest a Fruit</h1>
<p>Enter fruit name:
<input type="text" size="25" id="fruit" name="fruit"
  onkeyup="makeSuggestion(this.value)">
</p>

<p><span id="output">Suggestion made here</span></p>
</body>
</html>

Suggestion PHP File

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
if (isset($_REQUEST["args"])) {
    $fruit = strtolower($_REQUEST["args"]);
    $fruit = substr($fruit, 0, 1);
    if ($fruit == "a") {
        print "A is for apple";
    } else if ($fruit == "b") {
        print "B is for bananna";
    } else if ($fruit == "c") {
        print "C is for cherries";
    }
}
?>

13.3.3: Looking Up Zip Codes

  • In this example we lookup the city and state using a zip code
  • Once the user enters a zip code, and moves to the next field, the form fills in the city and state
  • The key to this example is the event handler: onblur
  • When the user leaves the zip field, we send the server the zip code
  • The server returns two values so we separate them before assigning them to the city and state fields
  • Note that data such as this is normally looked up in a database on the server
    • You can learn how to use databases and PHP in the course: CIS-165PH
    • It takes a few weeks to learn these skills
  • Instead, for this example, we simulate the database for a few places in our local area
  • You can try the Ajax version of the form yourself by clicking: Lookup Zip Code

Zip Code Lookup Page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Lookup Zip Code</title>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function getZip(zip) {
    myUrl = "ajaxzip.php";

    if (zip) {
        zip = "zip=" + zip;
    }
    loadData(myUrl, zip, output);
}

function output(text) {
    if(text.indexOf('|' != -1)) {
        update = text.split('|');
        document.getElementById("city").value = update[0];
        document.getElementById("state").value = update[1];
    }
}
</script>
</head>

<body onload='document.getElementById("zip").focus();'>
<h1>Lookup Zip Code</h1>
<table>
<tr>
  <td>Enter Zip Code:</td>
  <td><input type="text" id="zip" name="zip"
    onblur="getZip(this.value);"></td>
</tr>
<tr>
  <td>City:</td>
  <td><input type="text" id="city" name="city"></td>
</tr>
<tr>
  <td>State:</td>
  <td><input type="text" id="state" name="state"></td>
</tr>
</table>
</body>
</html>

Zip Code Lookup PHP File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
// Normally this is a database lookup
// as taught in CIS-165PH
if (isset($_REQUEST["zip"])) {
    $zip = $_REQUEST["zip"];
    if ($zip == "95001" || $zip == "95003") {
        print "Aptos|CA";
    } else if ($zip == "95005") {
        print "Ben Lomond|CA";
    } else if ($zip == "95006") {
        print "Boulder Creek|CA";
    } else if ($zip == "95007") {
        print "Brookdale|CA";
    } else if ($zip == "95060" || $zip == "95061"
            || $zip == "95062" || $zip == "95063"
            || $zip == "95064" || $zip == "95065") {
        print "Santa Cruz|CA";
    } else if ($zip == "95066" || $zip == "95067") {
        print "Scotts Valley|CA";
    } else if ($zip == "95073") {
        print "Soquel|CA";
    } else if ($zip == "95076" || $zip == "95077") {
        print "Watsonville|CA";
    }
}
?>

13.3.4: Getting Stock Prices

  • For security reason, the XMLHttpRequest can only request resources from the domain that served the page
  • Thus, the web page and server-side script must reside on the same web server
  • This is commonly known as the same origin policy (SOP)
  • SOP helps to close a vulnerability called cross-site scripting (XSS)
  • Cross-site scripting allows an attacker to compromise a web site's security by injecting a malicious script onto the page from another domain
  • To get content from another domain securely, we implement a server-side script to make requests on other domains
  • The following PHP script looks up stock quotes from www.amex.com
  • The script performs this task by forming a request URL and loading the page
  • Then the script searches the page using regular expressions to find desired pattern of a stock quote
  • Extracting information from web pages is known as "screen scraping"
  • Another feature of this example is the use of a small CSS "window"
  • You can try the application yourself by clicking: Latest Stock Quotes

Stock Quote Lookup Page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Latest Stock Quotes</title>
<style type="text/css">
#output {
    position:absolute;
    top:-5em;
    left:0em;
    height:10em;
    width:35em;
    text-align:center;
    background-color:#ffffff;
    border: 4px solid #98A2C6;
    z-index:2;
}
</style>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function getQuote(symbol) {
    myUrl = "ajaxquote.php";

    if (symbol) {
        symbol = "symbol=" + symbol;
    } else {

    }
    loadData(myUrl, symbol, output);
}

function output(text) {
    text += '<a href="javascript:closeViewer();">Close Window</a>';
    var myDiv = document.getElementById("output");
    myDiv.innerHTML = text;
    myDiv.style["display"] = 'inline';
}

function closeViewer() {
    var myViewer = document.getElementById("output");
    myViewer.style["display"] = 'none';
}
</script>
</head>

<body>
<h1>Latest Stock Quotes</h1>
<input type="radio" name="stock" id="s1" value="AMZN"
  onclick="getQuote(this.value)">
<label for="s1">Amazon</label><br>
<input type="radio" name="stock" id="s2" value="MSFT"
  onclick="getQuote(this.value)">
<label for="s2">Microsoft</label><br>
<input type="radio" name="stock" id="s3" value="YHOO"
  onclick="getQuote(this.value)">
<label for="s3">Yahoo</label>

<div style="position:relative;">
  <div id="output" style="display:none;"></div>
</div>
</body>
</html>

Stock Quote Lookup PHP File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
if (isset($_REQUEST["symbol"])) {
    $symbol = $_REQUEST["symbol"];
}
if ($symbol == "AMZN" || $symbol == "MSFT"
        || $symbol == "YHOO") {
    $url = "http://www.amex.com/equities/listCmp/"
          ."EqLCDetQuote.jsp?Product_Symbol=$symbol";
    $page = file_get_contents($url);
    $pattern = "/\\\$[0-9]+\\.[0-9]+/i";
    if (preg_match($pattern, $page, $matches)) {
        echo "<p>$symbol last sold at: ";
        echo $matches[0]."\n";
    } else {
        echo "No quote available\n";
    }
    echo "<br>Information retrieved from:<br>\n"
        ."<a href=\"$url\">$url</a><br>\n"
        ."on ".(date('l jS F Y g:i a T'))."\n</p>";
}
?>

More Information

13.3.5: Summary

  • In this section we first looked at how to make a reusable Ajax library
  • The key to this library is the loadData() function:
    /**
        Requests text from the server at the specified URL
        by sending args and forwarding the returned text
        to the callBackFunction.
    
        @param url The location of the requested resource.
        @param args The arguments sent to the resource.
        @param callbackFunc Function to call with the
            returned data.
    */
    function loadData(url, args, callbackFunc)
    
  • Using this library we looked at how to implement suggestions with the onkeyup event handler
  • After releasing a key, the web application requests a suggestion from the server using the loadData() function
  • In addition, we looked at how to supply city and state information based on a zip code
  • The zip code was sent to the server using the onblur() event handler, which is called when a user leaves an input field
  • The server uses the zip code to retrieve the city and state
  • Usually, the server looks up this data in a database
  • However, using a database is beyond the scope of this course
  • Finally, we looked at an application to look up stock prices on the American Stock Exchange
  • This application was more difficult because of the same origin policy (SOP) of JavaScript
  • The SOP helps to close a vulnerability called cross-site scripting (XSS)
  • Cross-site scripting allows an attacker to compromise a web site's security by injecting a malicious script onto the page from another domain
  • To get content from another domain securely, we implemented a server-side script to make requests on other domains
  • In addition, we formatted the stock price using a small CSS window

Check Yourself

  1. Why is it a good idea to create a function for making Ajax requests?
  2. What is a callback function?
  3. For the following function that accepts a callback function, how do you pass it a function named myCallBack()?
    function callHome(callBackFunction) {...}
    
  4. When does the onkeyup() event handler get called?
  5. When does the onblur() event handler get called?
  6. What is the same origin policy (or SOP)?
  7. What style would you enter to add a 5 pixel blue border around the element named output?
  8. What style can you use to prevent a browser from displaying an object?

Activity 13.3

Take one minute to read over the following Quick Quiz questions before we discuss them.

Quick Quiz

  1. For security purposes, the XMLHttpRequest object does not allow a web application to request resources from servers other than the one that served the web application.


  2. Making a request to a different server is known as .
  3. The same origin policy (SOP)


13.4: Finishing the Course

Learner Outcomes

At the end of the lesson the student will be able to:

  • Discuss the final preparation for the project presentation
  • Advise the instructor on how to improve future courses

13.4.1: About the Final Project Presentation

Important Final Exam Information

Date and Time: 6:00 8:50 P.M. Monday, December 14
Location: Room 516 (regular classroom)

Before the Presentation

  • Submit your project to Blackboard before the presentation:
  • Bring a written report on paper to give to the instructor before the presentation

Suggested Presentation Flow

  1. State your name and your project's name.
  2. Briefly describe the purpose of your project
  3. Demonstrate and discuss each project page including:
    • Animation page
    • Form page and validation techniques used
    • Cookie pages and cookie values set and retrieved

    Feel free to refer to or display your written report during the presentation. Point out as many of the cool features as possible so we can all enjoy them.

  4. Summarize the project.

    When the demonstration is over, or your time is up, then quickly summarize the program's purpose. Then pause for about 10 seconds to give us a chance to applaud!

After the Presentation

  • Feel free to leave (or stay) after your presentation
  • You can present to the instructor alone after the other presentations are through

13.4.2: Lecture Finale

  • During the semester we have covered many topics in JavaScript
  • With this knowledge you can develop dynamic Web sites
  • We have come a long ways and your project will allow you to demonstrate what you have learned
  • I hope that everyone has enjoyed taking the course as much as I have enjoyed presenting it
  • I am always open to suggestions for improving the course

Wrap Up

Due Next:
Final Project Presentation (Mandatory Attendance) (12/14/09)

Home | Blackboard | Schedule | Room Policies | Syllabus
Help | FAQ's | HowTo's | Links

Last Updated: December 06 2009 @16:38:04