Making Websites Interactive

tacitmarigoldInternet and Web Development

Jan 25, 2014 (3 years and 7 months ago)

249 views

Making Websites Interactive

Bryant College EDC

Web Developer Certificate Program

Spring, 2001

Objectives


Creating good forms


Understand how to implement JavaScript


Client Side field validation


Understand Server Side Processing


Implement PERL to process form data


Create Interactive Web Pages and E
-
Mail


Capturing and Storing Customer Data

Overview


Part 1


Interactivity Basics


-

Introduction


-

Definitions



Part 2


Forms Processing


-

Form Tag


-

Form Elements


-

Aligning Forms


-

Executing Pre
-
Defined Scripts


Overview


Part 3


JavaScript


-

Definition


-

Java vs JavaScript


-

Document Object Model


-

Events and Event Handlers


-

Functions and Methods


-

Examples


-

Debugging

Overview


Part 4


CGI/PERL


-

Define CGI and PERL


-

PERL Variables and Expressions


-

Environment Variables


-

Getting Data


-

Creating E
-
Mails


-

Creating HTML Pages


-

Reading and Writing Files

The Basics


Interactivity needed to attract customers


Makes the site engaging and fun


Helps to validate the expense


Cheap Marketing tool


Types of Interactivity


Forms


E
-
Mails


Image Rollovers


Friendly Web Pages


The Basics


Definitions


Client vs Server Side Processing


Forms Processing


Scripting Languages


CGI/PERL

Forms Processing


<FORM> tag


Starts a FORM


Must have an </FORM> tag


Contains a few attributes


Can have multiple on a page


Cannot be embedded



Format is;


<FORM ACTION=“mailto:training@ecentricsites.com”



ENCTYPE=“application/x
-
www
-
form
-
urlencoded”



METHOD=“POST”



NAME=“mailform”


>



Form Elements


Three types of form elements <INPUT>, <SELECT>,
and <TEXTAREA>



<INPUT TYPE=“text” NAME=“firstname” SIZE=“20”
Maxlength=30>



Creates the TEXT input box for the user’s name in our
form


NAME defines the name of the data for the field


Use only letters, numbers, and underscores


TYPE defines the various types of input fields recognized
by HTML

Form Elements


<INPUT TYPE=“text” NAME=“firstname” SIZE=“20”
Maxlength=30>



SIZE specifies how big the form field should be displayed


The user could still type more than 20 characters in the
above field, the browser just scrolls the text in the window


We can limit the length using MAXLENGTH=num

Form Elements


<INPUT TYPE=“checkbox” NAME=“hobby” VALUE=“0”
CHECKED>Skiing


<INPUT TYPE=“checkbox” NAME=“hobby”
VALUE=“1”>Sky Diving


Creates CHECKBOX input fields for the user


VALUE is used to assign a value to the checkbox when it
is CHECKED


Data following <INPUT> tag is displayed next to checkbox


The CHECKED attribute will pre
-
check the box.


More than 1 Check Box can be selected

Form Elements


<INPUT TYPE=“radio” NAME=“sex” VALUE=“M”>Male


<INPUT TYPE=“radio” NAME=“sex” VALUE=“F”>Female


Creates RADIO input fields for the user


VALUE is used to assign a value to the radio button when
it is CHECKED


Data following <INPUT> tag is displayed next to radio
button


The CHECKED attribute will pre
-
select a radio button.


Only ONE radio button can be selected

Form Elements


<SELECT NAME=“creditcard” SIZE=1>


<OPTION VALUE=“V”>Visa


<OPTION VALUE=“A” SELECTED>Amex


</SELECT>


SELECT specifies that you have a drop down box and
SIZE indicates how many drop down items to show at one
time


OPTION specifies an item in the drop down box. VALUE
indicates what the selection is assigned when the user
selects it.


SELECTED will pre
-
select the item from the drop down
box


MULTIPLE as an attribute for the SELECT tag allows
multiple selections to be valid.

Form Elements


