Docstoc

HTML FORMS

Document Sample
HTML FORMS Powered By Docstoc
					HTML FORMS


World Wide Web Technology
Yea, from the table of my memory
I’ll wipe away all trivial fond records
William Shakespeare



                                          1
HTML FORMS
   So far we have used the client-server model
    to make requests for documents and have
    documents served or returned.
   The Common Gateway Interface (CGI) allows
    a variation of this
    – in the sense that a CGI request is understood to
      be a request to execute an application rather than
      simply return a document.
   Of course in returning information to the client
    (browser) a (virtual) document must be used.
                                                           2
What is a FORM?

   Forms provide a means of submitting
    information from the client to the server.
    A form consists of one or more:
           text input boxes
           clickable radio buttons
           multiple-choice check boxes
           pull-down menus
           clickable images
           text and images (maybe instructions on form use);
                                                                3
The <form> tag
   All of the form elements within a
    <form> tag comprise a single form.
   The browser sends all of the values of
    these elements - blank, default, or user
    modified - when the user submits the
    form to the server.
   Browsers flow forms into the containing
    elements as if they were small
    embedded images. So layout elements
    such as <p> and <br> need to be
    used.                                      4
Form Attributes
 action - gives the URL of the application that is
  to receive and process the forms data; most of
  these are kept in cgi-bin or cgi-win; Common
  Gateway Interface binaries;
       Example:<form
        action="http://141.132.64.152/cgi-
        win/testgen.exe" ...</form>

 enctype - the browser encodes the form's data
  before it is passed to the server. The server
  may then decode the parameters or pass them
  still encoded to the application;
       standard encoding format is Internet Media Type named
        "application/x-www-form-urlencoded"; only other type is
                                                                5
        "multipart/form-data"
Form Attributes
    Example of what is sent to the server when a
     form with just 2 fields (name & address) is
     submitted:
     name=T+Rex&address=101+Jurassic+Par
     k+Drive%0D%0APostCode%0D%0A3350
    note that space becomes + and %0D%0A is
     the line break;
    method - sets the HTTP method that the
     browser uses to send the form's data to the
     server for processing; Either POST or GET;
     Example: <form method=GET
     action="http://141.132.64.152/cgi-
     win/testgen.exe" ...</form>                    6
The method attribute in more
detail
   Post
    – The browser sends the data in two steps:
      • contacts the form processing server specified in
        the action attribute;
      • sends the data to the server in a separate
        transmission;
    – On the server side POST-style applications
      are expected to read the parameters from
      a standard location once they begin
      execution.                                 7
The method attribute in more
detail
   GET
    – contacts the form-processing server and
      sends the form data in a single
      transmission step:
    – the browser appends the data to the form's
      action URL, separated by the ? character.



                                                8
Some rules of thumb about which
to use
    Send small forms with a few short fields via the
     GET method for better form transmission
     performance;
    Some server operating systems limit the length
     of command line arguments that can be passed
     to an application. Use the POST method;
    If security is an issue, choose POST because
     GET places the form parameters directly in the
     application URL (easily captured by network
     sniffers); POST can take advantage of
     encryption when transmitting the parameters as
                                                    9
     a separate transaction;
  A FORM example
<form method=POST action="http://www.ballarat.edu.au/cgi-bin
/horoscope">
Name:
        <input type=text name=name size=32 maxlength=80>
<p> Sex:
        <input type=radio name=sex value="M"> Male
        <input type=radio name=sex value="F"> Female
<p> Date of Birth:
        <input type=text name=year size=4 maxlength=4> Year
        <input type=text name=month size=2 maxlength=2> Month
        <input type=text name=day size=2 maxlength=2> Day
                                                            10
<p> <input type=submit> </form>
The form generated




                     11
Notes on the above

  Relate the code to the form produced;
  Relate the HotMetal form handling
   (especially via SGML attributes) to the form
   produced.
  What do you expect to happen if you fill in
   the form and press the submit button?
  What does happen?
  Why?
                                                 12
FORM Input Elements
   The <INPUT> Tag
    – This is used to define text fields, multiple
      choice lists, clickable images and submit
      buttons. Only the TYPE and NAME
      attributes are required.
   The <input> tag attributes
        align -
        checked -
        maxlength - maximum number of characters
         accepted by the browser
                                                     13
