AA notes.doc

83
NOTE: THESE NOTES ARE INTENDED TO BE SKETCHES ABOPUT WORK DONE IN CLASS Topics covered HTML JAVASCRIPT PHP MYSQL SQL STYLE SHEETS HTTP AJAX WEB SERVERS Requires AFS ACCOUNT at NJIT SSH Secure Shell for AFS file access (or similar tool) MySQL Account at NJIT (already provided to you through email notification) Software required Firefox web browser (and Internet Explorer browser) NotePad++ or TextPad (trial version from textpad.com) Please Note This file is updated before and after each class to reflect what we did in the class as closely as possible. The notes after the current class in the file are leftover from previous semesters but I have left them here for curiosity; the course topics will be covered in a somewhat different order and the examples and homework assignments will change, so only the notes up to the current class are for this semester. 1

Transcript of AA notes.doc

Page 1: AA notes.doc

NOTE: THESE NOTES ARE INTENDED TO BE SKETCHES ABOPUT WORK DONE IN CLASS

Topics covered

HTMLJAVASCRIPTPHP MYSQL SQLSTYLE SHEETSHTTP AJAXWEB SERVERS

Requires

AFS ACCOUNT at NJITSSH Secure Shell for AFS file access (or similar tool)MySQL Account at NJIT (already provided to you through email notification)

Software required

Firefox web browser (and Internet Explorer browser)NotePad++ orTextPad (trial version from textpad.com)

Please Note

This file is updated before and after each class to reflect what we did in the class as closely as possible.

The notes after the current class in the file are leftover from previous semesters but I have left them here for curiosity; the course topics will be covered in a somewhat different order and the examples and homework assignments will change, so only the notes up to the current class are for this semester.

On your AFS Account, it is your responsibility to:

Place a Blank (empty) html page named index.html in the directory (directories) on you web site that contains your homework to prevent others from seeing your HTML code.

Do not provide links on any of your web pages to any of your homework assignments, to help prevent linked access to your assignments.

1

Page 2: AA notes.doc

Class 01 Intro Tuesday January 19th (3-Tier.ppt, MySQL) – Exercise 01 MySQLOFFICE HOURS T/W/R 10-1130, R 1-230 GITC 3803 TEXT/MANUAL Internet Applications/J. McHugh.

Purchase at Canon Copier Services in basement of Cullimore Hall – under $15.00.WEB SITE http://www.cs.njit.edu/mchugh/notesIT202.html

For continual updates of notes on daily lectures see: AA notes.doc under Problems - Solutions > Class Notes > AA Spring 2010 > AA notes.doc

WEB PAGE INFO

1. Overview Course Information > Syllabus, Handout, Overview Grading, exams, text – see: Course Information > Overview List of learning objectives see: Problems-Solutions > What we will Learn

2. Web site Review web site LinksProblems - Solutions > Class Notes > A Fall 09, Assignments, AA notes.doc, etcThe notes are revised before and after each class – check them frequently !HTML + JS sites > w3Schools, etc. contains useful information.

3. JS Demos For Javascript Demos see: Introductory Survey > Survey Demos forsample student work such as Checkers Pank (AI), quizzer08a.html (time delays) OthelloPhilipKroge, Matt-Vance-SuperBlinker. These illustrate HTML/Javascript aspects of course – BUT are Not representative of the predominant PHP, server-based and MySQL database aspects.

4. MySQL Logon to MySQL and create/insert/browse/query simple database table. http://web.njit.edu/mysql/phpMyAdmin/ - you should have gotten email with account.Do Exercise 01.

What's it about? HTML, CSS, JavaScript, AJAX, 3-Tier Architecture: PHP (server-side language), programmed interface with database, MySQL, SQL, maybe for Honor's (Perl, Python).

What's the work? Participation/questions, program assignments s, lab exercises, two exams (written).

How's it graded? For basic points, see Overview (under Course Information on web site ) – I will flexibly recognize peak performances and exceptional knowledge/passion. Mechanically - an A is 90% of total points assigned, similarly for other grades –in reality I adapt the grade upwards depending on informal factors like superior performance on some assignments and participation in class. Work approx: 50% programming assignments / exercises, 40% exams, 10-15%-20% participation and attendance.

Comments Firefox – See also: https://addons.mozilla.org/firefox/60/ for toolbar with HTML tools. See TextPad.com for TextPad for Windows (might also use NotedPad++ free download). I recommend experienced students register in Honor's section. I will try to tailor assignments to your own personal level of knowledge, experience, and interest. If you have problems with the course for academic or personal reasons, consult me.

Read Text/manual -- Chapter 7 and 8 over next few weeks.2

Page 3: AA notes.doc

See AA Spring 2010 > 3-Iier Architecture.ppt for animated slide show. Discuss - 3-Tier Architecture: Browser (HTML, JS), Web Server (Apache, PHP, Tomcat/JSP), Database(SQL, MySQL), Internet (http)

Notes on your Home Page Setup -- These are comments in case you do not already have a home page set up. Your home page should be set up on the NJIT web site so you can access your NJIT MySQL account.

AFS AccountTransfer students - If you are a transfer student and do not yet have a UCID for an AFS account, go to bursar's office at the student mall and they will tell you how to get UCID/account. See also: http://ist.njit.edu/support/ucid/index.php#2

https://mailsys.njit.edu/~accts/cgi-bin/new

The link http://ist.njit.edu/webhosting/public_html.php shows how to set up a web site on your AFS account. This creates a public_html folder if you have not done so yet done.This requires your UCID and password. You may also need to refer to the links:

http://web.njit.edu/all_topics/User_Homepage/Setup/ (for accounts from before 2007)http://web.njit.edu/all_topics/AFS/windows.client/

To upload files to your web site, log on to your AFS account and place the files to be accessed under your public_html folder (or a directory under that folder).

Secure Shell SSHYou can access AFS with the SSH (Secure Shell)software available at NJIT software site (Google the words: NJIT software).

Changing your system passwordsTo change your system passwords use: https://mypassword.njit.edu/cgi-bin/upr/usecr.php

Changing your database passwordhttps://mypassword.njit.edu/cgi-bin/upr/dbpasschange.php

MySQL Account – if not received by email already, contact [email protected] from your NJIT email address and indicate your UCID and that you are taking IT 202.

