Download presentation
Presentation is loading. Please wait.
1
CMPT241 Web Programming Chapter 6 Forms
3
6.1: Form Basics 6.1: Form Basics 6.2: Form Controls
6.3: Submitting Data 6.4: Processing Form Data in PHP
4
HTML forms form: a group of UI controls that accepts information from the user and sends the information to a web server the information is sent to the server as a query string JavaScript can be used to create interactive controls (seen later)
5
HTML form: <form>
<form action="destination URL"> form controls </form> HTML required action attribute gives the URL of the page that will process this form's data when form has been filled out and submitted, its data will be sent to the action's URL one page may contain many forms if so desired
6
Form example Wrap the form's controls in a block element such as div
<form action=" <div> Let's search Google: <input name="q" /> <input type="submit" /> </div> </form> HTML Wrap the form's controls in a block element such as div
7
6.2: Form Controls 6.1: Form Basics 6.2: Form Controls
6.3: Submitting Data 6.4: Processing Form Data in PHP
8
Form controls: <input>
<!-- 'q' happens to be the name of Google's required parameter --> <input type="text" name="q" value="Colbert Report" /> <input type="submit" value="Booyah!" /> HTML input element is used to create many UI controls an inline element that MUST be self-closed name attribute specifies name of query parameter to pass to server
9
Form controls: <input> (cont.)
<!-- 'q' happens to be the name of Google's required parameter --> <input type="text" name="q" value="Colbert Report" /> <input type="submit" value="Booyah!" /> HTML type can be button, checkbox, file, hidden, password, radio, reset, submit, text, ... value attribute specifies control's initial text
10
Text fields: <input>
<input type="text" size="10" maxlength="8" /> NetID <br /> <input type="password" size="16" /> Password <input type="submit" value="Log In" /> HTML input attributes: disabled, maxlength, readonly, size, value size attribute controls onscreen width of text field maxlength limits how many characters user is able to type into field Password means characters will not appear in screen
11
Text fields: <input>
New attributes in HTML 5 autofocus makes control initially receive keyboard focus placeholder a hint or example of what the user should type shows up as light gray text required whether the browser should display an error if this is left blank
12
Text boxes: <textarea>
<textarea rows="4" cols="20"> Type your comments here. </textarea> HTML textarea is not self-closing (inline element) required rows and cols attributes specify height/width in characters initial text is placed inside textarea tag (optional) Play with the box, add more lines, can you add more lines?
13
Text fields: <input>
New type values in HTML 5 number min max url
14
Text fields: <input>
New type values in HTML 5 color data time month week
15
Check boxes: <input>
<input type="checkbox" name="lettuce" /> Lettuce <input type="checkbox" name="tomato" checked="checked" /> Tomato <input type="checkbox" name="pickles" /> Pickles HTML none, 1, or many checkboxes can be checked at same time What does the url look like?
16
Radio buttons: <input>
<input type="radio" name="cc" value="visa" checked="checked" /> Visa <input type="radio" name="cc" value="mastercard" /> MasterCard <input type="radio" name="cc" value="amex" /> American Express HTML grouped by name attribute (only one can be checked at a time) must specify a value for each one or else it will be sent as value on
17
Text labels: <label>
<label><input type="radio" name="cc" value="visa" checked="checked" /> Visa</label> <label><input type="radio" name="cc" value="mastercard" /> MasterCard</label> <label><input type="radio" name="cc" value="amex" /> American Express</label> HTML associates nearby text with control, so you can click text to activate control can be used with checkboxes or radio buttons
18
Text labels: <label>
<input id="bold" type="checkbox" name="bold" /> <label for="bold">Bold</label> <input id="italic" type="checkbox" name="italic" /> <label for="italic">Italic</label> HTML
19
Drop down lists: <select>, <option>
<select name="favoritecharacter"> <option>Frodo</option> <option>Bilbo</option> <option >Gandalf</option> <option>Galandriel</option> </select> HTML option element represents each choice select optional attributes: multiple, size optional selected attribute sets which one is initially chosen
20
Using: <select> for lists
<select name="favoritecharacter[]" size="3" multiple="multiple"> <option>Frodo</option> <option>Bilbo</option> <option>Gandalf</option> <option>Galandriel</option> <option selected="selected">Aragorn</option> </select> HTML optional multiple attribute allows selecting multiple items with shift- or ctrl-click must declare parameter's name with [] if you allow multiple selections option tags can be set to be initially selected
21
Option groups: <optgroup>
<select name="favoritecharacter"> <optgroup label="Major Characters"> <option>Frodo</option> <option>Sam</option> <option>Gandalf</option> <option>Aragorn</option> </optgroup> <optgroup label="Minor Characters"> <option>Galandriel</option> <option>Bilbo</option> </select> HTML
22
Menus, checkboxes, radio button..
Which one to use? When you have a lot of options to list or limited screen space, use menus. Otherwise, use radio buttons or checkboxes.
23
Reset Buttons Name: <input type="text" name="name" /> <br /> Food: <input type="text" name="meal" value="pizza" /> <br /> <label>Meat? <input type="checkbox" name="meat" /></label> <br /> <input type="reset" /> HTML Reset is not working here! Debug! test1.html specify custom text on the button by setting its value attribute
24
New control elements in HTML 5
datalist (combining text field and list): auto-completion <datalist id = "characters" > <option>Frodo</option> <option>Bilbo</option> <option>Gandalf</option> <option>Galandriel</option> <option>Aragorn</option> </datalist> HTML
25
New control elements in HTML 5
meter: horizontal bar of some numeric quantity <meter min = "0" max = "25" value = "24"></meter>24% Mitt Romney HTML
26
Grouping input: <fieldset>,<legend>
<legend>Credit cards:</legend> <input type="radio" name="cc" value="visa" checked="checked" /> Visa <input type="radio" name="cc" value="mastercard" /> MasterCard <input type="radio" name="cc" value="amex" /> American Express </fieldset> HTML fieldset groups related input fields, adds a border; legend supplies a caption Reset is not working here! Debug! test1.html
27
Styling form controls input[type="text"] { background-color: yellow; font-weight: bold; } input[type=“submit"] { ... a[href = “ } CSS CSS attribute selector: matches only elements that have a particular attribute value useful for controls because many share the same element (input) Reset is not working here! Debug! test1.html
28
Styling form controls Syntax Meaning [attr = “values”] exact match
a[href* = “manhattan.edu”]{ color: red; } CSS Syntax Meaning [attr = “values”] exact match [attr ^= “value”] begins with the given text [attr $= “value”] ends with the given text [attr *= “value”] contains the given text Reset is not working here! Debug! test1.html
29
Example
30
Technique Creating the two-column layout
All label elements are set to float left with a width and text-align of right
31
Head’s Up What did we learn? What’s next?
Form control elements (client-side) What’s next? Form submission (server-side)
32
6.3: Submitting Data 6.1: Form Basics 6.2: Form Controls
6.4: Processing Form Data in PHP
33
URL-encoding certain characters are not allowed in URL query parameters: examples: " ", "/", "=", "&" when passing a parameter, it is URL-encoded “Ben&Jerry" → “Ben%26Jerry" you don't usually need to worry about this: the browser automatically encodes parameters before sending them the PHP $_GET array automatically decodes them
34
Hidden input parameters
<input type="text" name="username" /> Name <br /> <input type="text" name="sid" /> SID <br /> <input type="hidden" name="school" value=“Manhattan" /> <input type="hidden" name="year" value="2019" /> HTML an invisible parameter that is still passed to the server when form is submitted useful for passing on additional state that isn't modified by the user Reset is not working here! Debug! test1.html
35
HTTP GET vs. POST requests
GET : asks a server for a page or data if the request has parameters, they are sent in the URL as a query string POST : submits data to a web server and retrieves the server's response if the request has parameters, they are embedded in the request's HTTP packet, not the URL
36
HTTP GET vs. POST requests
For submitting data, a POST request is more appropriate than a GET GET requests embed their parameters in their URLs URLs are limited in length (~ 1024 characters) URLs cannot contain special characters without encoding private data in a URL can be seen or modified by users
37
Form POST example <form action=" method="post"> <div> Name: <input type="text" name="name" /> <br /> Food: <input type="text" name="meal" /> <br /> <label>Meat? <input type="checkbox" name="meat" /></label> <br /> <input type="submit" /> </form> HTML
38
"Superglobal" arrays Array Description $_GET, $_POST parameters passed to GET and POST requests $_SERVER information about the web server $_FILES files uploaded with the web request $_SESSION, $_COOKIE "cookies" used to identify the user PHP superglobal arrays contain information about the current request, server, etc. These are special kinds of arrays called associative arrays.
39
Associative arrays $blackbook = array(); $blackbook[“marty”] = " "; $blackbook[“jessica”] = " "; ... print “Marty's number is " . $blackbook[“marty"] . ".\n"; PHP associative array (a.k.a. map, dictionary, hash table) : an array whose indexes are not integers associates a particular index "key" with a value key “marty" maps to value " " PHP file needs to be in C:\xampp\htdocs\
40
Printing an associative array
print_r($blackbook); PHP Array ( [marty] => [jessica] => [stuart] => ) output
41
$vehicles = $_POST["vehicles"];
foreach ($vehicles as $vehicle){ print "You selected ".$vehicle; } PHP
42
Example: Print all parameters
<?php foreach ($_GET as $param => $value) { ?> <p>Parameter <?= $param ?> has value <?= $value ?></p> } ?> PHP Parameter name has value Marty Parameter sid has value
43
Associative array functions
if (isset($blackbook["marty"])) { print "Marty's phone number is {$blackbook['marty']}\n"; } else { print "No phone number found for Marty Stepp.\n"; } PHP name(s) category isset whether the array contains value for given key array_keys, array_values an array containing all keys or all values in the assoc.array asort, arsort sorts by value, in normal or reverse order ksort, krsort sorts by key, in normal or reverse order
44
GET or POST? some PHP pages process both GET and POST requests
if ($_SERVER["REQUEST_METHOD"] == "GET") { # process a GET request ... } elseif ($_SERVER["REQUEST_METHOD"] == "POST") { # process a POST request } PHP some PHP pages process both GET and POST requests to find out which kind of request we are currently processing, look at the global $_SERVER array's "REQUEST_METHOD" element
45
6.4: Processing Form Data in PHP
6.1: Form Basics 6.2: Form Controls 6.3: Submitting Data 6.4: Processing Form Data in PHP
46
Uploading files <form action=" method="post" enctype="multipart/form-data"> Upload an image as your avatar: <input type="file" name="avatar" /> <input type="submit" /> </form> HTML add a file upload to your form as an input tag with type of file must also set the enctype attribute of the form it makes sense that the form's request method must be post (an entire file can't be put into a URL!) form's enctype (data encoding type) must be set to multipart/form-data or else the file will not arrive at the server The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
47
Processing an uploaded file in PHP
uploaded files are placed into global array $_FILES, not $_POST each element of $_FILES is itself an associative array, containing: name: the local filename that the user uploaded type: the MIME type of data that was uploaded, such as image/jpeg size : file's size in bytes tmp_name : a filename where PHP has temporarily saved the uploaded file to permanently store the file, move it from this location into some other file
48
Uploading files <input type="file" name="avatar" /> HTML example: if you upload tobby.jpg as a parameter named avatar, $_FILES["avatar"]["name"] will be “tobby.jpg" $_FILES["avatar"]["type"] will be "image/jpeg" $_FILES["avatar"]["tmp_name"] will be something like "/var/tmp/phpZtR4TI"
49
Processing uploaded file example
if (is_uploaded_file($_FILES["avatar"]["tmp_name"])) { move_uploaded_file($_FILES["avatar"]["tmp_name"], "$username/avatar.jpg"); print "Saved uploaded file as $username/avatar.jpg\n"; } else { print "Error: required file not uploaded"; } PHP functions for dealing with uploaded files: is_uploaded_file(filename) returns TRUE if the given filename was uploaded by the user move_uploaded_file(from, to) moves from a temporary file location to a more permanent file
50
Querying a Database in PHP
51
Reminder: Final Project Proposal
Substantial, multi-page website with client and server communications Template available online Submit to Moodle by April 9 before class One submission per team
52
Last Homework! PHP Forms
Brief summary of what we learned in this chapter
53
Tentative Timeline April 16 Last lecture
April 16 – May 3 Final project madness Two Progress checkpoints May 10 Final project presentation
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.