The <input> tag attributes
    name - defines the name of the input element;
     used to label the data when transferred to the
     cgi program;
    size - physical size of the input element; default
     is 20 characters;
    src -
    type - determines the type of input requested;
     text, radio buttons, password, reset, image,
     hidden, checkbox;
    value - optional; it can be used to insert an
     initial default value into the field;
                                                      14
Text Fields
   Conventional text field -
        size attribute dictates the width of the text box;
        maxlength dictates the maximum number of
         characters that the user can see and type;
        if maxlength exceeds size then text scrolls
         back and forth within the text entry box;
        server side application must trap errors;
        Masked text field - type=password;
         obscured onscreen but is
         transmitted unencrypted;
        File selection field - lets the user select and
         send a file; type pathname directly or use the    15
         Browse button;
Checkboxes

   type=checkbox
    – The name and value attributes are
      required.
    – If the item is selected it will contribute a
      value when the form is submitted;
   For example the form code:


                                                     16
Checkbox form code
<form>
What units are you studying this semester?
   <p>
     <input type=checkbox name=unit
     value="CP747"> CP747
   <br>
     <input type=checkbox name=unit
     value="CP725"> CP725
</form>



                                        17
Produces




           18
Radio Buttons

   Similar in behaviour to checkboxes
    except that only one in a group may be
    selected.
   We have already seen an example
    above.



                                             19
Action Buttons
  Submit - <input type=submit>
   submits form information to the server;
  Reset - clears the form on the client side;
  Custom buttons - clickable images; Eg.
   <input type=image
   src="images/pic.gif name=map>;
  Multiple buttons - Different value attributes
   can be used to distinguish the functionality
   of the submission process;
           <input type=submit name=action
            value="Add">
           <input type=submit name=action         20
            value="Delete">
Hidden Fields
   These are for embedding information in
    forms that cannot be altered by the
    browser or user.
   They may be used to label a form or to
    manage user/server interactions or to
    direct the server to some specific action.
    – <input type=“hidden NAME=“recipient”
      VALUE=“jly@ballarat.edu.au”>
      <input type=“hidden” NAME=“subject”
      VALUE=“Feedback Form”>
      <INPUT TYPE =“hidden” NAME=“redirect”
      VALUE=“main.html”>                   21
Text Areas
   The <textarea> tag creates a multiline text
    entry area in the browser display.
   On submission all lines of text are separated
    by %0D%0A and sends them to the server as
    the value of this element.
   Attributes are :
        cols - sets number of characters width
        name -
        rows - sets the number of lines
        wrap - off- single line; virtual-multiple line but
         single line transmission; physical- multiple lines
                                                            22
         displayed and transmitted;
Multiple Choice Elements
   The <select> tag allows the
    construction of multiple choices with the
    <option> tag.
   Attributes are:
        multiple - allows more than one selection at a
         time;
        name -
        size - number of options;
   This implements pull-down menus and
                                                          23
    scrolling lists.
24
Listbox
<FORM> What project are you doing?<P>

      <SELECT NAME=project size=3 multiple>

      <OPTION>Multimedia

      <OPTION>Java

      <OPTION>VRML

      <OPTION>SGML

      </SELECT></FORM>                        25
<OPTION> tag
    The <OPTION> tag has two attributes
     – VALUE and SELECTED.
     – By default all options are unselected so the
       SELECTED option is used to preselect one
       or more options.
     – VALUE can be used to set a value for each
       option. When it is not used the value is the
       content of the selection.


                                                26
FORMS Design
   In creating a form you immediately
    assume another role associated more
    with interface design.
       HTML allows you to concentrate on document
        structure and content;
       the browser presents the document
        information;
       Interface design, hci and HTML are blended in
        form design;
       Need to use the presentational apects of HTML
        to their full.
       Remember that users process forms in a
                                                        27
        predictable order, one element after another.
FORMS Programming
   Associated with each form is a server
    side application that processes the
    form.
   Writing a forms application from scratch
    is arduous and so reusing already
    written applications is advised.
   Often servers contain useful cgi scripts
    in the cgi-src directory. The basic steps
    are:
                                                28
Basic Steps
  – Form at the client end refers to an action
    (the application) in the cgi-bin area of the
    server;
  – The server passes the form data to the
    application;
  – Application executes, ends and passes the
    results back to the server by writing the
    result to the application's standard output
    as a MIME encoded file;
  – The server returns the results to the
    browser (client);                              29