Alternative assignments - Generally, I will give a fair amount of latitude to qualified people (in addition to Honor's students) to experiment with more advanced assignments if they have the background and commitment to handle them.

Honor's Assignments -- I will be providing Honor's challenge versions of assignments as we go along. One technique I will use will be to ask Honor's students to do assignments in other languages (like Perl or Python in addition to PHP). More significantly, I will propose separate projects for Honor's students that they can do instead of the standard assignments.

Class 01 Exercise 01 -- MySQL

Class 02 Exercise 02 on SQL (start with 3-Tier PPT for context) 3

Page 4: AA notes.doc

Do up to multi-table select discussion (explanation of results still required).

Class 03 Exercise 03 – Run and error check PHP program. Let class also start Exercise 04 on PHP program connection/insert to MySQL

Class 04 Exercise 04 – PHP and MySQL Exercise 02 continued - complete multi-table select discussion Tables with primary key – precludes insert duplicate keys. Clarify why one of the tables (students) has primary key and other (courses) does not. Select on multiple tables like select * from T1, T2 and Cartesian product (temporary) result and rows. Consider select like '%ba' on dictionary table. Use NotePad++ to expose blanks to explain results. Contrast '%ab ' with extra space at end.

4

Page 5: AA notes.doc

Class 05 [PPTs referred to here are animated]

What are HTML forms and brief overview of Assignment 01

For form discussion, refer to FormsPHP directory under spring 2010 web site.Used shooting metaphor for form: trigger (submit), bullets (input text fields), and target (action attribute). Considered examples m1.html and m1.php (or .txt) under directory and used Form-Program.ppt animated PPT.

For Assignment 01, overviewed key elements. Read Assignment 01.doc very carefully. See 2nd page of updated assignment description for detailed list of relevant items and where they are discussed in class manual. These will be discussed over next two weeks – in time to use them in Assignment 01. Emphasized importance of naming input elements so they can be accessed by PHP code. Assignment r=equires HTML table, timestamp data type in MySQL, etc.

Alluded to example suggested by Michael Baidoo and added under Exercise 04 directory. A question or variations along these lines will be part of midterm.

Class 06 [PPTs referred to here are animated]

Relative addressing and relocatability or portability: Form + PHP script that inserts data in MySQL: refer to Exercise 06: send.html and insertForm.php/txtTarget script is addressed relatively (filename refers to same directory from which form was downloaded). Understand why sendComplete.html is not portable: because the action targets absolute address as opposed to a relative one. Similarly understand the weakness or limitation of test.html – if target address is changed the HTML code has to be changed. This should not be! See comments under test.html. With relative addressing an entire web site can be moved around – and only the URL of the initial 'starting' form page should be impacted – but none of the HTML or PHP code.

Refer to 3-Tier Detailed.ppt under spring 2010 for role of web server (Apache) and php code.

Relation between query strings and formsExercise 05: Google Piggyback. For animated PPT see HTMLFormPiggybackGoogle.ppt under spring 2010 – reverse engineers the query string to define a form that imitates (partially) the Google home page.Check optional questions at end of Exercise 05 (midterm relevant)

HTML standards and validation: rationale for standardsTime-permitting try the HTML validation Exercise 07. Use primitiveHTML.html file under Exercise 07. Mention image and text content.

Possible midterm exam question: Check SQL question that required using three database tables added under Exercise 02.

Suggested exercises for home: try to see how to make a database table with a timestamp attribute and how you would make a PHP script that inserts an entry in it. Experiment with the PHP mail and date functions.

5

Page 6: AA notes.doc

Class 07 HTML standards and validationExercise 07 directory

Class 08 – 09 HTML (tables, input elements, Assignment 01 prototype), HTML editor

Exercise 08 - Manually construct table-organized form

Remarks – describe structure of table: table>rows>cells>content – usually same number of cells per row – make row with pair of cells - tr and td tags – th to bold center contents – form encompasses table element (for proper xml-like nesting of elements) - embed input text element, name, initialize value – add top row with contents, th, colspan both columns, attributes in start tag & contents between tags – add 3rd row with submit in one cell – text and radio group in another – single name for group elements – checked flag for default value - recap all aspects of code – where attributes go, attributes for cell versus contents – allowed contents – validate transitional – add W3C seal of approval

Exercise 09 – Use HTML Editor to reconstruct same table-form

Remarks – MS Expression Web,– carefully follow editing tasks listed on Exercise 09 sheet, such as standard set using page editor under tools, be careful of editor-generated names versus PHP $_GET name expectations or requirements, create the form before use toolbox to drag form elements into table (else get side-effects).

Exercise 10 – PHP control of HTML blocks

Remarks – blocks of HTML code can be embedded as shown (here to return a form):

if ( condition }{

PHP code?> HTML code block <?php

}else{ }

The HTML output is under the if statement control. The PHP tags just stop/restart PHP.

Exercise 11 – Styles - with an application to invisible elements

Remarks – where and how to define style rules, and how to apply or invoke (using class attribute or just element names), rules use properties of elements & their values like:img { width: 10px ; height: 20px ; } for a rule that applied to all image tags; display property & none value.

ONE SNOW DAY LOST PRELIMINARY DISCUSSION OF EXERCISE 12 ON RETRIEVALDETAILED INTERACTION/INDIVIDUAL/CLASS ON ASSIGNMENT 01 (1.5 HRS)

6

Page 7: AA notes.doc

Class 10 – 11 Data Retrieval & Assignment 02 – See problems/solution/notes under Exercises 12 / 13SEE ALSO POSTED SAMPLE MIDTERM EXAM + EXPLANATIONS

Exercise 12 – Data Retrieval - with simple layout in browserRetrieval paradigm:

$s="select * from students where name = '$name' " - define select query in $s( $t = mysql_query ( $s ) ) or die ( mysql_error( ) ) - save retrieved table of results in $twhile ( $r = mysql_fetch_array($t) ) - copy rows of $t to $r$ssn = $r["ssn"] - get ssn column from $r["ssn"]

Send output to browser with print statements and breaks.Try SQL Injection Attack on input data – see manual p. 244, etc.

Exercise 13 – Data retrieval - HTML menu wrapperSee Exercise 13 Birds directory for example of creating a large database-driven menu using PHP. See NotesBirds.txt for some notes on the code. Remember an HTML menu looks like:

<select name ="whatever" ><option value="what-1"> menu-choice-1 </option><option value="what-2"> menu-choice-2 </option>ETC

</select>Note that it is the select element that is named, not the separate option rows of the menu – though each of the rows does have a value. If a dynamically created menu is built using PHP, the choices/values are acquired from a database table via a select query. When the menu is used in the browser, the value of the selected menu row is presumably (eventually) submitted as the named value from a form so the menu must be embedded in an HTML form like

<form action ="some-script.php"> *** <input type=submit></form>

to make the select/menu element operational, including a needed submit button. The form identifies another PHP script intended to eventually "process" the data from the menu when it is used on the browser. A minor technical point is the use of the backslash notation \ to plant special characters like quotes ("s) inside other quotes (like in "action=\"x.php\"" to build the value of an action="x.php" in the form containing the menu)

See manual pp. 241-243 for constructing other HTML wrappers (like HTML tables).

Post versus Get in HTML forms -- retrieval v. insertion: see MethodNotes.txt under Exercise 08. The example simple01Manual.html uses a default Get for the method. The example simple02Manual.html under Ex 08 uses Post. If you refresh the PHP page resulting from submitting simple02Manual.html, the browser requests confirmation of the request – but does not do so for the Get request in simple01Manual.html. Also refer to: http://www.cs.tut.fi/~jkorpela/forms/methods.html for using method = get (to get or retrieve as here, default choice) versus method=post (to post or insert as in Exercise 08). See also: http://www.tonymarston.net/php-mysql/backbuttonblues.htm

7

Page 8: AA notes.doc

Class 12 Brief Intro to Javascript - events, functions, accessing input fields, dynamic HTML and dynamic properties.

PurposePHP represents a server-side language for processing requests sent by a browser and acts as an intermediary between a browser user and a background database. Javascript on the other hand is a client-side language, that is, it is interpreted (executed or run) by the browser and can dynamically interact with the browser's HTML. Unscheduled, asynchronous but common events on the browser (like mouse clicks on HTML elements or mouse movements) can be used to trigger Javascript responses which are usually implemented by Javascript functions. These Javascript responses to events can access information entered on the page, and actively modify a page's HTML elements and their contents. The examples considered here introduce the basic concepts and syntactical tools of Javascript. (Later we will see how AJAX Javascript functions can contact PHP programs in the background and use their results to alter the page.)

Topics functions, definitions & activationwhere Javascript goes – script tagsJavascript (JS) events to trigger functions – onclick, onload, onkeyup, onblur, onmouseover, etcalert function – used here to test operation of the script setup & pop-up messages to useranother window?document.getElementById ( id ) -- key JS method or functionid attribute – works in tandem with getElementById methoddotted hierarchical notation for accessing HTML element properties.value notation (for input field contents) error diagnostic tools in Firefox (Error Console) and Internet Explorer style rules such as for body, style properties – background, color, fontSize JS v. style rule names.style attribute used in Javascriptlive changes to styles using JavascriptJavascript Strings, concatenation operator in JS: +, parseInt and implicit type conversionRetrieving and storing results in elements

RGB Color ExampleMake a simple HTML page and Javascript that allows you to input the hexadecimal colorcomponents for a color in 3 separate input fields. A click on a button should then use these inputs to change the background color of the HTML body.

Background for problem:Describe RGB color modelHexadecimal notation for colors: 00….FF for each color componentPixel color components: Red, Green, BlueColor intensities, additive color modelWhite as FFFFFF (full intensity per pixel), black as 000000 (signals off per pixel, so dark)Compare Word color selector tool and RGB decimal notation

Development

1. function notation, definition, placement of code, HTML Form, button event, built-in alert for test, syntax errors – Firefox tools – IE tools.

2. Input field with id, document.getElementById ( id ).value, retrieve/store based on id.8

Page 9: AA notes.doc

RGB Problem Solution – posted under exercise 14 after class

Remarks during in-class development of Javascript RGB example:

Define function with alert message function f( ) { alert ( "hello" ) }

And place in head. Use IE first.Definition of function – appears as text on page – not desired.Place definition in script element, reload the page – does not appear, but does not execute

<script type="text/Javascript"> -- just Javascript has no effectfunction f ( ) { … }

</script>Now add function call/invocation in script element – then f executes on page load

<script type="text/Javascript">f( ) function f ( ) { … }

</script>Remove call from script element; Add function call in body element using event – onload = "f ( )"Misspell alert – try in Firefox, no action – check Tools>Error Console>error messages

In IE: Tools > Internet Options> Advanced > Enable debug & display messages Retest and note line numbers

Remove onload. Add onclick in button element in Form: <form>

<input type=text ><input type=button onclick="f( )" >

</form> Acquire data from input field – add id=1 in input field, u = document.getElementById(1).value assignment statement,

Put u in message with concatenation alert("hello " + u) Add style rule in style element in head (later we'll introduce dynamic styles)

<style type="text/css">body { color: yellow ; }

</style>

In-class Student Lab Exercise – see Exercise 14

Make simple multiplication calculator that takes pair of values A and B and outputs product A*B in field. Use RGB example as reference model. Add id=2, 3 fields for u * v setup and answer. Comment out alert: //alert ("hello " + u) .

Class 14 Introduction to Javascript patterns

Refer to Assignment 03 under spring 2010 directory -- see examples listed there including ReadMe.txt outline and pattern1.html example (see source)

Class 15 Midterm Exam -- FULL PERIOD

9

Page 10: AA notes.doc

Class 16 – 17 Assignment 03 and Javascript patterns -- continued

This class continues the discussion of patterns and their syntax started before the Midterm [and Spring break]. The topics are basic to solving the posted Javascript Assignment 03.

Pattern Recognition Syntax – patterns are so-called "regular expressions" that detect systematic textual patterns in strings of characters. Their basic notation follows and is common to many programming languages.

1. Begins and ends with forward slashes: / /2. The symbols ^ and $ can be optionally used to force the pattern to match the comparison string from its

beginning ( ^ ) to its last character or end ( $ ). Experiment with the previous example without the anchors at ^ and $.

3. A-Z matches any single letter from A to Z; similarly a-z; 0-9 gives digits. 4. The repetition operator + means one or more matches of the pattern (but not zero) is required: thus [A-Z]

+ matches any non-empty repetition of capital letters. The + applies to the previous group – here the [A-Z].

5. The period is a special character in JS patterns (which matches any single character), so to use it as a character to match you must write \. instead, using the backslash -- as for other special characters.

6. Square brackets [ ] or parentheses ( ) can identify the pattern being repeated by a repetition +. You could group several sub-patterns like [A-Z][0-9] in parentheses and repeat like ([A-Z][0-9])+. Importantly, alternatives have to be included inside parentheses to work right, like /^(boy|girl)$/.

7. Single symbols like an @ can be matched directly. A single symbol matches that single character. This includes the blank! Blanks embedded in a pattern are used as part of it!!

8. If s is the string being tested for a pattern and p is a variable that contains the pattern being searched for, then the function call s.search(p) returns -1 if the pattern is not in the string s – otherwise it returns the index of the location in the string where the pattern first occurs (starting from the first position at zero.

9. A notation like (\.edu|\.org|\.com) matches any one of the alternatives .edu etc. The vertical slash | denotes an or that is an alternative. Notice there are no blanks present in the above pattern such as around the vertical slash operator since a space or blank is itself considered as a character to be matched.

10. The notation {m,n} (or {m}) where m and n are integers (variables) that equal integers matches from m to n occurrences of the previous sub-pattern. For example [aeoiu]{1,2} matches one or two vowels.

Hands-on: Recognize the pattern: First-name Middle-initial Last-name as in: John Q. Public. What's the textual pattern? How do you ignore spaces/blanks appropriately? Note: there is no built-in trim function in JS.Hands-on: How do you handle a sequence of data fields being validated -- like an Age input after a field that tests for a name like in Assignment 03. How does the same submit event trigger checks for both patterns? Hands-on: How do you post warnings in a page when there is an error in the input – other than by using an alert popup -- like too young or too old in the case of Age, and in a visually effective way. Hands-on: How do you reset the warning fields to their initial clear state if valid data is submitted.Hands-on: How design a test plan and including a criterion for valid data and expected kinds of test results?

Assignment 03 pattern for Height in Feet and Inches – it should handle these correctly:5'8" valid5' 8" valid5' 12" invalid [12' makes another foot]5' valid5 ft. 8 in. valid5 ft. valid5ft. valid

10

Page 11: AA notes.doc

5 in. invalid [too short]

Some references Manual pages 124-130 http://www.javascriptkit.com/javatutors/redev2.shtml http://www.java2s.com/Tutorial/JavaScript/0520__Regular-Expressions/TestingforPatternMatches.htm

11

Page 12: AA notes.doc

Classes 18-19 AJAX -- and -- help individually on assignment 03 on patterns

Refer to examples under Assignment 04 (such as hello.html, .php, .txt and AjaxDB1.html, etc) PowerPoint slides (michael.pptx) overview Ajax frameworkFor Ajax see manual pages 171 – 175(7) & pp. 254 etc.

Illustrate Ajax framework with simple hello program: Use basic Ajax html template with onkeyup and target div for the HTML page (hello.html)Build up target hello.php from (incrementally verify/explain effects):

1. Initially a non-existent PHP file! – see what happens when Ajax invokes it.2. The empty PHP file <?php --- ?> 3. Successively add/test where PHP prints "hello" then "Goodbye" – with separate print's4. Then add a <br> tag to first print5. GET and also echo the data sent by Ajax function6. Add an alert ( response ) in handleResponse function before innerHTML statement

and observe different content of alert versus content shown in div element.

Demo AjaxDB1.html/php (gets words from database that start with typed string)Problem: Figure out how to implement the code for AjaxDB1.php:

0. Import dictionary.txt into database table.1. Connect to database2. Define SQL query $s that selects words from database that begin with the string sent by

browser – use SQL like operator.3. Run query $s and save results if $t4. Use while loop to process $t and "print" results to Ajax

Key points about AJAX framework:1. Create HTTP object: Boilerplate use of createRequestObject function to make http object (code

used depends on the browser!) Notice definition versus execution of the function! 2. Send Request to server: sndReq function to send http request to web server.3. Asynchronous: sndReq works in background asynchronously (the 1st A in AJAX).4. User-defined Event handler: handleResponse (or responder) function handles web server response.5. Event recognition: handleResponse only acts when the onreadystatechange flag is 4 (meaning

response completed).6. Identifying Event handler: onreadystatechange in sndReq identifies the handler function for the

response to the request.7. Response content: response is generated by PHP output print statements whose results are

concatenated in http.responseText, as well as any content from outside the PHP section of PHP program file.

8. Applying response: The response can be processed in Javascript function or just directly deposited in the HTML page as here using: document.getElementById (200).innerHTML = response which replaces the current contents of element 200 (in this case). Or content could be placed anywhere else on page with an id.

9. OPEN function: sndReq makes the request using the http.open function. Requires method and URL plus here a query string.

10. Making HTTP get Request: open function identifies the HTTP method used (in this case get) and gives the “query string” that identifies the server-side program that handles the request and its data.

11. Making the query string for get: The fragment 'Ajax00.php?v=' here indicates the URL Ajax00.php (assumes current web server directory) and that the PHP program will use $_GET ['v'] to

12

Page 13: AA notes.doc

get the data. It also concatenates the value of the data in the variable u. Do not insert spaces inside the query. The extra junk variable is used to force request to be done from the web server.

12. Getting HTML field data: The value of u is picked as u = document.getElementById(100).value13. ONKEYUP Event: An onkeyup event has been used for the input field that is natural to the

interactive mode of the example14. Database access possible: The PHP program can be enhanced to use the AJAX supplied data to

access a database as in the Google Home page example which Assignment 04 will simulate.15. Avoiding cached copies: The string + "&junk="+Math.random ( ) in the open function seems

obscure. You could omit it but what it does is ensure that new requests with the same data as a previous request don’t just get responded to by the browser with a stale cached copy of the results (which may be different if the PHP program has been modified). This string includes an artificial variable named junk with a random value (and so different each time) in the query string. This way each request is different so a cached copy cannot be used. The & before the junk variable is the usual ampersand that is used to separate variable=value pairs in a GET request.

Preliminary description of Assignment 04 Simulate Google Home page using your own personal database table (such as by importing dictionary.txt under Assignment 04 into your database). See HW problems and their solutions – currently:

1. AjaxBB1/html/php/txt for extracting information from database using Ajax2. Div Highlighting HW.txt/.JPG – solution to be posted3. Automatic form submission to Google – DivGoogleRequest.JPG – solution to be posted

Problem: Try to implement the highlighting behavior for a pair of div's as illustrated in the file Div Highlighting HW.txt/.JPG – using HTML and Javascript. Solution will be shown next class. See Div Highlighting.txt under Assignment 04 directory

To Instructor: illustrate but do not post the div01.html example – show behavior but not code.

Advanced Note:To see how to use Post instead of Get method: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

Try/experiment with CopyFileName.html – just html – has no PHP file associated with it.

13

Page 14: AA notes.doc

Classes 20-21 HTTP

Under Assignment 04 directory, refer to:

1. Solution to previous HW: div01.html , Highlighted Div Solution.ppt2. Next HW problem – JS-based form submission: DivGoogleRequest.JPG, google.html3. Understanding HTTP: HTTP Interaction.ppt, HTTP.txt4. Presentations/reports – week of April 19th – all students – 4 minutes + Word doc report with ref.5. Assignment 04 overview - Google home page effects

Class 21

1. GoogleProblemdiagram.ppt - overviews Asgt04 flow – also show Google page and relate to div's in HW highlighting, copying, form submission – Ajax DB example (AjaxDB1.html/php/txt) to underlying database for this effect

2. Solution to HW problem: Google form effect with static div's: div01GoogleForm.htmla. Form elements – action, named text field, id for form element, submit ( ) function, no submit

button!b. To make div's in PHP with database content, need to know what the static versions look like.

3. After this then GoogleProblemdiagram.ppt again (+AJAX PPT overview).a. Show flow of events/actionsb. Static div where Ajax content deposited versus dynamic div's manufactured in PHP

4. Questions and responses:a. How does Ajax work? – overviewed AJAX Overview.ppt – how sndReq called [by user event],

how responseText is packed like a chain of train cars of data from the print's in the PHP code.b. When does http object there get created? – when page is first loadedc. Look at Firefox Live headers plug-in to trace http exchanges triggered by the sndReq calls – look

at the Get request – with v and its value – as well as the always changing junk variable's value to force browser to not use any cached copy of results and to truly contact the server.

d. When do we use this code or modify? – the creation part is boiler plate for Ajax usage, and http object created when page loaded by browser – in this example only one

e. Why use Ajax rather than a Form? – the form disrupts the page, the Ajax does notf. Where is the variable for the PHP program triggered by the Ajax represented if not in a form

named field? – in the query string in the sndReq function.g. When is handleResponse called? – called by browser when the response is done – not by a user

event like sndReq is.5. Presentations PPT again – next week have the ideas ready.

Rest of class helped with Assignment 03 on patterns: Issues included:Using div tags for messagesGiving them styles

If time permits consider images and events / more HTTP.

14

Page 15: AA notes.doc

Class 22 Uploading Files in PHP

References: Manual pages 198-208http://www.meandeviation.com/tutorials/learnphp/php-syntax-check/http://us2.php.net/manual/en/

Terms: authorizing http write privileges, enctype encoding type, multi-part/form-data, input type: file, method: post, PHP built-in functions: move_uploaded_file ( string $filename , string $destination ), file_exists ( string $filename ), temporary location of upload, $_FILES built-in associative array of upload properties, global variable, $_FILES ["A"] ["name"], $_FILES ["A"] ["size"], $_FILES ["A"] ["type"], $_FILES ["A"] ["tmp_name"], $_FILES ["A"] ["error], MIME type/subtype pair, "image/pjpeg", "image/gif", "text/html”, "application/msword", or-die hurdles or gauntlet.

UNIX HTTP write privileges – In order to upload file and store it on your site, you must authorize this by running the following Unix command in an AFS terminal window. This assumes your target directory to upload to is under testUp under your public_html folder:

/usr/afsws/bin/fs sa ~/public_html/testUp http write

The command: /usr/afsws/bin/fs sa . http write should work for your "current directory" if you open a Unix terminal in that directory. The write privilege automatically applies to subdirectories.

HTML Form for Upload

<form action ="up00.php" method="post" enctype="multipart/form-data" ><input type = "file" name="A" /><input type = "submit" name="submit" />

</form>

Rudimentary upload program (make sure to include password protection so others don’t upload to your directories! ). The following command uploads to the same current directory where PHP program is:

move_uploaded_file ( $_FILES["A"]["tmp_name"] , "test.txt" ) ;

BUT this only makes sense if the file is a text file. The following more complex notation is more appropriate since it names the uploaded file correctly and with its correct type:

move_uploaded_file ( $_FILES["A"]["tmp_name"] , $_FILES["A"][ "name" ] ) ;

Password protection: It is important for security reasons to restrict an upload service by demanding a password from the Form. For example, if the Form has a text field “B”, then the PHP can use:

( $_POST["B"] == "whateverPassword" ) or die ( "Invalid password." ) ;

15

Page 16: AA notes.doc

To move an uploaded file to a subdirectory sub under the current directory use:

move_uploaded_file ( $_FILES["A"]["tmp_name"] , "sub/" . $_FILES["A"][ "name" ] ) ;

where the period denotes the PHP concatenation operator.

Information about the uploaded file is contained in the $_FILES array which is a built-in associative array (like the array $_GET["B"]) that contains information about the upload request:

$_FILES["A"][ "name" ] file name$_FILES["A"][ "tmp_name" ] where stored temporarily on server$_FILES["A"][ "size" ] number of bytes$_FILES["A"][ "type" ] MIME types like: text/html, image/gif, image/pjpeg$_FILES["A"][ "error " ] 0 if successful

You can filter or restrict upload request using or-die constructions (which act like hurdles or a gauntlet ). It is especially important to always include a password restriction.

( $_POST["B"] == " whateverPassword " ) or die ( "Invalid password." ) ; ( $_FILES["A"]["size"] < 30000 ) or die ( "File too big." ) ;( ( $_FILES["A"]["type"] == "image/pjpeg" ) || ( $_FILES["A"]["type"] == "image/gif" ) )

or die ( "Invalid type." ) ;( ! file_exists ( $_FILES["A"]["name"] ) or die ( "Overwrite not allowed" ) ;

The last filter checks if the uploaded file already exists and only allows the request if there is no file of the same name.

Suggested Exercises: Experiment with examples under Upload Examples directory. Be sure to authorize the UNIX HTTP write privileges first. up01.php checks for a password before doing upload and echoes the password, filename and temporary file location; up03.php checks password, file size -- allows only < 80000 bytes -- and file type -- gif or jpg. Basic HTML and PHP code for these follows.

Problem: Try to extend up03.php to also allow Word doc (of an acceptable size).

up01.html:<form action = "up01.php" method = "POST" enctype = "multipart/form-data" >

<input type = "file" name="A" />File<br><input type = "text" name="B" />Password<br><input type = "submit" name="submit" />

</form><pre>Requires password.</pre>

up01.php<?php//Don't forget to authorize write:

16

Page 17: AA notes.doc

// /usr/afsws/bin/fs sa ~/public_html/testUp http writeecho "<br>hello<br>" ;

$p = $_POST ["B"] ;$n = $_FILES["A"]["name"] ;$t = $_FILES["A"]["tmp_name"] ;print "<br> $n <br>";print "<br> $t <br>" ;print "<br> $p <br>" ; //check password heremove_uploaded_file( $t , $n );echo "<br>bye" ;?>

up03.php//check password here// Size OK ? ( $_FILES["A"]["size"] < 80000 ) or die ( "File too big." ) ;// Type OK ? ( ( $_FILES["A"]["type"] == "image/pjpeg" ) || ( $_FILES["A"]["type"] == "image/gif" ) ) or die ( "Invalid type." ) ;$n = $_FILES["A"]["name"];$size = $_FILES["A"]["size"];$type = $_FILES["A"]["type"];$t = $_FILES["A"]["tmp_name"];print "<br> Name of file: $n <br>";print "<br> Size of file in bytes: $size <br>" ;print "<br> MIME type of file: $type <br>" ;

move_uploaded_file( $t , $n ) ;echo "<br>File was uploaded" ;

17

Page 18: AA notes.doc

Class 23 Final Projects(s) and Discussion of Talk Topics

Final Projects

1. All should try the Google simulation assignment. Described under Assignment 04 directory.

See RubricDescriptionAsgts04Materials.txt for list of relevant files.

2. Students with estimated grade of B+ or A should also do the Two-Menu-Problem. This is due the day of the final or before. Described under Assignment 05 directory. Try Ajax.php (which also invokes Ajax1.php using an Ajax function call). You can use:

States and Codes.txt -- for States database tableStates and Cities.csv – for States and cities database tableTwoMenuProblemdiagram.ppt – for flow of events in the problemAjax-PHP-Menus.ppt – for outline of problem solutionAjax.php and Ajax1.php and account.php for demo

Time permitting: check http request & response using Firefox live headers. This yields only response header not response body. Firebug plug-in shows the response text under HTML and DOM tabs there. In Live headers note Get when Connecticut is requested [has code = 900000]. You can use Unix terminal window to trace HTTP response body [ ! ] (but it's not shown in Firefox Live headers tool). Put Ajax & Ajax1 & account.php files under test directory under public_html. Then telnet web.njit.edu 80 to connect to web server & make http get request:GET /~mchugh/test/Ajax1.php?v=900000 HTTP/1.0 to fetch cities in selected state [here Connecticut with code 900000].

3. Students with estimated grades of B or less, should instead do the Alarm Clock Javascript assignment under Assignment 05 directory. This is due the day of the final or before. You should refer to:

AlarmSeconds.html – for basic example of clock [using seconds only] with alarm & soundAlarmClock.jpg- - image of solutionAlarmClockDebugFeature1.jpg - - image of solution with debug optionAlarmClockDebugFeature2.jpg - - image of solution with debug optionAlarmClock.doc – for general directionsAlarmClockTemplate.html – for skeletal plan for solution

In demo – note debugging military time input & how clock values comes from the system clock [exhibit analog second display]. Try values like midnight, 0 hr, noon, 1 in afternoon. For sound file may need to use harp.njit.edu

Classes next week will focus on explaining aspects of the Alarm Clock assignment for the students who will be doing that and will require extensive work with individuals.

Presentations will be week of April 26th.

18

Page 19: AA notes.doc

Be prepared – including post any links of visual materials on your web site – or be prepared to plug your laptop into the room projector.

19

Page 20: AA notes.doc

20

Page 21: AA notes.doc

21

Page 22: AA notes.doc

22

Page 23: AA notes.doc

Last Semester -- Not same as current semester

Last Semester -- Not same as current semester

Last Semester -- Not same as current semester

Last Semester -- Not same as current semester

Last Semester -- Not same as current semester

Last Semester -- Not same as current semester

Last Semester -- Not same as current semester

Last Semester -- Not same as current semester

23

Page 24: AA notes.doc

Topics covered

HTML STYLE SHEETS JAVASCRIPT PHP MYSQL SQL HTTP AJAX WEB SERVERS

Requires

AFS ACCOUNT at NJIT SSH Secure Shell for AFS file access (or similar tool) MySQL Account at NJIT (already provided to you through email notification)

Software required Firefox web browser (and Internet Explorer browser) NotePad++ TextPad (trial version from textpad.com) Please Note

This file is updated before and after each class to reflect what we did in the class as closely as possible. The notes after the current class in the file are leftover from previous semesters but I have left them here for curiosity; the course topics will be covered in a somewhat different order and the examples and homework assignments will change, so only the notes up to the current class are for this semester.

On your AFS Account, it is your responsibility to:

Place a Blank (empty) html page named index.html in the directory (directories) on you web site that contains your homework to prevent others from seeing your HTML code.

Do not provide links on any of your web pages to any of your homework assignments, to help prevent

linked access to your assignments.

24

Page 25: AA notes.doc

Class 01 Intro -- Tuesday Sept 1st (Basics, Demos, 3-tier.ppt, MySQL)

OFFICE HOURS Tues 11:30-1:00 & 4:00 -5:30 / Thurs 5:30-6:30 / W 10-11 TEXT/MANUAL Internet Applications/J. McHugh.

Purchase at Canon Copier Services in basement of Cullimore Hall – under $10.00.

WEB SITE http://www.cs.njit.edu/mchugh/notesIT202.htmlFor continually revised notes on daily lectures see: AA notes.doc underProblems - Solutions > Class Notes > AA Fall 09 > AA notes.doc

WEB PAGE INFO

1. Overview Course Information > Syllabus, Handout, Overview Grading, exams, text – see: Course Information > Overview List of learning objectives see: Problems-Solutions > What we will Learn

2. Web site Review web site LinksProblems - Solutions > Class Notes > A Fall 09, Assignments, AA notes.doc, etcThe notes are revised before and after each class – check them frequently !HTML + JS sites > w3Schools, etc. Contains useful information.

3. JS Demos For Javascript Demos see: Introductory Survey > Survey Demos forsample student work - Matt-Vance-SuperBlinker, quizzer08a.html, build01.html, MattQuiz-BrendaDavis, Checkers Pank, OthelloPhilipKroge, MasterMind: These examples illustrate HTML/Javascript aspects of course – BUT are Notrepresentative of the predominant PHP server-based and MySQL database aspects.

4. MySQL Logon to MySQL and create/insert/browse/query simple database table. http://web.njit.edu/mysql/phpMyAdmin/ - you should have gotten email with account.

What's it about? HTML, CSS, JavaScript, 3-Tier Architecture: PHP (server-side language), programmed interface with database, MySQL, SQL, maybe for Honor's (JSP, Perl).

What's the work? Participation/questions, programs, exams (written).

How's it graded? For basic points, see Overview (under Course Information on web site ) – I will flexibly recognize peak performances and exceptional knowledge/passion. Mechanically - an A is 90% of total points assigned, similarly for other grades –in reality I adapt the grade upwards depending on informal factors like superior performance on some assignments and participation in class. Work approx: 50% programming assignments, 40% exams, 10-15%-20% participation and attendance.

Comments Firefox – See also: https://addons.mozilla.org/firefox/60/ for toolbar with HTML tools. See TextPad.com for TextPad for Windows (might also use NotedPad++ free download). I recommend experienced students register in Honor's section. I will try to tailor assignments to your own personal level of knowledge, experience, and interest. If you have problems with the course for academic or personal reasons, consult me.

25

Page 26: AA notes.doc

Read Text/manual -- Chapter 1, some of Chapter 7, 8 over next few weeks.

Time permitting, discuss - 3-Tier architecture: Browser (HTML, JS), Web Server (Apache, PHP, Tomcat/JSP), Database(SQL, MySQL, MS Access), Internet (http, TCP/IP), TextPad, NotePad++.

See Fall09 > 3-tier.ppt

Recommended Exercises A and B (try this, but do not hand in results):

A. Post a simple web page on your web site (ensures you have active site).B. Create a database table with two attributes on your MySQL account and list it (checks your account).

Notes on Home Page Setup -- These are comments in case you do not already have a home page set up. Your home page should be set up on the NJIT web site so you can access your NJIT MySQL account.

AFS AccountTransfer students - If you are a transfer student and do not yet have a UCID for an AFS account, go to bursar's office at the student mall and they will tell you how to get UCID/account. See also: http://ist.njit.edu/support/ucid/index.php#2

https://mailsys.njit.edu/~accts/cgi-bin/new

The link http://ist.njit.edu/webhosting/public_html.php shows how to set up a web site on your AFS account. This creates a public_html folder if you have not done so yet done.This requires your UCID and password. You may also need to refer to the links:

http://web.njit.edu/all_topics/User_Homepage/Setup/ (for accounts from before 2007)http://web.njit.edu/all_topics/AFS/windows.client/

To upload files to your web site, log on to your AFS account and place the files to be accessed under your public_html folder (or a directory under that folder).

Secure Shell SSHYou can access AFS with the SSH (Secure Shell)software available at NJIT software site (Google the words: NJIT software).

Changing your system passwordsTo change your system passwords use: https://mypassword.njit.edu/cgi-bin/upr/usecr.php

Changing your database passwordhttps://mypassword.njit.edu/cgi-bin/upr/dbpasschange.php

MySQL Account – if not received by email already, contact [email protected] from your NJIT email address and indicate your UCID and that you are taking IT 202.

Alternative assignments - Generally, I will give a fair amount of latitude to qualified people (in addition to Honor's students) to experiment with more advanced assignments if they have the background and commitment to handle them.

Honor's Assignments -- I will be providing Honor's versions of assignments as we go along. One technique I will use will be to ask Honor's students to do assignments in other languages (like Perl or Python in addition to

26

Page 27: AA notes.doc

PHP). More significantly, I will propose separate projects for Honor's students that they can do instead of the standard assignments.

Note: see also AA Supplemental Lecture Comments.doc under AA Fall 09 for extra comments

27

Page 28: AA notes.doc

Class 02 / 03 / 04 ( Thursday Sept 3rdd , Tuesday Sept 8th , Thursday Sep 9th )

Class 02 (MySQL import, image capture/tool, img tag / validation) Class 03 (HTML skeleton, DOCTYPE/encoding, styles, validation)Class 04 (hyperlinks, Firefox error console, HTML editors)

Assignment 01 – see also under Asgt01Fall09 directory

Due Monday Sept 14th @ noon. Send only email LINK to your HTML solution and the account name & password for your MySQL account. Do Not send it as attachment. Not following these rules will cause delays and may make your homework late for which you will lose credit. Points: 25 points:

1. Access your MySQL database with the account name and password sent to you by the system administrator before the semester started at: http://web.njit.edu/mysql/phpMyAdmin/. Remember student accounts use sql2.njit.edu. Create a database table with a few columns and enter some rows of data. Execute an SQL Select query like Select * from People where Age > 10 (the names depend on the table and column names you use). Snapshot the screen with the SQL results and query. Then make and validate an HTML page, that contains: an image of the MySQL page with the results of the SQL Select query and a hyperlink to an image of your HTML validation page results.

2. The HTML page and the snapshot images should be in a directory on your web site that contains a blank HTML page index.html and with no link otherwise to the homework page.

Use http://web.njit.edu/mysql/phpMyAdmin/

Enhancements for 10 extra points

enter data from text file using import option in MySQL validate the page under strict HTML (rather than transitional HTML) define and apply a style rule for the image dimensions hyperlink to a copy of the MySQL image in a subdirectory of the directory containing the HTML page

Concepts: standards validation, HTML page structure, DOCTYPE, character declaration, strict versus transitional standards, color-coded syntax editors, MySQL database, database tables, data definition, screens to create table, select data types, insert rows, delete rows, drop tables, browse contents, table structure, execute SQL select statement.

Work thru exercise in class lab

1. Demo assignment partial solution.

2. Logon to MySQL (open source database)

3. Create table (make up one) with data types

4. Populate table manually (SQL inserts) and import from text file

5. Browse table, edit/delete entries

28

Page 29: AA notes.doc

6. Use SQL Select query to list contents of table

7. Snapshot table contents in MySQL - use <alt> Prnt Scrn

8. Paste, Save snapshot as PNG file (properties) – use mspaint.exe, also compare bit map, JPEG & GIF size and quality of image. Display in browser.

9. Make simple HTML page with img tag and hyperlink. Display page using desktop environment.

10. Validate HTML page > http://validator.w3.org/ -- correct errors – DOCTYPE, encoding, title, tags, alt. Consider using attribute bgcolor="cyan" for body element. Do with strict DOCTYPE (and also use the options in validator to test transitional instead). Save results ?

11. Upload files(s) to web site and retrieve from Apache web server using browser (http request). SSH, public_html, subfolders, Unix capitalization sensitivity vs. Windows.

Links related to validation errors

For DOCTYPE see http://www.w3.org/QA/2002/04/valid-dtd-list.html - for strict HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">

or:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

For character encoding tag see http://www.w3.org/International/O-charset - commonly used:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >

For a list of deprecated attributes see http://www.codehelp.co.uk/html/deprecated.html.

HTML01.ppt under Assgt01Fall09 directory has Powerpoint animation overview of HTML related to Asgt01.

References to Internet Application Manual

Chapter 1 > Basics - especially pages 12 – 17Chapter 1 > Hyperlinks - pages 21 - 22Chapter 1 > Images - especially pages 24 – 37 Chapter 2 > Validation of HTML especially pages 79 – 83, 84 - 85Chapter 7 > SQL and MySQL > especially pages 207 – 219

Web site > AA Fall 09 > Assgt01Fall09 > HTML-snippets.txtWeb site > AA Fall 09 > AA Supplemental Lecture Comments.doc

Also: check index of manual.

PLEASE NOTE29

Page 30: AA notes.doc

Many of the example in Manual are listed under Book Directory under AA Fall 09 on web site.There they are subdivided into sub-directories related to topics in the text.The directory HTML Headings etc, and other directories have a number of simple examples that you can explore in tandem with the Manual.

Systems involved: browsers, online database, SQL, HTML, web server, image formatting tools, validation and HTML standards, specific HTML elements: img, hyperlinks, style element, attributes, deprecated, style properties & rules, error tools in Firefox, quirks mode fall-back (see Firefox>Tools>Page Info>render-mode)

Reading for next class (class 04): Chapter 5 > especially direct HTTP request – pages 173-177.

Lab continued

12. Upload one-line HTML to public_html folder and retrieve with browser. Create subdirectory, move files (html & image) there and retrieve with new URL. Break up URL to parts.

13. Validate HTML at validator.w3 and observe results.

14. Retrieve in Firefox and note Page > Info says quirks mode used to render file

15. Add skeletal HTML tags and revalidate. Note new results in validator.

16. Add loose HTML DOCTYPE & encoding statements and revalidate. Results indicate title tag and alt attribute problems.

17. Revalidate as strict DOCTYPE; note error about inline img element inside block element.

18. Include w3 seal of approval and try click to revalidate current file.

19. Modify img src to point to a subdirectory for image instead.

20. Replace img dimensions with a style element in head.

21. Use bgcolor attribute to set body color. Note fails in strict validation as attribute deprecated.

22. Replace bgcolor with body style rule and revalidate.

Read: Equivalent-Exercises-01 under Assignment 01 directory for fall 09 on web site.

Advanced Note: If you want to pursue the differences between some of the encodings, check the interesting article at http://techessence.info/node/60 (last accessed Sept 7, 2009) which addresses some of the issues related to UTF-8 versus US-ASCII and Latin-1. The encodings are an interesting topic but we will address it only tangentially in the class. The manual has discussions of encodings. When I validated a UTF-8 page from the NJIT web site, it was sent as Latin-1 by the NJIT web server rather than as UTF-8 which was what had been declared. Check also what happens if you retrieve a page from the site with Firefox which has the encoding reported differently (!) in the Page Info under General and headers.

30

Page 31: AA notes.doc

Class 04 – continuation of topics for Assignment 01 + Lab

HyperlinksSyntax, relative addressesHTML01.ppt animation for hyperlinksportability of relative addresses (what it means, its importance, versus absolute URL addresses)how W3 validation "seal of approval" works, check program & its referrer attribute

Firefox toolsTools > Error Console for detecting & diagnosing errorsexample: error in style rule: such rules ignored by browsers without crash (robust response), line numbers

HTML Editor [Front Page ] - or Expression Web 2.0 Pop-down menus to facilitate developing HTML, applies to attributes in tags alsoillustrate with img, hyperlink ( <a > </a> tag), and style element navigation tool for creating relative addresses

File & Directory configuration for Assignment 01Files01.ppt animation for directories and files

31

Page 32: AA notes.doc

Class 05 – 06 Introduction to 3-tier environment (HTML Forms, PHP, SQL, MySQL)

Assignment 02 will involve defining an HTML Form which sends data to a PHP program which then echoes the data back to the browser but more significantly also inserts the data in a MySQL database and a date.

Preliminary Problem Statement: Insert a Diary entry, entered by a user in a textarea on a Form, into a MySQL database table you define. Additionally, enter in the database table the date of entry (date and time of day), using either an appropriate PHP statement or an SQL command in the PHP program. The connection to the database should use an include file that contains the account information. Also, echo the diary entry (without the date information) to the browser, using a font controlled by a style rule in the page. The HTML page returned should be valid loose or strict HTML or XHTML (and include a W3 seal of approval so I can quickly validate the page myself). Require password for the user (sent from the Form) to get this service (the password should be different from the database password). If the password submitted is wrong, reject the request. Also have a link at the bottom of the returned PHP page that returns the browser back to the original Form when clicked.

Overview See Assgt02Fall09 directory: 3-tier.ppt for overview of 3-tier environment, also: PHP 02A.ppt, PHP 02B.ppt, PHP 02C.ppt. Also Asgt02.doc and Asgt02.ppt under Assgt02Fall09.

Objectives - examples & PPT under Assgt02Fall09

1. HTML Forms: syntax & purpose – action or program attribute, submit input tag, variable names, input text fields for variable values.

a. Illustrate with PHP hello program (m0.html, etc) to send message back to browser from program on server.

b. Illustrate program picking up data sent to server by Form using GET -- m0a.html, etc.

2. Illustrate web services (PHP 02A.ppt) using custom-made Google and W3 Validator Forms:a. Google.htmlb. W3Validator.html

3. Database connection & interaction: PHP 02B.ppt

a. Connecting to database - testConnect0.php, mysql_connect( $host, $use, $pass ) , mysql_select_db ( $project )

b. SQL insert – testConnect1.php, definition (string) and execution, mysql_query( ) , mysql_error( ), die( ).

c. Include account and password information file: testConnect2.php

4. More Complex PHP code – see PHP 02C.ppt -- for example: m1.html, m1.php.

PHP syntax check: www.meandeviation.com/tutorials/learnphp/php-syntax-check/

32

Page 33: AA notes.doc

Class 7 – 8 Assignment 02 3-tier Problem Contd.

Google & Validator piggyback examples – about Forms

Plan of Attack – Assgt02 Plan.doc

textarea elementname, dimensionsPHP names – variables & access via $_GETcheck query string – even on desktopHTML Form method: get – but POST method hides the data better & allows much more insert as text needs single quotes as well

password input elementversus other passwordscomparison and control of program flow with or die

testing Forms based on query strings alone in desktop environment (variables, target file)

web server versus PC desktop environment, effect of wrong extensions

PHP file layout, such as W3 sticker placement, or style element

sources of information about PHP -

inserting PHP string variable values into database table columns of type text

testConnect0, 1, 2 examples – for database interactiondistinguish their different aspects

datesPHP date function usage & inserting it as text

understand PHP function usageinsert as text type

MySQL timestamp type – defining table, several data types for dates, how to use at insertcreate table with type timestampdefault is timestamp inserted on insertCURRENT_TIMESTAMP is the insert parameter used

style sheets, link element, style rulesx.cssstyle rules as usual<link type="text/css rel=stylesheet href="x.css" >

testing for equality using die construction== operatorA or B expression – conditional evaluationdie (" --- " ) terminates program with a message

Refer also to 3-tier detailed.ppt under Assgt02 directory for overview of server environment.33

Page 34: AA notes.doc

Class 09 - 10 Assignment 03 (HTML tables, DB retrieval)

Overview of Assignment 03 -- see Asgt03Fall09a and b.ppt under Asgt09Fall directory.

Readings in Manual1. HTML Table pages 38 - 43 -- use HTML Editor to generate; note table > row > cell structure2. Dynamic tables in PHP pages 191 - 193 -- intermix calculations and HTML tags3. Data retrieval in PHP – pages 230 - 233 -- SQL select statement and PHP tools to get results

Continued Lab on Assignment 02.

Key points on retrieval syntax:

Select is the SQL command that retrieves a table from the database.If the select query is assumed to be stored in $s then:

$d = mysql_query ( $s ) executes $s and returns the results in $dCan't use: print $d ;

If $d is the result of select, then $r = mysql_fetch_array ( $d ) returns the next row of $d saved in $rCan't use: print $r;

If $r is a row from the table of results then: $r [ 'A'] gives the value in the cell for the column named "A"Can use: print $r [ 'A' ] ;

If mysql_fetch_array ( $d ) is empty (because there were no rows or you have already processed all of them), then setting:

$r = mysql_fetch_array ( $d ) ; makes $r empty – or false as far as a while statement is concerned.

If mysql_fetch_array ( $d ) is not empty (because there is a row left in the results) then setting:

$r = mysql_fetch_array ( $d ) ; makes $r non-empty – or true as far as a while statement is concerned.

The quantity $r above is called an Associative Array – which means that its contents are accessed using names like in the reference $r [ 'A'].

The standard looping control structure for accessing any selected results is:

while ( $r = mysql_fetch_array ( $d ) ) { --- ; }

Each loop iteration advances a pointer through the rows of the table until there are no more rows left to access.

If a select statement is executed, then mysql_affected_rows ( ) returns the number of rows selected. This is useful for the name & password test in Assignment 03.

34

Page 35: AA notes.doc

Note on kinds of errors:1. print " <br> $r[ 'name']"; -- causes PHP syntax error2. select from x where name = 'Bert' -- missing * - SQL errorMySQL http://web.njit.edu/mysql/phpMyAdmin/

35

Page 36: AA notes.doc

Class 11 – 12 Assignment 03 -- continued -

Assignment 03 is Due: Saturday October 17th

Midterm Exam is 25 minutes at end of class on Tuesday Oct 13th + entire class Thursday October 15th

Retrieval with SQL (approximate) pattern matches (Optional enhancement)Manually try approximate query such as SELECT * FROM `Diary` WHERE B like '%2009-10%'where the attribute B in the table Diary is assumed to be of type timestampand so therefore looks like 2009-10-05 15:32:42The SQL like operator in the where condition is a standard SQL operator that matches certain patterns.In this case the pattern uses the notation % which matches any string of characters.Combined with the partial date string (2009-10), this pattern retrieves Diary items (for October 2009)that is 2009-10.This capability allows adding date-based retrieval of the diary entries where a user can identify the year and month on the Form (like in 2009-10) based on which the PHP code can then construct a date-based select statement.You can try this as an optional extra-credit enhancement to Assignment 03.The year and month should be selected via two menu which send appropriate values to PHP.

HTML menu element (Optional enhancement )HTML select element, where element name goes, where values go Refer to menu.html under Assignment 03 directory.

Generate HTML menus dynamically using PHP and databaseRefer to the dynamic menu examples under Assignment03Fall09 > MENU directory. The HTML Form there has to be adjusted to use either phpmenu0 or 1 as the action script. Both PHP programs make menus. The program phpmenu0 makes a menu with values 1, 2, 3, etc.The program phpmenu1 makes a menu in a Form which lets the user call another PHP program phpPicture that then displays an image based on the menu selection.

Database retrieval and HTML wrapperRefer to capture.php (and .txt) under Assignment 03 directory for retrieval example.

Re-traversing an SQL results table (capture.php, .txt)Re-execute the SQL queryAccessing only the first of the retrieved values.

Comments on Midterm exam and posted Sample exam.

HTTP headers for POST messages (Optional enhancement)LiveHTTPHeaders: Firefox add-on – set options for requestPOST header and data -- GET versus POST.Refer to capture.html under Assignment 03 directory.

36

Page 37: AA notes.doc

Manufacturing HTML Code -- Code for PHP menu programs:

phpmenu0.php: (database connect must be used first)

$s = "select * from presidents" ;$d = mysql_query ( $s ) or die ( print mysql_error( ) ) ;

$k=0;print "<select name='A' >" ;while ( $r = mysql_fetch_array ( $d ) ){ $k++; print "<option value=$k >";

print $r[ 'name'] ;print "</option>";

} ;print "</select>" ;

phpmenu1.php:

$s = "select * from presidents" ; //define query$d = mysql_query ( $s ) or die ( print mysql_error( ) ) ; //run query and save results in $d

print "<form action='phpPicture.php'>"; //make Form tag

print "<select name='A' >" ; //make menu tagwhile ( $r = mysql_fetch_array ( $d ) ) //grab next row of results{ print "<option value=" . $r[ 'name'] . ".jpg >" ; //menu option & image filename

print $r[ 'name'] ; //option contentsprint "</option>"; //close option tag

} ;print "</select>" ; //close menu tag

print "<input type=submit value='Show the Picture' >"; //make submit button

print "</form>" ; //close Form

phpPicture.php:

$A=$_GET["A"]; //get menu valueprint "<img src='image/$A' height=200 width=200 >"; //make image tag

37

Page 38: AA notes.doc

Class 13 Brief Intro to Javascript - events, functions, accessing input fields, dynamic HTML and properties.

Note: we will return to PHP, etc later.

Purpose

PHP represents a server-side language for processing requests sent by a browser and acts as an intermediary between a browser user and a background database. Javascript on the other hand is a client-side language, that is, it is interpreted (executed or run) by the browser and can dynamically interact with the browser's HTML. Unscheduled, asynchronous but common events on the browser (like mouse clicks on HTML elements or mouse movements) can be used to trigger Javascript responses which are usually implemented by Javascript functions. These Javascript responses to events can access information entered on the page, and actively modify a page's HTML elements and their contents. The examples considered here introduce the basic concepts and syntactical tools of Javascript.

Topics functions, definitions & activationwhere Javascript goes – script tagsJavascript (JS) events to trigger functions – onclick, onload, onkeyup, onblur, onmouseover, etcalert function – used here to test operation of the script setup & pop-up messages to userdocument.getElementById ( id ) -- key JS method or functionid attribute – works in tandem with getElementById methoddotted hierarchical notation for accessing HTML element properties.value notation (for input field contents) error diagnostic tools in Firefox (Error Console) and Internet Explorer style rules such as for body, style properties – background, color, fontSize .style attribute used in Javascriptlive changes to styles using JavascriptJavascript Strings, concatenation operator in JS: +Retrieving and storing results in elements

RGB Color ExampleMake a simple HTML page and Javascript that allows you to input the hexadecimal colorcomponents for a color in 3 separate input fields. A click on a button should then use these inputs to change the background color of the HTML body.

Background for problem:Describe RGB color modelHexadecimal notation for colors: 00….FF for each color componentPixel color components: Red, Green, BlueColor intensities, additive color modelWhite as FFFFFF (full intensity), black as 000000 (signals off so dark)Compare Word color selector tool and RGB decimal notation

Development

1. function notation, definition, placement of code, HTML Form, button event, built-in alert for test, syntax errors – Firefox tools – IE tools.

2. Input field with id, document.getElementById ( id ).value, retrieve/store based on id.38

Page 39: AA notes.doc

RGB Problem Solution

<html><head><script type="text/Javascript">function f ( ){

x = document.getElementById(1).valuey = document.getElementById(2).valuez = document.getElementById(3).value

RGB = "#" + x + y + z document.getElementById(4).style.background=RGB}</script>

<style type="text/css" >body { background: blue ;} </style> </head><body id=4 ><form>

<input type=text id=1 /> RED <br><input type=text id=2 /> GREEN <br><input type=text id=3 /> BLUE <br><input type=button value="RGB" onclick="f ( )" />

</form></body></html>Development

Remarks during development of Javascript RGB example:

Define function with alert message function f( ) { alert ( "hello" ) }

And place in head. Use IE first.Definition of function – appears as text on page – not desired.Place definition in script element, reload the page – does not appear, but does not execute

<script type="text/Javascript"> -- just Javascript has no effectfunction f ( ) { … }

</script>Now add function call/invocation in script element – then f executes on page load

<script type="text/Javascript">f( ) function f ( ) { … }

</script>Remove call from script element; Add function call in body element using event – onload = "f ( )"Misspell alert – try in Firefox, no action – check Tools>Error Console>error messages

In IE: Tools > Internet Options> Advanced > Enable debug & display messages Retest and note line numbers

Remove onload. Add onclick in button element in Form: <form>

<input type=text ><input type=button onclick="f( )" >

</form> 39

Page 40: AA notes.doc

Acquire data from input field – add id=1 in input field, u = document.getElementById(1).value assignment statement,

Put u in message with concatenation alert("hello " + u) Add style rule in style element in head (later we'll introduce dynamic styles)

<style type="text/css">body { color: yellow ; }

</style>

In-class Student Lab Exercise

Make simple multiplication calculator that takes pair of values A and B and outputs product A*B in field. Use RGB example as reference model. Add id=2, 3 fields for u * v setup and answer. Comment out alert: //alert ("hello " + u) .

--and – In-class Lab on Assignment 02.

Solution to in-class Javascript Calculator Exercise:

<html><head><script type="text/Javascript">

function f(){

x = document.getElementById(1).valuey = document.getElementById(2).valueResult = x * y document.getElementById(3).value = Result

}</script><style type="text/css" >body { background: blue ;} </style></head><body id=4><form><input type=text id=1 />x <BR><input type=text id=2 />y <BR><input type=text id=3 />x*y <BR><input type=button value="Multiply" onclick="f()" /></form></body></html>

40

Page 41: AA notes.doc

Class 14 Introduction to Javascript patterns

Refer to Assignment 03 under Spring 2010 directory -- see examples listed there including ReadMe.txt outline and pattern1.html example (see source)

Class 15 Midterm Exam -- FULL PERIOD

Class 16 Assignment 03 and Javascript patterns -- continued

Pattern Recognition Syntax – patterns are so-called "regular expressions" that detect systematic textual patterns in strings of characters. Their basic notation follows and is common to many programming languages.

11. Begins and ends with forward slashes: / /12. The symbols ^ and $ can be optionally used to force the pattern to match the comparison string from its

beginning ( ^ ) to its last character or end ( $ ). Experiment with the previous example without the anchors at ^ and $.

13. A-Z matches any single letter from A to Z; similarly a-z; 0-9 gives digits. 14. The repetition operator + means one or more matches of the pattern (but not zero) is required: thus [A-Z]

+ matches any non-empty sequence of capital letters.15. The period represents a special character for an operator in JS patterns, so to allow it to be used as a

regular character you need to say \. instead, using the backslash -- same for other special characters. 16. The square brackets are used to identify the pattern being repeated by a +17. Single symbols like an @ can be used directly. A single character matches that single character. This

includes the blank!18. If s is the string being tested for a pattern and p is a variable that contains the pattern being searched for,

then the function call s.search(p) returns -1 if the pattern is not in the string s – otherwise it returns the index of the location in the string where the pattern first occurs (starting from the first position at index=0.

9. A notation like (\.edu|\.org|\.com) matches any one of the alternatives .edu, etc. The vertical slash | is an or. Notice there are no blanks present in the above pattern since a blank is considered a character and otherwise the blanks would be required as part of pattern too.19. The notation {m,n} (and {m}) where m and n are integers or variables that equal integers matches m to

n occurrences of the previous sub-pattern. For example [aeoiu]{1,2} matches one or two vowels.

Exercise: Try to recognize the pattern: first-name Middle-initial last-name like in: John Q. Public (what's the textual pattern? how do you apply the pattern syntax?) Also, how do you handle a sequence of data fields to be validated. Thus, suppose have 2nd input field for Age after this field (where value must be 18-100). How do you also check for this pattern? How do you handle this pair of data validations requirements for successive fields? How do you post informative warnings in the page (like too young or too old? in the case of Age) in a visually effective way. What constitutes a test plan and statement of test results?

Pattern for Height of Person in Feet and Inches – it should handle these correctly:5'8" valid5' 8" valid5' 12" invalid [12' makes another foot]5' valid5 ft. 8 in. valid5 ft. valid5ft. valid

41

Page 42: AA notes.doc

5 in. invalid [too short]

Some references Manual pages 124-130 http://www.javascriptkit.com/javatutors/redev2.shtml http://www.java2s.com/Tutorial/JavaScript/0520__Regular-Expressions/TestingforPatternMatches.htm

42

Page 43: AA notes.doc

43

Page 44: AA notes.doc

Class 15 - 16 Intro Javascript II - Data validation for Forms and simple Patterns

Assignment 04 – Experiment with the Unattended password reset page on NJJIT web site. Make a Form with validation and messages inspired by the Unattended Password reset page. A basic version gives grade of 25/50 (grade C); better versions with more of these features gives 40/50 (for B or B+); enhanced version with features like email test or months with correct days for Honor's enhanced version (50 points). Assignment 03 Due Saturday October 24th – Assignment 04 Due Friday Nov 6th

References Manual pages 125-128 http://www.javascriptkit.com/javatutors/redev2.shtml http://www.java2s.com/Tutorial/JavaScript/0520__Regular-Expressions/TestingforPatternMatches.htm

HTML Form Submission and Input Validation

Make an HTML page with Javascript that tests if an input field is non-empty (use simple getElementById test of the value), numerical (use built-in function), or looks like a word (use a Javascript pattern for a string of letters). Use the onsubmit event for a Form to control whether the request is passed on to a server or blocked if the test fails. Make the JS function return Boolean values to indicate the status of the request.

The Form below blocks the submission if the value returned for f( ) is false. Otherwise the Form tries to transfer to a file (here just a stub) identified in the action. The onsubmit event occurs when submit button is clicked. The Boolean outcome determines if the request is transmitted or not.

<html><head><script type="text/Javascript">

function f ( ){

s = document.getElementById(1).value if ( s=="" ) { alert ("Empty - Please fill in field.") ; return false }

//The example two variations. The first tests if the field is a number. if ( isNaN(s)) { alert ("Field must be numerical. Not submitted.") ; return false }

return true //Else accepts submit if the data is a number and exits.

//The following variation checks for a word (instead of a number). //To try it, comment out the previous two statements.

p = /^[A-Za-z]+$/ if (s.search ( p ) ==-1) { alert ("Field is not a word.") ; return false } alert ("Request submitted.") return true

}</script><body bgcolor="tan"><form action="us.gif" onsubmit = "return f()" >

<input type = text id=1 />Input to Validate <br><input type = submit value="Validate data"/>

</form></body></html>

44

Page 45: AA notes.doc

Pattern Recognition Syntax – patterns are so-called "regular expressions" that detect systematic textual patterns in strings of characters. Their basic notation follows and is common to many programming languages.

20. Begins and ends with forward slashes: / /21. The symbols ^ and $ can be optionally used to force the pattern to match the comparison string from its

beginning ( ^ ) to its last character or end ( $ ). Experiment with the previous example without the anchors at ^ and $.

22. A-Z matches any single letter from A to Z; similarly a-z; 0-9 gives digits. 23. The repetition operator + means one or more matches of the pattern (but not zero) is required: thus [A-Z]

+ matches any non-empty sequence of capital letters.24. The period represents a special character for an operator in JS patterns, so to allow it to be used as a

regular character you need to say \. instead, using the backslash -- same for other special characters. 25. The square brackets are used to identify the pattern being repeated by a +26. Single symbols like an @ can be used directly. A single character matches that single character. This

includes the blank!27. If s is the string being tested for a pattern and p is a variable that contains the pattern being searched for,

then the function call s.search(p) returns -1 if the pattern is not in the string s – otherwise it returns the index of the location in the string where the pattern first occurs (starting from the first position at index=0.

9. A notation like (\.edu|\.org|\.com) matches any one of the alternatives .edu, etc. The vertical slash | is an or. Notice there are no blanks present in the above pattern since a blank is considered a character and otherwise the blanks would be required as part of pattern too.28. The notation {m,n} (and {m}) where m and n are integers or variables that equal integers matches m to

n occurrences of the previous sub-pattern. For example [aeoiu]{1,2} matches one or two vowels.

Exercises: Try to recognize the pattern: first-name Middle-initial last-name like in: John Q. Public (what's the textual pattern; how apply the pattern syntax). Also, how to handle a sequence of data fields to be validated. Thus, suppose have 2nd input field for Age as well (where value must be 18-100). How to recognize this pattern? How to combine this pair of data validations requirements? How do you post warnings in page (like too young or too old?) in visually effective way. What constitutes a test plan and statement of test results?

Class exercise: do prototype assignment 04 – with twp pattern checks, test cases and results stated, proper sequencing of tests so entire suite done at a single submit and all diagnostic messages posted using innerHTML to user

Examples:Area Code (not complete telephone number – should handle 0's better than here)

function f ( ){ s = document.getElementById(1).value p = /^(\([1-9]{3}\)|[1-9]{3})$/ if (s.search(p) ==- 1) { alert ("data is not a valid area code") ; return false } alert ("valid area code: request submitted") return true}

Test results are important to articulate (both positive and negative outcomes):973 valid(973) valid

45

Page 46: AA notes.doc

9734 invalid973) invalidExtend this pattern to a complete 10-digit telephone number like 973 596 3333 or (973)596-3333..

Pattern for Height of Person in Feet and InchesHow about heights of people like recognizing height in feet and inches such as:

5'8" valid5' 8" valid5' 12" invalid5' valid5 ft. 8 in. valid5 ft. valid5ft. valid5 in. invalid

Solution – This uses the alternative operator |, repetition factors: + (one or more repetitions), * (zero or more), {1,3} (1 to 3 repeats), anchors: ^ (beginning) and $ (end), and parentheses ( ) to allow repetition of a sub-pattern enclosed in the parentheses! Note that the single quote ' and the double quote " are not special characters for pattern syntax so they do not require a backslash \ like the period and parentheses do.

p = /^[1-9][ ]*('|ft\.)[ ]*(([1-9]|10|11)[ ]*("|in\.)){0,1}[ ]*$/

Email Validator using Patterns (this is not a complete email validator)Make an HTML page and Javascript that tests whether an input looks like a valid email address. (This is a simplified, incomplete email validator which is not quite correct. Try to understand it.

<html><head><script type="text/Javascript">function f( ){ s = document.getElementById(1).value

//pattern = /^[A-Za-z]+@$///pattern = /^[A-Za-z]+@[A-Za-z\.]+$/pattern = /^[A-Za-z]+@[A-Za-z]+\.(edu|org|com)$/if ( s.search(pattern) == -1 ){ alert ("Not recognized") ; return false }alert ('good')return true//Notice the period is a special character and so needs \ before it

}</script><body bgcolor="tan"><form action="us.gif" onsubmit="return f()">

<input type = text id=1 />Email Address <br><input type = submit value="Email Test" />

</form>Test cases: <br>Beware of blanks which are not included here ! <br><br>[email protected] <br> Recognized as [email protected] <br> Not [email protected] <br> Not recognized (even though valid email address)[email protected] <br> Not recognized but see * below.</body></html>

46

Page 47: AA notes.doc

Explain what the following pattern recognizes?

pattern = /^[A-Za-z]+@([A-Za-z]+\.)+(edu|org|com)$/

This pattern better illustrates is a regular expression. It recognizes expressions like * above.

Exercise - Try to improve the email validator immediately above to allow for better email address recognition, such as other valid characters like digits or underscores _ . The link http://javascript.internet.com/forms/email-address-validation.html has a full email validator.

Thought Question -- Think of a pattern you would like to recognize and try to design a recognizer for it ?

47

Page 48: AA notes.doc

Over the remaining classes, we will cover some basic topics in JavaScript including time and random effects, delayed execution, and recursion. Then we will consider how to upload files using PHP. Finally I will spend two classes on using AJAX to interact via PHP with the MySQL database. We will also allow time to work on in-class and consider issues related to the pending assignment on pattern validation for Forms.

We will begin with some remarks on the global logic for the pattern assignment homework, how to place messages about input errors in the browser from JavaScript, and what a suite of test cases (positive and negative results) would look like.

Class **1 Media (sounds), Date and Time, Delayed function Execution, Recursion, Random effects

Purpose

This introduces the use of sound files in HTML pages. The standard player widgets (controls) as well as JavaScript functions to control the files are considered. We use a rudimentary seconds-based alarm clock example to illustrate some of the concepts. The implementation uses the fundamental programming technique of recursion to obtain a new Date (including time) object once each second. The JavaScript setTimeout function lets us do this by making a delayed invocation of a function (after a second delay). Notably, setTimeout does not stop execution of the JavaScript during the delay; it just starts the requested function after a delay; but it continues executing any code that follows the timeout statement. The media (here sound files) issues are affected by the browser used since there are significant variations among browsers in how they handle media. For example there are differences between the JavaScript functions used in IE and Firefox, but we will not explore this here. See manual.

---------------------------------------------------------------------These examples are under Sound Examples directory for Fall 09

Playing Sound Files - JavaScript methods & embed tag/attributes

Understand the embed tag: source of sound; vanishing the player icon using width & height equal to 0 (try tag with and without dimensions); autostart effects whether file plays on load of page (true) or not (false); loop effects whether the sound is repeated or not once started; id required to refer to the embed element file in JavaScript; onclick events in button tags trigger the functions that control the sound file. Play ( ) and Stop ( ) are JavaScript methods to control the embed file.

<html><head><script type="text/JavaScript">

function playSound (p) { document.getElementById(p).Play( ) }function stopSound (p) { document.getElementById(p).Stop( ) }

</script>

</head><body><embed src="flourish.mid" autostart=true loop = true width=0 height=0 id=1 ><form>

<input type="button" value="Play Sound" onclick="playSound (1)" /><input type="button" value="Stop Sound" onclick="stopSound (1)" />

</form></body></html>

48

Page 49: AA notes.doc

---------------------------------------------------------------------

Seconds Clock (gives current second) with Alarm

This illustrates how to use Dates, times, delays, and recursion in JavaScript.

In the example, a function f ( ) is executed as soon as the page is loaded into the browser using an onload event in the body tag. Because it calls itself recursively, the function f never stops executing as long as the page is loaded. f uses Date ( ) to construct a JavaScript Date object that contains the date and time of day and stores the object in y. The Date object allows us to use many other functions like getMilliseconds, getSeconds, etc. The getSeconds function is used in an assignment statement to return the value of the seconds for the current clock and store it in the 1st input element (id=1). A style rule and class attribute make the input text field’s font red. The function f then gets an “alarm time” from an input field and saves it in y. If x and y match, the sound file is started and the alarm time cleared. A function playSound (3) is called by f to start the alarm sound; when the listener clicks the “Stop” button the function stopSound (30) stops the sound file. An embed tag makes the browser load a file with the alarm clock sound. This is a simple midi file which is recognized by the browser. An onclick event for the Stop button element stops the sound file (assuming it was triggered because the clock time matched the alarm time). With the setTimeout function the function f is re-called from within itself (recursively) – but each such call is delayed for 1000 milliseconds (or one second); as a result the time (in seconds) is updated every second. Without the setTimeout function call f would just execute once and return (stop).

<html><head><style type = "text/css"> . A { font-size: 128pt ; color: red ; } </style>

<script>function f ( ) // executed recursively every second.{ v = new Date ( ) x = v.getSeconds ( ) document.getElementById (1).value = x //store current seconds in text field 1 y = document.getElementById (2).value //get alarm time in seconds text field 2 if ( x==y && x!=0 ) //test if it's time for an alarm { //alert ("wake up !"); document.getElementById (2).value="" //clear alarm

playSound (3) //start embedded sound object } setTimeout ("f( )" , 1000) //delayed recursion}

function playSound (p) { var x = document.getElementById(p) ; x.Play ( ) }function stopSound (p) { var x = document.getElementById(p) ; x.Stop ( ) }

</script></head>49

Page 50: AA notes.doc

<body onload="f ( )" ><embed src="flourish.mid" autostart=false width=0 height=0 id=3 >

<input type = "text" id=1 class="A" /> Time in seconds <br><input type = "text" id=2 class="A" /> Enter alarm time in seconds <br><input type="button" value="Stop" onclick="stopSound ( 3 )" /></body></html>

Notes regarding above1. Try invoking and displaying the Date object without recursion – display v in alert.2. Get / store the Date seconds in text field – then compare system clock (analog view for seconds)3. Introduce recursive call to iterate update of Date results.4. The onload event triggers the initial f function call (just once).5. The embed element for media uses id, autostart, and various techniques for hiding player icon.6. Note how to identify the alarm condition.7. Make a stop button to stop the clock. Read the setTimeout/clearTimeout discussion below under

item 2. Just make a Stop Clock button that calls a function that stops the clock. The setTimeout statement in f should be changed as shown there. The new function (say g triggered by the button) should just invoke clearTimeout.

---------------------------------------------------------------------

To experiment with these ideas: Try making a time-based game like whack-a-mole as illustrated in Sound Examples directory. The game randomly plants an image of a mole in a cell of a table (initially all cells contain a blank image). Concurrently a user tries to click the mole image to stop the mole. But the user is only allowed a number of milliseconds before the mole image is moved from its current cell (which is cleared) to another randomly chosen cell (where the mole is redisplayed) so the mole may have already disappeared from the cell you click. The game stops when the user clicks the mole in time, that is, before it hops to another cell.

The problem requires an HTML table of cells, a pair of image files to fill the cells (blank images and a mole image). A field on the page should contain the current delay (say t milliseconds) for how long the mole stays in a cell. This delay can be acquired by any JavaScript function that needs to know the delay. To simulate the jumping mole, a function f should call itself every t milliseconds, clear the cell with the current mole image, and plant the mole image in another random cell (see innerHTML below for how to change the image in a cell and the random number formula for generating random cell id’s). A function g should let a player try to stop the mole by clicking its image / cell before it hops somewhere else. g must check if the identifier for the cell clicked by the user matches the current identifier for the cell with the mole. If the identifiers match, g should stop the next scheduled mole hop (see clearTimeout below for how to do this), start a sound file, and replace the mole image with another image not yet used to indicate the end of the mole.

The HTML infrastructure needs a table (say 4x4) with cell id's and click events for each of the cells. The cells can have id’s from 1-16 and initially have blank images. An onload event should start the mole-hopping function f the first time. f should place a mole randomly in the table and then schedule a delayed repeat of f using recursion. The delay (in milliseconds) can be acquired by f from a field on the page. Since f is called repeatedly it acquires the delay repeatedly (so the delay can be changed as the game goes on). If the delay is named t then f should call itself recursively every t milliseconds after the page is first loaded. Each cell should provide an onclick event to call the checking function g ( id ) (based on the id of the cell clicked). Concurrently with f’s ongoing iteration, whenever a cell is clicked, g checks if the id of the clicked cell matches the id for the cell with the mole. A Stop button can stop the sound played when g detects a mole hit.

50

Page 51: AA notes.doc

Try to implement the problem before looking at the solution. A solution is given under the Sound Examples directory. See whack-a-mole-prototype.html for basic template for a solution. Also whack00.html, needed sound and image files and whack01.html for full solution.

Relevant Syntax and Other Remarks

1. Random number generators: Math.floor ( 16*Math.random ( ) ) generates random integers from 0-15. Add 1 to get random numbers from 1 to 16.

2. The timer below created by the setTimeout function returns an identifier which can be used to block the timer before it goes off. The statement:

e = setTimeout ( "function call" , milliseconds )

stores this identifier in variable e. If the indicated milliseconds delay passes, this timer will trigger the requested function call. However, it is possible to prevent this. The scheduled timer event can be removed by:

clearTimeout ( e )

This deletes the timer event e, preventing the scheduled call to f, effectively stopping the game.

3. Use the innerHTML attribute to replace images or any other content of cells. Thus

document.getElementById(k).innerHTML = "<img src='blank.gif' />"

replaces a cell’s contents with the image tag on the right hand side.

4. Other in-class work -- Pattern Validation Assignment 04.

References: See manual pages for handling sound media. Pages 157-158 for clock example with recursion, delays, dates.

Note: web.njit.edu restricts types of sound files. mp3 files not allowed there. harp.njit.edu insteadAFS is used in any case for the files and web pages.

51

Page 52: AA notes.doc

Class **2 Uploading Files in PHP

References: Manual pages 194 – 205http://www.meandeviation.com/tutorials/learnphp/php-syntax-check/http://us2.php.net/manual/en/

Terms: authorizing http write privileges, enctype encoding type, multi-part/form-data, input type: file, method: post, PHP built-in functions: move_uploaded_file ( string $filename , string $destination ), file_exists ( string $filename ), temporary location of upload, $_FILES built-in associative array of upload properties, global variable, $_FILES ["A"] ["name"], $_FILES ["A"] ["size"], $_FILES ["A"] ["type"], $_FILES ["A"] ["tmp_name"], $_FILES ["A"] ["error], MIME type/subtype pair, "image/pjpeg", "image/gif", "text/html”, "application/msword", or-die hurdles or gauntlet.

HTTP write privileges – In order to upload file and store it on your site, you must authorize this by running the following Unix command in an AFS terminal window. This assumes your target directory to upload to is under testUp in your public_html folder:

/usr/afsws/bin/fs sa ~/public_html/testUp http write

The write privilege automatically applies to subdirectories of testUp.

HTML Form for Upload

<form action ="up00.php" method="post" enctype="multipart/form-data" ><input type = "file" name="A" /><input type = "submit" name="submit" />

</form>

Primitive PHP upload program (make sure to include password protection so others don’t upload to your directories !!! ). This uploads to same current directory where PHP program is (testUp):

<?phpmove_uploaded_file ( $_FILES["A"]["tmp_name"] , "test.txt" ) ;

? >

This only makes sense if the file is a text file. Otherwise use following to name uploaded file appropriately: move_uploaded_file ( $_FILES["A"]["tmp_name"] , $_FILES["A"][ "name" ] ) ;

For security it is important to restrict the upload service by requiring a password from the Form. For example, if the Form has a text field “B”, then:

( $_POST["B"] == "abracadabra" ) or die ( "Invalid password." ) ;

To move file (say) to a subdirectory sub under testUp use: move_uploaded_file ( $_FILES["A"]["tmp_name"] , "sub/" . $_FILES["A"][ "name" ] ) ;where the period is the PHP concatenation operator.

52

Page 53: AA notes.doc

$_FILES is a built-in associative array (like the array $_GET["B"]) that contains information about the upload request:

$_FILES["A"][ "name" ] file name$_FILES["A"][ "tmp_name" ] where stored temporarily on server$_FILES["A"][ "size" ] number of bytes$_FILES["A"][ "type" ] MIME types like: text/html, image/gif, image/pjpeg$_FILES["A"][ "error " ] 0 if successful

To filter or restrict upload request use or-die hurdles or a gauntlet like (it is especially important to always include a good password !!! ).

( $_POST["B"] == "abracadabra" ) or die ( "Invalid password." ) ; ( $_FILES["A"]["size"] < 30000 ) or die ( "File too big." ) ;( ( $_FILES["A"]["type"] == "image/pjpeg" ) || ( $_FILES["A"]["type"] == "image/gif" ) )

or die ( "Invalid type." ) ;( ! file_exists ( $_FILES["A"]["name"] ) or die ( "Overwrite not allowed" ) ;

The last filter checks if the uploaded file already exists (or here since we use the negation operator ! – if the file does not exists).

In class exercises: Experiment with the simple upload examples under Upload Examples directory. Make sure to authorize the Unix write privileges first. up00.php uploads the file to current (target) directory, up01.php checks for a password before doing upload and echoes the password, filename and temporary file location (up02.php is similar but uses password field on form for password), up03.php checks file size and allows only < 80000 bytes and type gif or pjpeg.

53

Page 54: AA notes.doc

Class 24 Alarm Clock Lighter Assignment -- uses sounds, simple recursion, Date object, time delays

Purpose We describe a rudimentary seconds-based alarm clock example to illustrate the concepts. The implementation uses a fundamental programming technique of recursion to obtain a new Date (including time) object once each second. The JavaScript setTimeout function lets us do this by making a delayed invocation of a function (after a second delay). setTimeout does not stop execution of the JavaScript during the delay; it just starts the requested function after a time delay; in the meantime it continues executing any code that follows the timeout statement. The sound file issues are affected by the browser used since there are significant variations among browsers in how they handle media. For example there are differences between the JavaScript functions used in IE and Firefox, but we will not explore this here. See the manual.

---------------------------------------------------------------------These examples are under Assignment 05 directory for Fall 09

Sound Files - JavaScript methods & embed tag/attributes

Understand the embed tag: source of sound; vanishing the player icon using width & height equal to 0 (try tag with and without dimensions); autostart effects whether file plays on load of page (true) or not (false); loop effects whether the sound is repeated or not once started; id required to refer to the embed element file in JavaScript; onclick events in button tags trigger the functions that control the sound file. Play ( ) and Stop ( ) are JavaScript methods to control the embed file.

<script type="text/JavaScript">

function playSound (p) { document.getElementById(p).Play( ) }function stopSound (p) { document.getElementById(p).Stop( ) }

</script>

</head><body><embed src="flourish.mid" autostart=true loop = true width=0 height=0 id=1 ><form>

<input type="button" value="Play Sound" onclick="playSound (1)" /><input type="button" value="Stop Sound" onclick="stopSound (1)" />

</form></body></html>

---------------------------------------------------------------------

Seconds Clock (gives current second) with Alarm -- This illustrates how to use Dates, times, delays, and recursion in JavaScript. In the example, a function f ( ) is executed as soon as the page is loaded into the browser using an onload event in the body tag. Because it calls itself recursively, the function f never stops executing as long as the page is loaded. f uses Date ( ) to construct a JavaScript Date object that contains the date and time of day and stores the object in y. The Date object allows us to use many other functions like getMilliseconds, getSeconds, etc. The getSeconds function is used in an assignment statement to return the value of the seconds for the current clock and store it in the 1 st input element (id=1). A style rule and class attribute make the input text field’s font red. The function f then gets an “alarm time” from an input field and saves it in y. If x and y match, the sound file is started and the alarm time cleared. A function playSound (3) is called by f to start the alarm sound; when the listener clicks the “Stop” button the function stopSound (30) stops the sound file. An embed tag makes the browser load a file with the alarm clock sound. This is a simple midi file which is recognized by the browser. An onclick event for the Stop button element stops the sound file

54

Page 55: AA notes.doc

(assuming it was triggered because the clock time matched the alarm time). With the setTimeout function the function f is re-called from within itself (recursively) – but each such call is delayed for 1000 milliseconds (or one second); as a result the time (in seconds) is updated every second. Without the setTimeout function call f would just execute once and return (stop).

<html><head><style type = "text/css"> . A { font-size: 128pt ; color: red ; } </style>

<script>function f ( ) // executed recursively every second.{ v = new Date ( ) x = v.getSeconds ( ) document.getElementById (1).value = x //store current seconds in text field 1 y = document.getElementById (2).value //get alarm time in seconds text field 2 if ( x==y && x!=0 ) //test if it's time for an alarm { //alert ("wake up !"); document.getElementById (2).value="" //clear alarm

playSound (3) //start embedded sound object } setTimeout ("f( )" , 1000) //delayed recursion}

function playSound (p) { var x = document.getElementById(p) ; x.Play ( ) }function stopSound (p) { var x = document.getElementById(p) ; x.Stop ( ) }

</script></head><body onload="f ( )" ><embed src="flourish.mid" autostart=false width=0 height=0 id=3 >

<input type = "text" id=1 class="A" /> Time in seconds <br><input type = "text" id=2 class="A" /> Enter alarm time in seconds <br><input type="button" value="Stop" onclick="stopSound ( 3 )" /></body></html>

Notes regarding above1. Try invoking and displaying the Date object without recursion – display v in alert.2. Get / store the Date seconds in text field – then compare system clock (analog view for seconds)3. Introduce recursive call to iterate update of Date results.4. The onload event triggers the initial f function call (just once).5. The embed element for media uses id, autostart, and various techniques for hiding player icon.6. Note how to identify the alarm condition.7. Make a stop button to stop the clock. Read the setTimeout/clearTimeout discussion below under

item 2. Just make a Stop Clock button that calls a function that stops the clock. The setTimeout statement in f should be changed as shown there. The new function (say g triggered by the button) should just invoke clearTimeout.

55

Page 56: AA notes.doc

References: See manual pages for handling sound media. Pages 157-158 for clock example with recursion, delays, dates.

Note: web.njit.edu restricts types of sound files. mp3 files not allowed there. harp.njit.edu insteadAFS is used in any case for the files and web pages.

56

Page 57: AA notes.doc

Class **3 AJAX

Key points

16. Boilerplate use of createRequestObject function to make http object.17. sndReq function to send http request to web server.18. sndReq works in background asynchronously (the A in AJAX).19. handleResponse (or responder) function handles the server response.20. handleResponse only acts when the onreadystatechange flag is 4 (meaning program done).21. onreadystatechange in sndReq identifies the handler function for the request.22. response is generated by PHP output print statements whose results are concatenated in

http.responseText.23. The response can be processed in Javascript function or deposited in the HTML page using for

example: document.getElementById(200).innerHTML = response which replaces the current contents of element 200 (in this case).

24. sndReq makes the request using the http.open function.25. open indicates the HTTP method used (in this case get) and gives the “query string” that identifies

the server-side program that handles the request and its data.26. The fragment 'ajax00.php?u=' here indicates the program and that its input variable u (which is the

name PHP program will $_GET) and includes/concatenates the value of u.27. The data value of u is stored in v by sndReq statement: v = document.getElementById(100).value28. Replacing the onclick event for the button with an onkeyup event for the input field gives another

view on the interface that is more natural to the interactive application we have in mind.29. The PHP program can be extended to use the AJAX supplied data to access a database like in

Google Home page.30. The string + "&sid="+Math.random( ) in the open function seems obscure. You could omit it but

what it does is ensure that new requests with the same data as a previous request don’t just get responded to by the browser with a cached stale copy of the results (which may be out of date if the PHP program’s code has changed). This string includes an artificial variable named sid with a random (and so different value each time) in the query string. This way the request is different and a cached copy will not be used. The & before the sid variable is the usual symbol used to separate variable=value pairs in an http GET request.

Examples are under AJAX Examples under Fall 09 directory. Exercise: Try to extend it to pick up words that begin with what you have written so far from a small dictionary file in your database (sample posted as listword.txt). Need SQL like operator in select statement.

ajax00.html<html><head><title> </title><script type="text/Javascript">function createRequestObject(){ var ro; var browser = navigator.appName; if(browser == "Microsoft Internet Explorer") { ro = new ActiveXObject("Microsoft.XMLHTTP"); } else { ro = new XMLHttpRequest(); } return ro;}

57

Page 58: AA notes.doc

var http = createRequestObject();

function sndReq( ){ v = document.getElementById(100).value http.open('get' , 'ajax00.php?u=' + v + "&sid="+Math.random() ); //warning: don't put extra blanks in open strings such as NOT: php ? u = but php?u= http.onreadystatechange = responder; http.send(null);}

function responder( ){ if( http.readyState == 4 ) { var response = http.responseText; document.getElementById(200).innerHTML = response }}</script><style type="text/css"> div { border: 2px solid black ; background-color: red ; }</style>

</head><body ><input type = text value="I stay the same." />Persistence<br><input type = text id=100 />Input <br><input type = button onclick = "sndReq( )" /><div id=200 class="A">Here I am.</div>

</body></html>

ajax00.php<?php$w = $_GET["u"] ;print "<br>u is $w <br<br>" ; print "<br><br>" ;for ( $k = 0; $k < 10; $k++ ) { print "index k is: $k and u is $u <br>" ; }?>

58

Page 59: AA notes.doc

Class **4 AJAX Google-like Example

Topic: This illustrates AJAX interaction with a background database, how to wrap database results in complex HTML elements, and submitting forms from JavaScript rather than via a submit button. This example produces effects similar to the Google home page where a string (as it is typed) generates at each keystroke a drop-down list of words retrieved from a database which begin with that string. When the cursor moves over the drop down list the background colors change back and forth from white to light red. The list items are click-sensitive and trigger a form submission to the Google search engine based on the word selected by the click. The form invokes the Google search engine and sends the search data (from text field) in q.

Files to check:

Static HTML version of div elements (later dynamically constructed via PHP)http://www.cs.njit.edu/mchugh/psswrd/web-course-materials/IT202/Fall2003/A-assignments/Sp06/AA%20Fall%2009/AJAX%20Examples/div02.html

HTML with AJAX and JavaScript:http://www.cs.njit.edu/mchugh/psswrd/web-course-materials/IT202/Fall2003/A-assignments/Sp06/AA%20Fall%2009/AJAX%20Examples/Gooogle Example/mysearchNew1.html

PHP text of code for example:http://www.cs.njit.edu/mchugh/psswrd/web-course-materials/IT202/Fall2003/A-assignments/Sp06/AA%20Fall%2009/AJAX%20Examples/Gooogle Example/mysearchNew1.txt

PHP code for example:http://www.cs.njit.edu/mchugh/psswrd/web-course-materials/IT202/Fall2003/A-assignments/Sp06/AA%20Fall%2009/AJAX%20Examples/Gooogle Example/mysearchNew1.php

PowerPoint animated diagram of application flow:http://www.cs.njit.edu/mchugh/psswrd/web-course-materials/IT202/Fall2003/A-assignments/Sp06/AA%20Fall%2009/AJAX%20Examples/Gooogle Example/diagram.ppt

Some relevant HTML and JavaScript code:

function ON(p) { document.getElementById(p).style.background='#ff8080' }function OUT(p) { document.getElementById(p).style.background='#ffffff' }function MOVE(p) { document.getElementById(100).value

= document.getElementById(p).innerHTML }<style type="text/css"> body { background: cyan ; } div { border: 2px solid black ; width: 400px; height: 30px ; background-color: white ; }</style>

Static version of div elements:<div id=1 onmouseover = 'ON(1)' onmouseout = 'OUT(1)' onclick = 'MOVE(1)'>

<b>wikipedia </b> </div><div id=2 onmouseover = 'ON(2)' onmouseout = 'OUT(2)' onclick = 'MOVE(2)'>

<b>google </b> </div>59

Page 60: AA notes.doc

Class **5 Session id’s in PHP

Refer to the examples under SessionsPHP under Fall09 directory on web site.

The examples 10, 11, 12 use the session id and get correct coherent web conversation behavior that differentiates different session by different browsers correctly. Test the behavior by using two different browsers. Each will create a separate conversation. If you run my Form/code, the conversation you create will be separate from the conversations I create – because they will have different session id’s and the transactions that the PHP stores in the database will reflect that.

The examples 20, 21, 22 do not use the session id and so do not create a coherent conversation. Note there would be no session id in the request or response headers for these examples.

The sessionHeadersPHP.doc follow some of the HTTP headers for examples 10, 11, and 12.

60