Session 29: Using Form Data to Make Pages Dynamic
Opening
Last week, we...
- learned how to create HTML forms, and
- considered how to style forms with CSS.
Today, let's look at ways to use form data to make pages dynamic, with a focus on things we can do as client-side developers. We will see a couple of new ideas in HTML, revisit a couple more, and revisit some simple JavaScript.
To do that, we need a few web pages to work with.
Download this starter code as the base for our work today. It contains three web pages:
and their associated style sheets and script files.
I will work in Chrome today. We will find its behavior when sending and reloading forms to be useful later.
Using Form Data to Customize A Page
Recall our JavaScript examples to set colors and fonts, to
style table cells, and the like. In those examples, we used
prompt
boxes to get user input. Unfortunately,
prompts are not visually attractive and, even worse, occurred
every time the page loaded.
Now we know how to use input elements to give the user control over when and what data to use to customize a page. We can do that all on the client-side, without a form, using the same simple JavaScript as before.
The idea:
- Define CSS classes for two or more themes (antique, dark mode, ...).
- Let user choose a theme for the page.
- Let user click a button to cause the change.
Define CSS classes for the themes.
Simple styling for the page and form are given.
Let user choose a theme.
The user will choose the theme from a dropdown menu. We
learned about the datalist
element last time.
But it gives too much freedom to users... We want them to
select one specific item from a predefined list.
Let's a select
element. We first saw it in
the Airbnb form example
in last week's reading. Give the menu a label.
Once users select a theme, they can let the page now by pressing a button.
We don't need a form
element here, because all
behavior is occurring on the client. But we do have a "form"
of sorts: a menu with a label and a submit button. Let's wrap
them in a div
that can be styled as a form.
Write JavaScript to respond to the event.
This script can be a standard button listener. It will retrieve the user's selection and adds the requested class to the body of the page.
The final result: HTML | CSS | JS
This page is a simple example of how to use input data to style
a page. But it doesn't use a form
at all! Let's
look at a second example that does.
Using Form Data to Do Custom Search
We have a problem: You are not a running server, so GET and POST don't work if we send them to the host of your page.
But we can send the data to another server in the ACTION, as long as that server accepts messages. Many websites offer public interfaces to their services (APIs), such as the Cat as a Service site we used in Session 25.
Using the Google Search Server
The most widely used web service is
Google search,
at the URL https://www.google.com/webhp
.
Google's API defines a set of names that we can use in a URL.
The main one is q
, for the query.
We can select media type with tbm
.
bks
for booksisch
for imagesvid
for videos
We can focus the search on pages last modified in a given time
frame using as_qdr
.
d
for last dayw
for last weekm
for last monthy
for last year
There are many others, including as_sitesearch
to
limit searches to a specific domain and as_epq
to
request an exact match (instead of q
).
If we use names defined in Google's API, then the GET method will build a query string for us and launch a search!
Build a search form.
Let's build a search form to save us having to type the query string: a text box, two menus with labels, and a submit button.
Style the form.
- Set the width of the form.
-
Make the text box a bit wider, using
input[type=text]
. -
Give a little left margin to the submit button, using
input[type=submit]
.
Observe the URLs. The browser constructs the URL as a part of submitting the data to the server using GET.
Your page can also exert some control over the URL, by processing the values in the form. For example, suppose you wanted to add a term to the search query, say, 'steampunk' to match the theme of your page.
Write a script to modify the search term.
We can append ' steampunk'
to the search term,
which is the value of the text input.
This approach works best if you want to add a random string to
the query, or to have a reset button on the form. If you
always want to add the same string to the search query, you
can initialize the value of the text box:
value='steampunk '
.
The final result: HTML | CSS | JS
This example uses another server as the target for a form. If you find an API you like (say, dogs or cats as a service), you can use a form like this one to let the user select a new image for your page — just add a little JavaScript to modify an element on the page in response to the query.
There is one way we can submit data on the client side: use a protocol that the browser can handle locally.
Using Form Data to Create an Email Message
As we learned in the first week of the course, the web is built
on the http
protocol (now, https
).
Many other protocols exist, including older interchange schemes
on the internet, such as ftp
.
mailto
is URL scheme for email addresses. When
we use it as an anchor's href
, it produces a
hyperlink that allows users to send an email message to the
given address directly from the web page, without having to
enter the address into their email client.
This is fine for launching a blank message in the local email client and letting users type their message there.
Within a web page, we can do more. Like http
,
the mailto
protocol also uses query strings to
encode data for the message.
That is the same sort of query string used by the GET and POST methods to submit form data.
A web page can hardcode the subject and body of a message in its HTML before launching the email client. With a form, though, the user can enter data that is used to build the query string.
Study the form.
Much like the contact form from last session, this form consists of two label/text box pairs, a large text area for the body of the message, and way to submit.
Two things on the submission method:
- We could use a submit button again, but an anchor can do the job, too.
-
Notice the
href="#"
. Recall that we can use "#" instead of "GET" or "POST" as a form's submission method, meaning that the form handling will be done by the web page itself. It means roughly the same in an anchor: stay here. JavaScript will process the form.
We can use the same style sheet as we used for last session's
form. We can even use the buttons
class:
class="buttons"
to push the submit link to the far right of the form.
Write a script to create query string.
Our script needs to:
- access the values of the fields,
- encode the values for use in a URL, and
- assemble the query string from its parts in the form.
Why must we encode the values? Remember that some characters
means something in a URL, including ?
,
+
, and &
. If the user enters
any of these characters into a subject or body and we include
them as-is in the query string, the browser will interpret
the URL differently than the user intended!
We can use the builtin function
encodeURIComponent(someString)
to encode the
strings before assembling the URL.
If we were programming on the server, we could use this URL to
send the message directly over the internet. On the client,
we can rely on the fact that web browsers know to process the
mailto
protocol by opening the client's default
email app: window.open(url);
This still requires the user to hit send, but that is the best we can do on the client. On the positive side, it gives the user a chance to edit their message before sending.
One last bonus bit of HTML: If you don't mind mixing a little
JavaScript into your HTML, you can add the event listener to
the anchor inline using the onclick
attribute,
and thus eliminate the last two lines of the script:
onclick="sendMail();"
And we are done. Even with its limitations, this example shows how powerful HTML and JavaScript can be on the client.
Closing
These three examples are all ways that we can make our web pages dynamic using HTML input elements and forms, with a little JavaScript sprinkled in.
The final project is live and due at the end of this week. Feel free to use any of these examples as a starting point for dynamic behavior on your pages.
Next time, we will wrap up the a course — or cancel the session so that you can use it as a work day. If you have a preference, please let me know by email or in the office. In any case, I will have the an in-class lab exercise that you can do as practice on your own time, if you'd like.
The final exam is one week from Thursday. It won't be like the previous exams, or cumulative beyond the fact that everything we have done this semester has grown our knowledge of HTML, CSS, and JavaScript. It will be an in-class lab exercise that asks you to create, style, and process a simple form.
I will post more information later this week under Final specification in the "Readings" column on the home page.