Forms Programming
   So the first line of the application's
    output must be a MIME content-type
    descriptor.
   In the case of the application returning
    an HTML document, the first line is:
    – Content-type: text/html
   The second line must be empty.


                                             30
Forms Programming
   If a GIF image was returned then the
    line would be:
    – Content-type: image/gif
   Plain text which is not HTML can be
    returned with:
   Content-type: text/plain



                                           31
GET Forms
   Parameters are passed as part of the
    URL that invokes the server side form
    application.
   Named parameters
    – These are passed to GET applications by
      creating an environment variable named
      QUERY_STRING and setting its value to
      the entire portion of the URL following the
      question mark.

                                                    32
GET Forms

 – The application must retrieve this variable
   and extract from it the name/value pairs.
 – Most servers have a set of utilities that
   perform the tasks for you.
 – Here is an example C program that dumps
   the parameters:



                                                 33
C program to get FORM values
#include <stdio.h>
#include <stdlib.h>
#define MAX_ENTRIES 10000
typedef struct {char *name;
                char *val;
               }entry;
char *makeword(char *line, char stop);
char x2c(char *what);
void unescape_url(char *url);
void plustospace(char *str);
main(int argc, char *argv[])
{ entry entries[MAX_ENTRIES];
   int num_entries, i;
   char *query_string;
                                         34
 C Program for GET
/* Get the value of the QUERY_STRING
       environment variable */
   query_string = getenv("QUERY_STRING");
/* Extract the parameters, building a table of entries */
   for (num_entries = 0; query_string[0]; num_entries++) {
       entries[num_entries].val = makeword(query_string,
              '&');
       plustospace(entries[num_entries].val);
       unescape_url(entries[num_entries].val;
       entries[num_entries].name =
          makeword(entries[num_entries].val, '=');
       }




                                                        35
C Program for GET
/* Spit out the HTML markup */
   printf("Content-type: text/html\n");
   printf("\n");
   printf("<html>");
   printf("<head>");
   printf("<title>Named Parameter Echo</title>\n");
   printf("</head>");
   printf("<body>");
   printf("You entered the following parameters:\n");
   printf("<ul>\n");
/* Echo the parameters back to the user */
   for (i = 0; i < num_entries; i++)
      printf("<li> %s = %s\n", entries[i].name,
              entries[i].val);
/* Close with the HTML */
   printf("</ul>\n");
   printf("</body>\n");
   printf("</html>\n");
                                                        36
GET

   Note the system call getenv() to
    obtain QUERY_STRING.
   Actual applications will need the code to
    match the application functionality.




                                           37
Unnamed parameters with GET

   Unnamed parameters are passed to the
    application as command line
    parameters.
   So for example these can easily be
    picked up in a shell script.



                                         38
POST Forms

   POST style applications expect to read
    encoded parameters from their standard
    input.




                                        39
C Program for POST
#include <stdio.h>
#include <stdlib.h>
#define MAX_ENTRIES 10000
typedef struct {char *name;
                char *val;
               }entry;
char *makeword(char *line, char stop);
char *fmakeword(FILE *f, char stop, int
*len);
char x2c(char *what);
void unescape_url(char *url);
void plustospace(char *str);
main(int argc, char *argv[])
{ entry entries[MAX_ENTRIES];
   int num_entries, i;                    40
  C Program for POST
/* Parse parameters from stdin, building a table of entries
*/
   for (num_entries = 0; !feof(stdin); num_entries++) {
       entries[num_entries].val = fmakeword(stdin, '&',
&cl);
       plustospace(entries[num_entries].val);
       unescape_url(entries[num_entries].val;
       entries[num_entries].name =
          makeword(entries[num_entries].val, '=');
       }




                                                        41
 C Program for POST
/* Spit out the HTML markup */
   printf("Content-type: text/html\n");
   printf("\n");
   printf("<html>");
   printf("<head>");
   printf("<title>Named Parameter Echo</title>\n");
   printf("</head>");
   printf("<body>");
   printf("You entered the following parameters:\n");
   printf("<ul>\n");
/* Echo the parameters back to the user */
   for (i = 0; i < num_entries; i++)
      printf("<li> %s = %s\n", entries[i].name,
              entries[i].val);
/* Close with the HTML */
   printf("</ul>\n");
   printf("</body>\n");
   printf("</html>\n");                           42
The Apache Server

   Information about this server is at
    http://www.apache.org.
   This is the unix based server that will be
    used for your pages and your CGI.
   There is now Apache 1.3 availaible for
    NT and Win95.
   You could download this and install at
    home
                                             43
    Stopping and starting Apache on

    Win95 95, Apache runs as a console
    On Windows
    application.
   You can tell a running Apache to stop by opening
    another console window and running
    –      apache -k shutdown
   This should be used instead of pressing Control-C in
    the running Apache console window, because it lets
    Apache end any current transactions and cleanup
    gracefully.
   You can also tell Apache to restart. This makes it re-
    read the configuration files. Any transactions in
    progress are allowed to complete without interruption.
    To restart Apache, run
    –     apache -k restart                                44
Apache Web Server

   Note for people familiar with the Unix
    version of Apache: these commands
    provide a Windows equivalent to kill
    -TERM pid and kill -USR1 pid.
    The command line option used,
    -k, was chosen as a reminder
    of the "kill" command used on
    Unix.
                                         45
Apache

   Find httpd.conf
    – Notice document root - where is it set now
    – CGI
    – What other settings?




                                               46
The Website server
   This is an NT based server that you can
    download and install on a Windows 95
    or NT machine.
   You can get some information about its
    CGI by down loading the Website Web
    server from
    http://software.ora.com/download/ and
    looking at
    http://localhost/wsdocs/32demo/window
    s-cgi.html
                                          47
    Website
   Note: the IP address for localhost is 127.0.0.1
   A simple "Hello World” example with the VB
    windows based CGI is provided below.
   At this stage you should try to make some
    sense of this by consulting the server
    documentation and the CGI.BAS or
    CGI32.bas files.
   Other samples can be found in cgi-
    src/VB4 samples directory if you have
    taken the trouble to download and install the
    Website server.
                                                    48
Website VB code for Hello CGI
'----------------------------------------------------------------------
'     **************
'     * SAMPLE.BAS *
'     **************
' Sample CGI back-end for WebSite and Windows httpd
' Requires procedures in CGI.BAS. Set the VB project options to use
' Sub Main as the startup form.
'----------------------------------------------------------------------
Option Explicit
' Sample CGI script
' Returns a "hello" document
' CGI32.BAS contains the "Sub Main()" entry point. That code initializes
' the CGI environment, then calls CGI_Main(), here. At this point, the
' output file is open, the input file (if any) is NOT. Use the Send()
' function to isolate yourself from the output file number, and as
' a convenient shortcut.
                                                                       49
'
Website VB code for Hello CGI

Sub CGI_Main()
  Send ("Content-type: text/html")
  Send ("")
  Send ("<HTML><HEAD><TITLE>Hello!</TITLE></HEAD>"
  Send ("<BODY><H1>Hello!</H1></HEAD><BODY>")
  Send ("Hello from Visual Basic!")
  Send ("<P>It is now " & Now)
  Send ("</BODY></HTML>")
End Sub



                                              50
 Website VB code for Hello CGI

'---------------------------------------------------------------------------
' Inter_Main() - Stub for interactive startup
' See the comments in the CGI32.BAS declarations section
'---------------------------------------------------------------------------
Sub Inter_Main()
   MsgBox "This is a CGI program."

  ' Exit Sub will end the program
End Sub



                                                                           51
Main Points of the Decoding
process
    – Determine the request HTTP method (GET or POST)
      by checking the REQUEST_METHOD environment
      variable;
    – If the protocol is GET, read the query string from
      QUERY_STRING;
    – If the protocol is POST determine the size of the
      request using CONTENT_LENGTH and read that
      amount of data from the standard input;
    – Split the query string on the "&" character, which
      separates key-value pairs
      (name=value&name=value)
    – Decode the hexadecimal and "+" characters in each
      key-value pair.
    – Create a name-value table with the name as index.    52
Bourne Shell Script for Hello
#!/bin/sh
echo Content-TYPE: text/html
echo
echo
echo Hello World!




                                53
Perl

#!/usr/bin/perl

print "Content-TYPE: text/html\n\n";

print "Hello World!\n";




                                       54
Some Web resources on FORMS
& CGI
  http://www.stars.com/Seminars/HTML/For
   ms/
  http://www.stars.com/Seminars/CGI/




                                            55

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:17
posted:5/21/2010
language:English
pages:55