cs304 logo

Class on Forms, JavaScript, jQuery and Ajax

Last week, we learned about MySQL and the database back-end. We also learned about ER diagrams.

Today, we'll be learning about the front-end, and having pages that

The Three-Tier Architecture

Next week, we'll learn PHP, the first kind of middle-ware that we'll be learning, and we'll finally have the entire process complete.

Goal

By the end of today, you will be able to:

Plan

  1. I'll distribute solutions to the first homework. Please don't take one if you are turning the assignment in later.
  2. We'll review ER diagrams and do an exercise on it, so you're prepared for the next homework.
  3. We'll do a brief exercise on the conventional form submission protocol
  4. I'll answer your questions from the Sakai quiz
  5. We'll do some exercises with Ajax form submission and response processing. I expect that we'll complete this next time. If you're new to JS and JQ, I urge you to partner with someone who is familiar with them, but then you sit at the keyboard!

ER Diagrams

Remember, ER diagrams

Exercise on Professors and Courses

For the following, assume we have (at least) two tables:

Prof (SSN,Name) Teaches Course(Dept,Number,Title)

Sketch the ER diagram you would want and the corresponding tables.

  1. Profs can teach the same course in several semesters, and only most recent offering is recorded
  2. Profs can teach the same course in several semesters, and each offering is recorded
  3. Every Prof teaches something
  4. Every Prof teaches exactly one course
  5. Every Prof teaches exactly one course and every course is taught by someone
  6. certain courses are team taught.

Here's my solution:

ER diagram of Professors
  teach Courses

How would you modify this for the other situations?

Forms

Forms are the conventional way to (1) trigger a script by the back end, and (2) send data to that back end.

Old-School versus Ajax

But this is so old fashioned! Why not eschew this with the modern Ajax methods that are newer and shinier?

Form Submission Methods

Forms have two submission methods, choses by the METHOD attribute of the FORM tag. They are

What's the difference? What are the Pros and Cons of GET and POST? Working with a partner, find 3-4 answers; we'll discuss.

My answers:

Example: Bleats

As our first example, we will have a database of Brief Lexical Emissions And Transmissions or BLEATS.

Exercise 1: A Form to Submit a Bleat

Create your own form to submit a bleat. It should not use the GET method. You can make it pretty if you like, but don't spend too much time on that.

Try using https://cs.wellesley.edu/~cs304/php/bleats/insert-bleat-ajax.php as the action. What happens?

Note: You can work locally on your own laptop or classroom Mac for all the exercises today, because we will be working on the front-end (browser). In later classes, we'll work on the back-end by logging into Tempest.

Here's my solution:

form1.html Notice the URL when you submit (the form uses POST) and notice the response.

Using Ajax Instead

When we used insert-bleat-ajax.php, we saw that the result was not at all what we expected. It wasn't a web page, it was some JSON code.

With Ajax, we have two steps:

Let's do these in order.

Submitting Form Data using jQuery

The jQuery library makes Ajax much easier. The essential is using one of the following:

The data to send is not necessarily easy to do. You know what it looks like with the GET method; it looks the same with the POST method. This is called serializing a form. Here's a useful method:

Unless you are doing something fancy, it's easiest just to serialize the whole form, as the jQuery documentation suggests.

jQuery Demo

I'll demonstrate the following for you, using our add bleat form.

  1. Loading the jQuery library.
  2. Serializing the form
  3. Making an Ajax request (form submission)
  4. Adding an event handler to a button

Next, you'll put this together as an exercise.

Exercise 2: Bleating via Ajax

Create your own form to submit a bleat via Ajax.

  1. You can adapt your previous one.
  2. Remember to add a script tag to load the jQuery library. This URL works nicely:
    //ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js

    (Omitting the HTTP/HTTPS allows either.)

  3. Load jQuery at the end of the body. Put your code after that.
  4. Use this link to see the current bleats to see if your code is working.

Here's my solution:

ajax1.html We'll take a minute to look at my solution. Does my solution work if there is more than one form on the page?

Here's a version with progressive enhancement: ajax1a.html

Event Handler for Success Callback

We've used the .get() and .post() methods with two arguments, the url and the data. It's time to add a third argument, the success handler, which is a kind of event handler.

Note that jQuery will sometimes be clever and allow you to omit arguments, so the ordinal numbers may be off. See their examples:

Exercise 3: Ajax Bleating with Acknowledgement

  1. Modify your previous form to insert or reveal the words "success," when the acknowledgement is received from the server.
  2. I strongly suggest you start with something simple like a console.log or alert message. Then work on the success notice. You can even work on the success notice as a separate function and debug it without having to do more bleats.
  3. As before, you can use this link to see the current bleats to see if your code is working.
  4. For an extra, optional challenge, cause the words to fade out after 10 seconds.

Here's my solution:

ajax2.html. We'll take a minute to look at the reportSuccess function and how to experiment with it using the JavaScript console.

The Document as a Dynamic Tree

When we write out HTML, we think of the web page as a static piece of text, just as an HTML file is. However, via JavaScript, a web page can be dynamic. The API between JavaScript and the browser, allowing JS to modify the document, is called the Document Object Model or DOM. The dynamic document itself is also called the DOM.

The jQuery library makes modifying the DOM easier with a ton of manipulation methods.

This just scratches the surface of what jQuery lets you do quite easily. My goal is not to teach you all of this, but to get you started learning it as needed.

Processing a Response

The next step is to process the response from the server, which in this case we know is:

Therefore, we can iterate over that list, inserting each into the document.

Exercise 4: Ajax Bleating with Updates

  1. Modify your previous form to insert the response from our insertion, namely the latest bleats
  2. As a debugging technique, I strongly suggest that you save the bleats to a global variable and then write a function to operate on a list as its argument. You can use the global variable many times while debugging the function.
  3. There are lots of ways to do this, but I recommend keeping it simple:
    1. Create an unattached list item
    2. Set the text of the list item to the concatenation of the bleat id, the number of likes, and the bleat text
    3. Append the list item to an OL or UL that is already attached to the DOM.
  4. The suggestion above results in the page re-rendering up to 30 times. An improvement is to append each unattached list item onto an unattached list, and then attach the list to the DOM when you're done.
  5. As before, you can use this link to see the current bleats to see if your code is working.
  6. For extra credit, use the list-bleats-ajax.php script to load a list of current bleats when the page loads.
  7. If you're really ahead, you can nicely format the bleats using CSS.

Here's my solution:

ajax3.html. We'll take a minute to look at the showBleats function and how to experiment with it using the JavaScript console.

Adding Event Handlers

We can also make a page dynamic via event handlers

Liking Bleats

Let's see this in action. Here's a partial view of the DOM for this document:

liking a bleat via event bubbling to an event handler
  1. The user clicks on a bleat (an LI). That's the event target.
  2. The click bubbles up
  3. The event handler at the DIV handles it

How to Implement Liking

First, we need some kind of API (via a GET/POST form) to like a bleat. That's done with the following URL:

https://cs.wellesley.edu/~cs304/php/like-bleat-ajax.php

Supply a bid=nn pair, where NN is the number of the bleat ID, and the web app will increment the likes for that bleat.

Coding is best and most successful when we can code and test small units, so before we add an event handler to like any of an arbitrary list of bleats, let's first write code to like a particular bleat.

Exercise 5: Function to like a Bleat

  1. Modify your previous web app to implement a function that, when given a bleat id (bid), sends an Ajax-request to the server to increment the likes on that bleat.
  2. You can always use bids 1, 2, and 3; those never expire.
  3. The response will be a list of bleats, justs like inserting a bleat does.
  4. Your function could also insert that onto the page.
  5. You can test your function by hand using the JS console.
  6. As before, you can use this link to see the current bleats to see if your code is working.

Here's my solution:

ajax4.html. We'll take a minute to look at the likeBleat function and how to experiment with it using the JavaScript console.

How to Implement Liking, Part 2

As we saw from the picture, earlier, we need to do the following:

  1. Make sure each bleat knows its BID via a data- attribute
  2. Attach an event handler on an ancestor of all the bleats
  3. The event handler should use the event target to determine the element that was clicked on, and via that, the BID.
  4. It then uses our earlier function to like the bleat.

Exercise 6: A Web App that Implements "Likes"

  1. Modify your previous web app to complete the implementation of likes, using the steps outlined above.
  2. Modify your display of the bleats so that each gets a data-bid attribute. You can use the jQuery .attr() method to set/get attributes.
  3. Use console.log liberally in order to check what you're doing.
  4. As before, you can use this link to see the current bleats to see if your code is working.

Here's my solution:

ajax5.html. We'll take a minute to look at the solution.

Summary

We've come a long way! We learned

We also managed to build a little application to submit and like bleats.