Forms, Ajax, and Email


Goal

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

  1. Have a working PHP script that sends email to you

  2. Use jQuery to send form data to you using that script and Ajax

Recap

We learned about two major topics: Form Submission, and Form submission via Ajax.

Form Submission

  • Forms are the primary way that users send information to the server (back end), rather than receive it.
  • Even things that don't look like forms are probably just forms in disguise, such as Facebook updates.
  • Forms require:
    • a set of input elements. We've see these before in the forms reading.
    • each input must have a name. The browser sends name-value pairs to the server when the form is submitted. The names are determined by the programmer, while the values come from the user. (mostly; there are hidden inputs and such)
    • the form tag has an action attribute that specifies the script (on the server) that will get and process the data submission
    • the form tag also has a method attribute that chooses either GET or POST. (The default is GET.)
      • GET puts all the data in the URL, so it is limited in length and vulnerable to shoulder surfing and such, but nice for emailing, bookmarking and such.
      • POST sends the data later in the request, so it can be essentially unlimited in length and can be slightly more secure.
      • neither is really secure without HTTPS

Ajax

  • In the olden days, forms were only submitted by the browser and the page with the form was replaced by the response from the back-end script. This is still the most universal and accessible mode. (Assistive software doesn't always execute JavaScript properly.)
  • In modern times, forms can be submitted by JavaScript while the user continues to interact with the page.
  • JavaScript can also set up a response handler, which is yet another kind of event handler. In this case, the response handler is a function that gets invoked when the response from the back-end script arrives.
  • The function gets invoked with the response as its argument, so it can look at the response and figure out what to do.

This capability is called Ajax. Ajax allows a web browser to act like a desktop application. Think Gmail and Google apps.

Ajax can either be used to receive info from the server (e.g. Facebook updates, new mail from Gmail) or to send info to the server (e.g. Facebook posts, sending mail).

In this course, we'll only use it to send mail, but you should know its wider applicability.

Quiz Question Nr. 1

The action attribute specifies

  1. what data to send

  2. whether to send the data

  3. where to send the data

  4. how to send the data

Quiz Question Nr. 2

To put the form data in the URL when submitting the form, the page author should use

  1. the GET method

  2. the POST method

  3. either A or B

  4. none of the above

Quiz Question Nr. 3

Ajax ...

  1. is something that happens in the browser

  2. is something that happens on the server

  3. is a way to pass data from the browser to the server

  4. is a way to pass data from the server to the brower

Ajax Recap

Ajax is tricky because we can't use the following reasonable idea:

// the following does *not* work:
var data = $.get("url");
processResult(data);

The reason is because of the fact that, from a computer's point of view, it takes forever (millions of cycles) for the data to arrive from the server. So, it doesn't want to wait that long for .get to return and assign a value to data. The browser doesn't want to freeze for all that time, waiting for the data to arrive. It wants to pay attention to the user.

Instead, Ajax requires you to supply a function, an event handler, which will then get invoked when the data does arrive. This event handler is also called a callback. The callback is invoked with the data as its argument, since that's presumably why you requested it. In our example above, processResult is perfect as a callback function. Therefore, we do:

$.get("url", processResult);

Task #1, analysis

With a partner, using the following Ajax example and your JavaScript console, determine the following:

  • How long does it take for the data to arrive?
  • Does it take the same amount of time every time?
  • What URL is the data gotten from?
  • If you visit that URL (just copy/paste it into your browser location bar), you can see the actual data that is sent. Or look at the serverData global variable.

Ajax and Email Forms

We can also use Ajax to send data to the server. We will send data from a form, and we will use the POST method. Let's first figure out, though, the data we're going to send and how we will send it.

Let's start with specific examples from the reading.

Let's make sure the JavaScript code is clear:

function handleResponse(responseObj) {
    console.log("response is "+responseObj.status+" and "+responseObj.text);
    if( responseObj.status == "ok" ) {
       $("#response_element").html(responseObj.text).css("color","green");
    } else {
       $("#response_element").html(responseObj.text).css("color","red");
    }
}

function sendmail () {
    var where = $("#rsvp-form").attr("action");
    var fn = $("#rsvp-form [name=from_name]").val();
    var fe = $("#rsvp-form [name=from_email]").val();
    var what = {from_name: fn, from_email: fe };
    $.post( where, what, handleResponse, "json");
}       

$("#ajax_send_button").click(sendmail);

Quiz Question Nr. 4

These forms claim to be RSVP, but they always say "yes I'm coming." Can we modify these forms to send a Yes/No, rather than always saying "yes"?

  1. Yes, just add a SELECT menu to the form.

  2. Yes, just add a BODY property to the JS object literal in the Ajax code

  3. Yes, but only in the Ajax version; the normal version can't do that.

  4. No, because the back-end script doesn't allow it

Restricted Web Email

Both of the above forms allowed you to specify the recipient (so you could send it to yourself) but not the content. Couldn't we provide a more flexible form that would allow you to specify all the email essentials:

  • from
  • to
  • cc
  • subject
  • body

Yes, we could, but it would be a very bad idea. Spammers would find that form in about ten minutes and start using it to send spam. Even if you look at our PHP scripts and figure out how to do this, don't. You'll get your server blacklisted and then you won't be able to send legitimate email.

In our examples, we will restrict the email in various ways to make it unappealing to spammers. The primary way is to restrict the recipient. The bad guys could fill up the recipient's email box, but they can already do that.

Submitting the form using Ajax

The back-end script determines what form inputs are meaningful. Our email scripts look for the following:

  • from_name
  • from_email
  • subject
  • body

If additional inputs are sent, they are silently ignored.

In the two examples above, we used a different back-end script that only let you specify the first two inputs: the subject and body of the email were pre-specified.

Echoing Data

For the next task, we'll use a script that just echoes the data back to the browser. It's not useful for any real tasks, but scripts like this are invaluable for debugging. Think of it as like a console.log for Ajax requests. Click on it!

http://cs.wellesley.edu/~cs110/php/echo.php

You can see that the script sends back a little bit of HTML.

Try the following (we are using the GET method):

Task #2: Sending Data

  1. Write some JS/JQ code to send some data, like the first example above (hedwig and gryffindor), to the echo.php script. Hint: use a JS object literal.
  2. The server will send back that bit of HTML. Write a response handler (a function) that will get the response and insert it onto this page in the box below whose ID is response1. Hint: you might use the .html() method.
  3. Use the execution box below to test your code.
response1


Your solution might look like this:

function responseHandler (chunk) {
    $("#response1").html(chunk);
}

$.post("http://cs.wellesley.edu/~cs110/php/echo.php",
       {pet: "Hedwig", house: "Gryffindor"},
       responseHandler);
  

Formatting an Email

Suppose we give the user some choices about the body of the email but not the recipient. If we further allow ourselves to format the result more nicely than those bullet lists earlier, we can get something like the example from the reading.

We'll switch to that other page and make sure everyone is comfortable with all that code.

Generating a PHP Script

If you want to use this facility, we need a way for you to create the appropriate PHP script. Rather than teach you the language just for this one purpose, we've created a meta-script: a script that writes a PHP script for you. It has a form for you to fill out with your email address and your desired default values, and then gives you a PHP script in your Downloads folder (or wherever your browser puts it).

Task #3: Email Forms

This task will ensure that the basics of email form submission work for you.

  1. Fill out the creation form. When you submit it, it'll send back a personalized PHP script that your browser will download.
  2. Using CyberDuck (or some other FTP client), create a "mail-form" folder on the server, in your public_html.
  3. Copy the downloaded PHP script to the mail-form folder.
  4. Download a copy of this tiny-form.html.
  5. Edit it (use TextWrangler) to specify your PHP script in the action attribute, replacing the bogus value in the original. Use a relative URL, meaning just the name of the custom PHP script. That's the only change!
  6. Copy it to the server into the mail-form folder, so that the relative URL for the PHP script is correct. You will now have a folder with an HTML file and a PHP file: the HTML file has a form that uses the PHP file to send mail to you.
  7. Test it by filling out the form and sending yourself an email message.

Summary

We hope that after these activities you have a good understanding of

  • Ajax can be used to get info, such as a list of students, or the latest Facebook updates, from a server.
  • Ajax can also be used to sent info, such as form data, to a server.
  • The jQuery .post() method needs:
    • a URL
    • some data to send, though this is optional (sometimes the URL is all we need)
    • a callback function to handle the response.
    • an expected response type
  • Those methods can be used to send a form to a server.

Solutions

Will be posted later, visit again after .

Quiz answers:

1. C
2. A
3. C and D. In CS110, we'll use Ajax to send data to server (option C).
4. D

© Wellesley College Computer Science Staff. This work is licensed under a Creative Commons License. Date Modified: Wednesday, 11-Oct-2017 13:22:06 EDT