<TEXTAREA NAME=“comments” ROWS=3 COLS=30>Insert
Comments Here </TEXTAREA>



TEXTAREA specifies that you have a large amount of text
to capture


ROWS and COLS indicate how big of a text area to
DISPLAY.


<TEXTAREA> needs a </TEXTAREA> tag


Data between the <TEXTAREA> and </TEXTAREA> tags
will be put into the text area box.

Form Elements


<INPUT TYPE=SUBMIT VALUE=“Test this form”>


Each form must have exactly one field of type submit


This creates the button the user pushes when they’re
done


You can put whatever words you want in the submit
button, using the VALUE keyword


The default will be “Submit”


When this button is clicked, the browser collects all the
values of each of the input fields and sends them to the
web server identified in the ACTION keyword

Form Elements


<INPUT TYPE=RESET VALUE=“Reset this form”>


This creates a button the user can push to reset all form
fields to their initial state


You can put whatever words you want in the submit
button, using the VALUE keyword


The default will be “Reset”


When this button is clicked, the browser resets all inout
fields to their initial state, Items marked as SELECTED or
CHECKED will be set “ON”

Aligning Forms


Important to Align your Form for Visual Presentation


When user resizes window, form could become
distorted


Form can look different across browsers and may be
rendered different


Tables can be used to align fields properly


Form will keep it’s visual look and feel across
browsers and during resizing


Executing Server Scripts


Many pre
-
defined scripts on the internet


Can interface with them directly


Can copy them and make small changes and use
them (with owners permission)


Why reinvent the wheel


Good site for scripts is;




http://cgi.resourceindex.com/Programs_and_Scripts/PERL/


JavaScript Scripting Language


Developed by Netscape


Recognized across browsers


Browsers execute JavaScript statements when
processing an HTML page for display


Can create mouse rollover events


Add conditional behavior to a web page


Interpret Form data


Pop up Message boxes and Dialog boxes



JavaScript vs Java


Not Related


JavaScript is interpreted and Java is compiled


JavaScript is run on the client, Java applets reside
on the server and are copied to the client for
execution


JavaScript does not have classes, inheritance, and
strong variable typing




Document Object Model


Way for Scripting languages to reference
objects on a web page


Reference objects on a page using the DOM
model standard of



objectName.propertyName


objectName can be standard object like
“window”, or a sub object within the window
like a “form”


Example



window.document.formname.buttonname




Document Object Model





Document Object Model


Examples


window.document.formname.textbox.value


window.document.bgColor = “#333333”;


document.write(“You just came from “ +
history.previous);




Placement of JavaScript


JavaScript is embedded into an HTML document


Can be embedded in one of four ways


As statements and functions within the <SCRIPT> tag


Specified as a file to be included with the HTML source


As a JavaScript expression as the value for an HTML
attribute


As event handlers within certain HTML tags






The <SCRIPT> Tag


Can be declared anywhere within the HTML code via
the <SCRIPT> and </SCRIPT> tags


Example



<SCRIPT LANGUAGE=“JavaScript”

TYPE=“text/javascript”>



<
--





Javascript Code



--
>



</SCRIPT>



Comment lines hide code from older browsers


LANGUAGE attribute tells browser its JavaScript





JavaScript Source File


SRC attribute of <SCRIPT> tag allows you to specify
a file to be embedded


Example



<SCRIPT SRC=“common.js”>




Javascript Code



</SCRIPT>


Any statements specified within the script tag are
ignored if the file is found


External JavaScript file should have a .js suffix


Only JavaScript statements within the JavaScript file





JavaScript Expressions


Used as a Value for an HTML attribute


Example



<HR WIDTH=“&{barwidth};%” ALIGN=“LEFT”>


Start with an ‘&’


Ends with a ‘;’


Variable must already have been defined
within previous JavaScript code


Netscape only





Event Handlers


Can be added as an event handler to an
HTML tag


Example



<INPUT TYPE=“button” Value=“Click Me”



onClick=“alert(‘I
\
’ve been clicked’)”>


onClick is the event handler


Put JavaScript instructions in quotes


