RU beehive logo ITEC dept promo banner
ITEC 325
2017spring
ibarland

homelectshws
D2Lbreeze (snow day)

forms
html input forms, and php

Video: form basics: passing key/values (12m36s)

Forms and form-handlers:
A form is an html page where users may enter information (e.g. their favorite color, and whether or not they feel happy). Then, “submitting the form” just means requesting some other URL, but including the users's information along with the request.

Slightly more detail: When a user clicks submit, the browser takes the URL specified in the form tag — we call that URL the "form-handler". As it requests the form-handler, it includes the form's info along with the request, as key/value pairs (e.g. "fave-color" => "orange" and "isHappy" => "a-yep"). The form-handler (which might be a php program) can use this information to craft a response (html). Here is a small example.

The main thing to note is how the key-value pairs are specified. the form has input tags, with an attribute “name”. That name is what is used as the key, in the key-value pair! The value might come from the user (in the case of a input type='text' tag), or might be taken from the tag's value attribute (in the case of the checkbox shown).

Of secondary interest is the form tag itself. It's important attribute is action: When submitting, the browser merely requests the URL specified by action, and it also bundles along the key/value pairs specified by the form's inputs. If method='get', the key/value pairs are attached at the end of the URL (like form0-get.php); if the method='post' then the key/value pairs are instead passed along inside the http header.

We've already discussed that when php.radford.edu gets a request for a URL ending in .php, it runs that file as a program (returning anything that program printed out). But right before it runs the program:

  1. The server starts a php-process, in the OS.
  2. In that process's memory-space, the server creates an array named “$_POST” and populates it with any key/value pairs that were in the http request packet.
  3. In that process's memory-space, the server creates another array, named “$_GET”, and populates it with any key/value pairs at the end of the URL (following a “?” in the URL)
  4. Finally, it runs the requests php program, starting from line 1. That's why our PHP program has a arrays $_POST and $_GET to work with.
(Btw, there a few other arrays that are also pre-initialized for you; look up “PHP superglobals” if interested.)

label tags

You can use a label tag, to connect some text (anywhere on page) with (sending focus to) a particular input: See the example form below. Either enclose the text and the input inside the same label, or use label's for attribute.

Gotcha: While <input name='aNodeName'/> uses the name attribute to pass information to the action/request, the html <label for='aNodeId'>… uses id to refer to the DOM node of the current tree. (This actually makes good sense, but takes a moment of thought.)

grouping inputs into a single array

What if we have several different inputs which are grouped together? For example, in addition to asking about favorite colors and quests, you have several inputs all about a mailing-address (street, city, state, and zip). We could have the handler receive each input separately:

array( "favorite-color" => "orange"
     , "quest" => "cookies"
     , "street" => "800 E. Main St"        // }
     , "city" => "Radford"                 // } unsatisfying to not have
     , "state" => "VA"                     // } these four grouped more closely
     , "zip" => "24121"                    // }
     , "is-happy" => "yep"
     );
          
But clearly, this is unsatisfying: the four inputs for street, city, state, and zip are closely related in a way that the other inputs aren't. We know from programming, that we'd like to have all the address-information grouped into its own object/array:
array( "favorite-color" => "orange"
     , "quest" => "cookies"
     , "address" => array( "street" => "800 E. Main St"        // }
                            , "city" => "Radford"              // } Much better! The address
                            , "state" => "VA"                  // } is now a single object!
                            , "zip" => "24121"                 // }
                            )
     , "is-happy" => "yep"
     );
          
In intro programming, this is the same notion of an object, one of whose fields happens to be another object. (An array containing an array is the natural, proper representation.)

Happily, we can achieve this! If an input tag's name attribute contains square-brackets, a (sub) array is created inside $_POST, exactly like we want:

 <input type='text'     name='favorite-color'/>
 <input type='text'     name='quest'/>
 <input type='text'     name='address[street]'/>
 <input type='text'     name='address[city]'/>
 <input type='text'     name='address[state]'/>
 <input type='text'     name='address[zip]'/>
 <input type='checkbox' name='is-happy' value='yep'/>
            
In our form-handler, $_POST['address'] is now an entire sub-array. So we can pull out elements of that array by following it with square-brackets: $_POST['address']['zip']. Some people also prefer to pull out the sub-array and put it into its own variable, though that's not strictly necessary:
              echo "favorite color is ", $_POST['favorite-color'], "\n";
              echo "the address's zip is ", $_POST['address']['zip'], "\n";
              // Or, we can make a new variable to hold just the sub-array:
              $address = $_POST['address'];
              echo "the address's city is ", $address['city'], "\n";
            
pro tip: If you do want to grab a value from an array and stick it in a variable (rather than just typing out the array-and-index every time you want to use it), do yourself a favor and make the variable-name the same as the index-name:
                $faveCol  = $_POST['favorite-color];  // ACK this way lies madness
                $is_happy = $_POST['is-happy'];       // Good — parallel naming reduces mental overhead
              

The only thing to note is a slight discrepency in quote-marks, in the html source (no quotes inside the square-brackets), and the PHP code accessing an array-index (where you do put quotes inside the square-brackets3).

GET vs POST

Video: GET vs POST (11m16s) GET & POST methods

Q: But how is information communicated from a web form (pure html) to a php program?
A: When you click 'submit', the HTML makes a page-request to the page specified by the form's "action" attribute. (Presumably it's a php page.) The page-request incudes extra information about what html input fields had been selected, etc., as part of the http request. The server gets that request and invokes the php file as normal, but it also pre-initializes an array of values for the program — and it fills that array with the extra information contained in the page-request.

When to use which?:

takeaways

video from distance lecture (breeze), 2017-feb-07 (1h42m), REVIEWING this info

1 Okay, in HTML5 it's okay to not explicitly state a value at all, for a boolean-attribute. But for this class, we'll also follow XHTML's rule that every value must have an explicit value. Hence, checked='checked'.      
2 Note that everything the HTML designers bundled together under the input tag do have one thing in common: it's not allowed to have a body. I can see wanting to syntactically name which tags are forbidden a body and which allow one, but that still doesn't explain why each input-type isn't its own tag, which would then make all input tags treated equally.      
3 Well, admittedly: PHP, in its awfulness, will interpret text-without-quotes as a string, so it would actually work to look up an array-index without putting quote-marks inside the square brackets. But that's CRAZY. Put quotes around string-constants, like we do in every other language on the planet (at least, if you want full points, in this course).      
4 Idempotent is not quite the same as having-no-side-effect: For example, if you add-to-shopping-cart-unless-item-already-there, you can change state, but still be idempotent.      
5 Well, “irrelevant” state-change is okay: you can update log files and update cookie-timestamps, w/o violating the spirit of a GET request.      
6 And later, when we talk about sticky-forms, I'll suggest “customer-info-edit.html” which requires either …-form or …-handle.      

homelectshws
D2Lbreeze (snow day)


©2017, Ian Barland, Radford University
Last modified 2017.Mar.18 (Sat)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.