CS 120, Fall 2011, Lab 11:
JQuery and AJAX

In this lab, you will make an interactive web page that uses AJAX to communicate with programs on the server. For AJAX, you'll be using the JQuery $.post() routine that we have been discussing in class. The lab uses the same "message board" application that you worked with in Lab 9, but now you will be accessing an AJAX-enabled version.

To work with AJAX, the files for today's lab have to be in your www folder — that is, in your web portfolio. Open Aptana Studio. DO NOT CREATE A NEW PROJECT. Instead, open your web portfolio project, and create a new folder inside that project. Name the folder "lab11". Now, open the folder /classes/cs120/lab11-files in a file browser, and copy the contents of that folder into the lab11 folder that you have just created. You will working on the file named bb120.html.

Because of important JavaScript security restrictions, for a web page to use AJAX, the web page has to be loaded into a browser from the same computer that contains the server-side programs. This means that you need to access bb120.html through the math.hws.edu web server. Open Chrome, and go to the URL of your bb120.html file on the server. The URL will be of the form

     http://math.hws.edu/~zz9999/lab11/bb120.html

but with zz9999 replaced by your own user name. Do not run the file through Aptana. Instead, when you modify the file in the Aptana Editor, hit the "Reload" button in Chrome to see the new version.

The server-side programs that you will be using can be found on the server in the directory http://math.hws.edu/bb120/ajax. Open another tab in Chrome, and go to this URL. By clicking the files in that directory, you can see what the server returns in each case. For some of the files, you have to be logged in to see anything interesting (you can try that later). For other files, you won't see anything interesting unless you send some data to the server, and you won't be able to do that just by clicking on a link. (By the way, I suggest that you use Chrome rather than Firefox because Firefox won't show you the JSON objects that the server-side programs send back; instead, it will ask you to save the response to a file.)

This lab is due by 2:00 PM on the Monday before Thanksgiving.

About JQuery's $.post()

The exercises for the lab start in the next section. This first section reviews some aspects of JQuery, AJAX, and the web application that you will be working with.

We have discussed JQuery's $.post() function in class, but here is a short review. The basic format of the command is

$.post( url, dataToSend, whatToDoNext )

where dataToSend, and whatToDoNext are both optional. Here, url is the web address of the server-side program to which the data will be sent, dataToSend is a JSON object containing the data that is to be sent to the sever, and whatToDoNext is the name of a function that will be called when the response comes back from the server. The data that is received from the server will be sent to that function as a parameter. For all the programs that you will be working with in this lab, the data is sent back as a JSON object. (This is not true of all server-side programs; it's part of the protocol that I designed for this lab.)

The dataToSend can be constructed by hand, using JSON notation. For example, the data might contain two strings labeled "username" and "password". These names would typically be the names of input boxes on the page. In any case, they play the same role as the names of such boxes: That is, they tell the server what each piece of data is. A JSON object containing the data could be written as, for example,

var data = { username: "zz9999", password: "fred" };

However, often the data will come from an HTML <form>. JQuery has a nice function to get all the data from a form and make it into an object:

var data = $("#formid").serialize();

Here, the form would have id="formid", and the names of the input elements in the form would become the names of the data in the JSON object. (All of the input elements need to have names for this to work.) So a typical AJAX call with data from a form might look like this example from bb120.html:

   function doLogin() {
      var logindata = $("#loginform").serialize();
      $.post( "/bb120/ajax/login.php", logindata, loginResponse );
   }
   function loginResponse( response ) { 
      .
      .  // process the response from the server
      .
   }

And the simpler case where there is no data to send, might look like another example from that file:

   function doLogout() {
      $.post( "/bb120/ajax/logout.php", logoutResponse );
   }
   function logoutResponse( response ) {
       .
      .  // process the response from the server
      .
   }

Of course, to know how to use AJAX effectively with some web application, you have to know the exact details of the protocol that is implemented by the application. For the message board application that you will be working on in this lab, the protocol says:

  1. All data must be sent using the post method (not get, which is also supported by AJAX).
  2. Every request to the server gets a response in the form of a JSON object.
  3. Every response includes items named status and info. That is, if the response object is named response, then response.status and response.info exist.
  4. The value of response.status is always one of the strings "ok" or "error", depending on whether the request succeeded or failed.
  5. The value of response.info is a plain text string with information about the request. If response.status is "error", then response.info is an error message in a form that might be shown to the user. If response.status is "ok", then response.info usually just confirms that the request succeeded.
  6. The other data that is sent or received depends on the particular server-side program that is being contacted. (The information you need will be given below, when it is needed.)

Exercise 1: Get Some Messages

For your first exercise, you should make the page bb120.html load some messages as soon as the page is loaded. For this, you need to send an AJAX request to the program messages.php. The protocol for this program specifies:

You should call the function that sends the AJAX request as soon as the page has been loaded. That is, you can do it in a JQuery init function (or in a body onload function).

When the response is received, you should add the message HTML to the page. See the login/logout examples that already exist in bb120.html for help on how to do this. You will need to add another div to the page to hold the messages.


Exercise 2: Whoami

When the user logs in, the greeting "Welcome, Guest" changes to "Welcome, registered user." This is kind of impersonal. Make the page greet the user by name. As soon as a log in succeeds, send a request to the server-side program whoami.php. The response from this server will tell your page who has logged in. You should change the greeting in the heading to read something like, "Welcome, John Q. Doe", using the user's realname. Here is the protocol for the whoami program:

(What will you do if the user has no realname?)


Exercise 3: Posting

As soon as a login succeeds, you should also add a form to the page that the user can use for posting messages to the message board. (Or show a form that was already on the page, but invisible.) Don't forget to remove or hide the form when a logout is done.

The form should have a <textarea> named "message" where the user will enter the message. When the user posts the message, the data from the form will have to be sent to the server-side program post.php, which uses this protocol:


Exercise 4: Message Refresh

After a message posting succeeds, you should immediately send another AJAX request to the server to request a new list of messages. The new list will include the message that was just posted, as well as any other messages that have been posted by other people since the last message was sent. When the message list is received, show it on the page in place of the current list. The request should be sent to the program messages.php, whose protocol was already specified in Exercise 1.

You might also want to add a "Refresh Messages" button as a permanent part of the page. Clicking this button will get a new list of messages from the server. You should be able to call the exact same function for this that you already wrote for the first part of this exercise.


Exercise 5: Do Something Else

Add at least one more AJAX feature to the page. We will discuss some possible ideas in class. In fact, I might write a few more programs that you can use. Here are some additional server-side programs that you could use:

New Messages to get a list of messages not yet seen by the logged-in user:

Change Password to change the password of the logged-in user:

Show Profile to retrieve the profile information for a user.

Also, you should try to make the page look reasonably good. Add some CSS, at least for the list of messages!