Alert is a pre
-
defined JavaScript function





Events and Event Handlers


Events are defined actions on objects


Events Handlers are defined JavaScript
functions that do something when the
event happens


Three major events on which you can
add event handlers


Form related events


Links


Loading and Unloading windows




Form Related Events


onClick, onBlur, onChange,
onFocus, onSelect


Add event as an attribute to the
object HTML tag.



<INPUT TYPE=“button” value=“Click Me”




onClick=“dosomething()”>





onBlur Event


Occurs whenever a form object loses
focus.


Works with Input element Type “text”


Works with the Textarea element


Works with the Select element


Example


<INPUT TYPE=“text” Name=“text1”
onBlur=“alert(‘You have just left the text1
form field’)”>





onChange Event


Occurs whenever a form object loses
focus AND its value has changed.


Works with Input element type “text”


Works with the Textarea element


Works with the Select element


Example


<INPUT TYPE=“text” Name=“text1”
onChange=“alert(‘You have just modified form
element text1’)”>





onClick Event


Occurs whenever a form object is
clicked with a mouse.


Works with Input element types
“button”, “checkbox”, “radio”, “reset”,
and “submit”


Example


<INPUT TYPE=“button” Name=“button1”
onClick=“alert(‘Button1 has been clicked’)”>





onFocus Event


Occurs whenever a form object
receives focus


Works with Input element type “text”


Works with the Textarea element


Works with the Select element


Example


<INPUT TYPE=“text” Name=“HocusPocus”
onFocus=“alert(‘HocusPocus has Focus’)”>





onSelect Event


Occurs if the text has been highlighted
via a dragging of the mouse or tabbing
into non
-
empty fields


Works with Input element type “text”


Works with the Textarea element


Works with the Select element


Example


<INPUT TYPE=“textarea” Name=“textarea1”
onSelect=“alert(‘Text has been selected’)”>





Events on Links


onClick, onMouseover, onMouseout


Add event(s) as an attribute to the <A
HREF> object HTML tag.


<A HREF=“http://www.somecompany.com”
onMouseover=“window.status=‘Specializes in
Custom software code’;return true”>Go to
Somecompany</A>





Events on (Un)Loading Windows


onLoad and onUnload events


Use as an attribute to the <BODY>
tag.


Can also be used with the <IMAGE>
tag


<BODY onLoad=“alert(‘Welcome to my Lair’)”
onUnload=“alert(‘You
\
’ll be back’)”>





Functions and Methods


A Function is a set of JavaScript statements
that perform a task


A Method is basically a pre
-
defined function
associated with an object.


ALERT() is a method


DoSomething() is a function that you create


WRITE is a method for the document object


Functions


Should be placed in the <HEAD> portion of
the document


JavaScript statements within a function are
not executed until the function is called


Format is


function displaymessage() {



alert(“Another annoying popup”);


}



Can pass parameters within the ()

Methods


Associated with an object


-
window.open(‘http://www.yahoo.com’,
‘window1’, ‘scrollbars=yes, status=yes,
width=300, height=300’)


-
history.back()


-
prompt(“Enter your name”, “ “)




Image Rollovers


Easy to implement


Uses Event Handlers and Document
Object Referencing


Can make a function which handles all
image swapping




Verifying Form Data


Save time


No need to go to server


Can do this with a JavaScript Function


<FORM ACTION=“serverstuff.cgi”



NAME=“myform”



onSubmit=“return VerifyForm(document.myform)”


>



Debugging JavaScript


Most time spent debugging


Stay calm


Use Alert boxes


Check for syntax


Check for missing brackets or typos


Code little pieces at a time and test


Comment your code


JavaScript is CaSe SeNsItIvE




The Common Gateway Interface


CGI


Protocol not a Language


CGI scripts are programs that follow the CGI
protocol


Interactive web sites take advantage of CGI to
process data on the server


Use CGI to create e
-
mail, search databases, log
activity or even put a counter on a page


PERL is the most common programming language
that is used for CGI


PERL


Practical Extraction and Report Language


Originally written for scanning text files,
extracting information and printing reports


Expression syntax resembles C


Interpreted language and highly portable
across systems


WEB programming choice


Many available scripts


PERL for the Web


A few things are needed for PERL to work properly


Shebang Line

#!/usr/bin/perl


HTML header



print “Content
-
type: text/html
\
n
\
n”;


Two “
\
n” are required


Save file as .pl


Upload File to server as ASCII


Place in cgi
-
bin directory and CHMOD to 755



Variables and Expressions


Numbers and Strings


Constants and Variables


Scalars



$myvar = Jim


Arrays



@myarray = (“Jim”, “Harry”, “Sally”)


Hashes



%myhash = (“Jim”, “Schmidt”, “Harry”,



“Carrey”, “Sally”, “Jones”)

Operators and Functions


+,
-
, *, and /


$average = $totalamount / 10


If ($average == 10) { code }


If ($average != 10) { code }


} else { code }


Functions perform an action


print (‘My first PERL script’)


Functions


Pre
-
defined functions and functions you create


Functions can changed operands or return a result
value


Shift(@names) would modify the @names array by
shifting all values down 1 and returning the first
item in the array


Sort (@array) will sort the array in ASCII order


Subroutine is a function you create

sub dosomething {


some code


return 1;

}

Environment Variables


Supplied by Server every time you request
a page


Stored in a special hash variable called
%ENV


Can be used to determine if the Get or Post
method was used


Other variables show the IP address of
sender, what browser they are using, and
the Current Date

GET vs POST


GET appends data onto the URL


POST places data into the STDIN


Data is in the form name/value separated by an ‘&’
for all the fields of the form being submitted


REQUEST_METHOD will contain GET or POST


QUERY_STRING will contain the data for the GET
method


CONTENT_LENGTH will contain the data found in
STDIN for the POST

ParseForm Routine


Generic Subroutine to get all the form data and
place into a hash called %formdata


Works for GET or POST


Can be included into the PERL source code with
the “require” statement


Form elements can be accessed using the format
$formdata{‘key’}


Creating E
-
Mail


Use %formdata to create an E
-
Mail


Open up a pipe to the mail program



open(MAIL,”|/usr/lib/sendmail
-
t”)



Use “print” function to send data to the mail
program



print MAIL “To: $formdata{‘recipient’}
\
n”;


Need two “
\
n” at end of mail header before data
section starts


When done use “
close(MAIL);
” to close pipe and
send the mail

Creating E
-
Mail


When performing an “open” always add an Error
Handler



open(MAIL,”|/usr/lib/sendmail
-
t”) ||




&ErrorMessage;


Can use a “label” to perform piping



print MAIL <<_EOT;



..stuff ..



_EOT



close(MAIL);

Formatting E
-
Mail


Can access form field by name



$firstname = $formdata{‘firstname’};


Can print all fields with a loop



foreach $key (keys(%formdata)) {




print MAIL “$key = $formdata{$key}
\
n”; }


Can format the values



$amount = $formdata{‘amount’};



$formatamt = sprintf(“
\
$%.2f”, $amount);



print MAIL “amount = $formatamt”;

Creating HTML


MIME content header


Format HTML with the print function


Use a backslash “
\
” before special characters so
PERL doesn’t try to interpret them.


Add a newline character (
\
n) where you would like
a return in the HTML


Route to an existing HTML page using the Location
header



print “Location: /webpages/thankyou.html
\
n
\
n:;

Working with Files


We can read and write to files on our server


Use the “open” command



open (MYFILE , “>../files/myfile.txt”) ||



&Error);


A “filehandle” is created


To write data to the file use the print function



print MYFILE “data”;


Can read one record at a time or the whole file



$record = <MYFILE>



@wholefile = <MYFILE>


Working with Files


File can be used as a database. Simply add
delimiter

characters when writing the data out


When the data is read back in, use the
split

function to split on your separator character to build
an array and/or hash.


Good idea to lock a file if you are going to be
writing to it. Use the flock(MYFILE,2) function