Your SlideShare is downloading. ×
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
AA notes.doc
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

AA notes.doc

4,647

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
4,647
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
13
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Topics covered in course HTML STYLE SHEETS JAVASCRIPT PHP MYSQL SQL HTTP AJAX WEB SERVERS Requires AFS ACCOUNT NJIT Secure Shell SSH for AFS file access MySQL Account at NJIT - provided through course Note: These notes are updates before and after each class. The notes after the current class are leftover notes from last semester. I leave them here for curiosity but the course topics will be done in a different order and the nature of the examples and assignments will change, so only the notes up to the current class reflect this semester. It is your responsibility to: • Keep a blank index.html page in the directory on you web site that contains your work to prevent others from readily accessing your code. • Do not provide links on any publicly accessible page to any of your homework assignments, to help prevent linked access to your assignments. 1
  • 2. Class 01 Intro -- Tuesday Jan 20th Office Hrs – Tues / Thurs 1:00-2:30, W 10-11 Where's info ? Course Text - $5.00 See AA Spring 09 > BookIndex.pdf for corrected index. Web site: http://www.cs.njit.edu/mchugh/notesIT202.html AA notes at: Problems - Solutions > Class Notes > AA Spring 09 > AA notes.doc Problems-Solutions > What we will Learn 1. Overview Course Information > Syllabus, Handout, Overview Grading, exams, text – see: Course Information > Overview 2. Web site Review web site links Problems - Solutions > Class Notes > A Spring 09, assignments, AA notes.doc, etc The notes are revised before and after each class ! HTML + JS sites > w3Schools, etc. Contain useful source material. 3. JS Demos For Javascript Demos see: Introductory Survey > Survey Demos Sample student work - mainly on Javascript (Introductory Survey > Survey demos from 1st half of semester) Matt-Vance-SuperBlinker, quizzer08a.html, build01.html, MattQuiz-BrendaDavis, Checkers Pank (locally), OthelloPhilipKroge (locally), MasterMind: These examples are representative of HTML/Javascript aspects of course – BUT do not illustrate the PHP server-based and MySQL database assignments. 4. Database Open MySQL and create/insert/browse simple 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 point spread see Overview (under Course Information on web site ) – I will flexibly recognize peak performances and exceptional knowledge/passion. Mechanically - A is 90% of total points assigned, etc for other grades – but 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% 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. • I recommend experienced students register in Honor's sections • 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 spiral bound notes -- Chapter 1, some of Chapter 7, 8 over next few weeks. Time permitting, discuss - 3-Tier architecture: Browser(HTML, JS), Web Server(Apache, Tomcat, PHP), Database(SQL, MySQL, MS Access), Internet (http, TCP/IP), TextPad. 2
  • 3. Notes on Home Page Setup These are comments in case you do not already have a home page set up. The setup should be on the NJIT web site so you can access MySQL. Transfer students: If you are a transfer student and do not yet have an AFS account, go to bursar office at student mall and they will tell you where to go to get the account. AFS Account: The http://ist.njit.edu/webhosting/public_html.php link shows how to set up an AFS account,. Then you can set up a public web site with a public_html folder if not yet done. This requires a UCID and password. You can also refer to: http://web.njit.edu/all_topics/AFS/windows.client/ and http://web.njit.edu/all_topics/User_Homepage/Setup/ To upload files to your web site, log on to your AFS account and place the files to be accessed over the web under your public_html folder (or in a directory under that folder). Secure Shell SSH You can access AFS with SSH (Secure Shell) available on NJIT software site (Google: NJIT software). Changing System Passwords To change your system passwords use: https://mypassword.njit.edu/cgi-bin/upr/usecr.php Changing database Passwords https://mypassword.njit.edu/cgi-bin/upr/dbpasschange.php. 3
  • 4. Class 02 - Class 03 Intro -- Thursday January 22nd Tuesday January 27th Exercise for Friday January 30th Noon. 1. Access your MySQL database with the account name and password sent to you by the system administrator before the semester started. http://web.njit.edu/mysql/phpMyAdmin/. Remember student accounts use sql2.njit.edu. Make a table with a few columns and enter some rows of data. Execute an SQL Select query like Select * from People where Age > 10 (the details depend on the table and column names you use). Snapshot the screen for the SQL results. Then make and validate an HTML page, that contains: a link to the image of the MySQL page with the results of the SQL Select query, and a link to an image of your HTML validation page results. 2. The HTML page and snapshot image 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. However, email a link to the solution to me when finished. Concepts: standards validation, HTML page structure, DOCTYPE, character declaration, strict versus transitional standards, color-coded syntax editors, MySQL database, tables, data definition, screens to create table, select data types, insert rows, delete rows, drop tables, browse contents, table structure, SQL select statement Work thru exercise in class: 1. Demo assignment solution. 2. Logon to MySQL (open source database) 3. Create table (make up one) with data types 4. Populate table manually (SQL inserts). 5. Browse table 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 bit map or GIF, size. Compare & Display in browser 9. Simple HTML page with img tag and hyperlink. Drag-and-drop display of HTML page. 10. Validate HTML page – http://validator.w3.org/ -- correct errors. – DOCTYPE, meta charset, title, / > tags, alt. Compare introducing attribute bgcolor="cyan" in body element. Do with strict DOCTYPE (and also use the options in validator to test transitional instead). 11. Upload files(s) to web site and retrieve using http request. SSH, public_html, subfolders, Unix capitalization sensitivity vs. Windows. Validation (10) 4
  • 5. For character encoding tag see http://www.w3.org/International/O-charset and <meta http-equiv="Content-Type" content="text/html; charset=utf-8" > For DOCTYPE see http://www.w3.org/QA/2002/04/valid-dtd-list.html and <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> For list of deprecated attributes see http://www.codehelp.co.uk/html/deprecated.html. Internet Application Book References Chapter 1 – pages 7-10 Chapter 1 > Images - pages 17-30 Chapter 2 – Validation of HTML pages 75, also pages 70-73 Chapter 7 – SQL and MySQL > pages 196-208 PLEASE NOTE Many of the example in Book are posted under the Book Directory under AA Spring 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 should explore in tandem with the text. See animated HTML01.ppt under Assgt01 directory Reading responsibilities and quizzes. Chapter 1 > Hyperlinks - pages 14-16 Chapter 5 > especially direct HTTP request – pages 163-167 Homework Enhancement: • image of a MySQL screen with the results of an SQL select statement • an image of the validation results for the page • validated under strict HTML • a style rule for the images with dimensions • a hyperlink to a copy of MySQL image -- in a subdirectory of the directory containing the HTML page 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. 5
  • 6. Class 04 HTTP Exercise HTTP exchanges under the browser hood: Use telnet and direct HTTP request to GET (retrieve) file from web site. – see HTTP01.ppt under web site -- spring 09 Try such as: mchugh/test/b.html on web site: • Use terminal window acquired from SSH (-- or -- command prompt cmd executed from run). (If use command prompt, then after telnet connection to remote computer is issued, you need to type: <ctrl> ] , followed by set localecho, followed by <CR> to ensure typed characters are visible (echoed).) You cannot backspace in the resulting TCP environment (because backspace character becomes part of HTTP message sent, thus messing up the message content). • telnet web.njit.edu 80 (port 80 identifies program that services the request – here web server) • GET /~mchugh/test/b.html HTTP/1.0 -followed by <CR><CR> • You may have to copy/paste the GET request to avoid a timeout of the connection • Telnet establishes a two-way TCP connection over which HTTP messages are exchanged with remote computer (like web.njit.edu or google.com) on port 80 (where web servers listen by convention). • In a browser request the URL would be: http://web.njit.edu:80/~mchugh/test/b.html Or try: • telnet google.com 80 • request: GET /index.html HTTP/1.0 to retrieve Google home page. Or use: • numeric IP address for google.com (in dotted quad form as follows): • telnet 74.125.19.103 80 instead of symbolic name (can get IP from http://whois.ws/ or http://ip- lookup.net/ or command nslookup . Images referred to in these HTML pages (like us.gif in same dir as b.html) are not included in HTTP response message. The browser has to parse those responses and go back to the server to request such files on a second pass! You could get the image with: GET /~mchugh/test/us.gif HTTP/1.0 (Do this in command prompt – it caused a communications problem in UNIX prompt). Display response message (copy from command prompt) as HTML Page ! How do you copy from the dos command prompt. And then save as HTML and display. Points covered: • Explicit connection to remote computer via symbolic address • telnet connection • port for program requested • HTTP Get command to request resource (HTTP request) • HTTP response message • HTTP response body • Content-Length • Content-Type • Numeric IP address • Copying content of command prompt 6
  • 7. Some points on terminology URL Like http://www.njit.edu Domain Name Like www.njit.edu 7
  • 8. Class 05 - 06 PHP – Two-Tier & Three-tier Software Architectures Purpose To introduce the notion of a server-side scripting language and illustrate it with PHP scripts and their correlative HTML Forms. Refer to: PHP 01.ppt animated presentation on Sp 09 web site for overview and exercises. Example Simple calculation & PHP HTML wrapper – see PHP 01.ppt PHP Syntax checking www.meandeviation.com/tutorials/learnphp/php-syntax-check/ PHP reference http://us2.php.net/manual/en/ Exercise (password, email) Make PHP program and associated HTML Form that generates a random password (using crypt function) and emails the results (using mail) to user who submitted the Form. Later: Modify Example program so times table is wrapped in HTML table Requires first knowing the HTML table element. For Assignment 03. Exercise (Database insertion) Insert data in a table based on a Form. Given name, password and email address on a Form, insert the data with name, email, and password into a MySQL table named Information. The table can be created beforehand manually. 1st : Do insert Manually after creating Information table. Refer to text pages 226, 213-218, etc. 2nd : Do using PHP to connect to database and execute SQL statement using the Form data. $username = "---" ; $password = "---" ; $hostname = "sql2.njit.edu"; $project = "---" ; mysql_connect ($hostname, $username, $password) or die ("Unable to connect to MySQL"); echo "Connected to MySQL<br> "; mysql_select_db ( $project ) or die ( mysql_error ( ) ) ; $s = "insert into name-of-table values ( value-1 , value 2, value-3 ) " ; print "<br>$s<br>; mysql_query ( "insert into name-of-table values ( 'Howie' , 11, 'IT' )" ); Explain Output Source Explain the curious output from the show_source function. Use High level editor [like FrontPage] and note role of special characters like < and their representation in HTML. Also understand the color effects that result from the way PHP show_source knows the keywords in HTML and PHP. 8
  • 9. Assignment 02 See under Assgt02 directory on web site, as well as in PHP 01.ppt Originally due noon Friday 13th Due date Changed to Wednesday 18th Noon Assignment 03 - Refer to PHP 01.ppt. Also wrap output in suitable HTML table Final specification of the assignment and Due date not decided yet. HTTP Exercise Request m1.php with data M and N using GET command after telnet connection to web.njit.edu Web server on port 80. The root directory is /~your-ucid. Also capture and display response. From terminal window and display as HTML page. 9
  • 10. Class 07 - 08 Continuation Assignment 02, PHP, HTML Topics: text attributes, primary keys, or-expression control structure, mysql_error( ) function, PHP date function, SQL Now ( ) function, MySQL timestamp type, new line control character, HTML high level editors, PHP HTML wrappers. Assignment 02 Requirements – Assgt02.doc as posted 1. Technical note: use single quotes for database text attributes like '$x' as part of an insert. Note what happens if omit – get SQL "column" error. 2. Use Primary key for Information table to prevent duplicate entries for password. Try with Type varchar (with length) or some number type like smallint(6). 3. The PHP or-expression construction is frequently used to handle failure of an action like: ( Run-SQL-query ) or ( React-to-failure ) where we assume each term returns a Boolean value so it can be part of an expression like: mysql_query ( $s ) or ( print mysql_error ( ) ) ; where the statement after the or is only executed if the first expression fails (conditional evaluation). For example, trying to insert a duplicate key in Information causes the first term to fail and so an error message will be displayed for mysql_error, even though the PHP program still continues execution. 4. Time and date • PHP date ( ) function (page 178 of text for example). • You can make the date or time attribute in a database table have type timestamp in MYSQL. Then, if you perform a manual insert, the time value is automatically included (try this). You can also use the SQL NOW function like: $s ="insert into sample-table values ( '$name' , NOW( ) )"; where we assume the table attributes are text and timestamp respectively. 5. Layout of email content • Use n newline character in email text message. ---------------------------- 10
  • 11. Class 08 High Level Editors, Tables, HTML/PHP Wrappers, Assignment 03, Assignment 02 HTML content Layout. Nice layout of echoed content. See Assgt02.doc under dir Assgt02 for suggestions. High level HTML Editor (using MS FrontPage) Start FrontPage, navigate to my current dir before saving. Illustrate design/code views Drop-down prompts for elements and attributes Add img element, use navigation tool to add relatively addressed image file. Make HTML tables - use high-level graphical tools and note low level syntax. Exercise HTML/PHP Wrapper Modify PHP for m1.php under Assgt02 dir. Make HTML wrapper in m1.php output of times table as HTML table. 11
  • 12. Class 09 Database Retrieval, Database Passwords, Encrypted passwords Assignment 03 – Retrieval from Database + Password protection + HTML wrapper for results + Email Due date: Noon Saturday Feb. 28th See Assgt 03.ppt under Assgt 03 directory Next topic – Javascript – then will return to PHP, etc. Simplified version of Assignment 02 For reasonable PARTIAL CREDIT Insert password and textarea content into database table Diary using HTML Form, PHP script, and MySQL. Echo Form data back to browser also. Simplified version of Assignment 03 For reasonable PARTIAL CREDIT Use password to retrieve database table Diary's contents for that password. Echo Form data back to browser in HTML table. Database Retrieval SQL Select statements for retrieval Manual illustration of SQL in database SQL definition in PHP mysql_query & mysql_error to illustrate testing for SQL errors (versus PHP errors!) – Exp: elect - not select for mysql error - SQL ERROR Exp: o - not or - PHP ERROR Exp: mysql_queryy - not mysql_query - UNRECOGNIZED FUNCTION NAME or-construction for above mysql_queryy ($s) or ( print mysql_error( ) ); PHP Database Retrieval - see text pages 218-219 etc results table, row of results table, cell of row: ( $x = mysql_query ($s) ) or ( print mysql_error( ) ); Compare Boolean expression: A or B print "rows: " . mysql_affected_rows ( ) ; PHP concatenation operator -- dot $x = mysql_query ($s), $y = mysql _fetch_array($x), $y["name"], while loop behavior while ( $y = mysql_fetch_array ($x) ) print "A1: " . $y['A1'] . "<br>"; Note: $y['A1'] and $y["A1"] have to be outside the outer quote string Could use: $z = $y["A1"]; to access $y first – so quotes not an issue Relate to Assignment 03 Wrap results in HTML table tags (retrieval from Diary). See PHP 01.ppt – bottom of slide 16 for basic problem Send results also in email to person with that password (using retrieval from Information). Exercises Database retrieval - $s, $x, $y, $y [ "---"] HTML table wrapper for results - intermix print, data, table tags 12
  • 13. Class 10 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 & activation where Javascript goes – script tags Javascript events to trigger functions – onclick, onload alert function – here, to test operation of the script setup & pop up messages to the user document.getElementById ( id ) -- key JS method or function id attribute – works in tandem with getElementById dotted, hierarchical notation for accessing HTML element properties .value (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 Javascript live changes to styles using Javascript Javascript Strings, concatenation operator in JS: + Retrieving and storing results in elements RGB Color Example Make a simple HTML page and Javascript that allows you to input the hexadecimal color Components of a color in 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 model Hexadecimal notation for colors: 00.FF for each color component Pixel color components: Red, Green, Blue Color intensities, additive color model White 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. 13
  • 14. RGB Problem Solution <html><head><script type="text/Javascript"> function f( ) { x = document.getElementById(1).value y = document.getElementById(2).value z = 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 effect function 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> 14
  • 15. 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).value y = document.getElementById(2).value Result = 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> 15
  • 16. Class 11 - 12 Brief Intro to Javascript II - Data validation for Forms in Javascript and simple Patterns References Text pages 115-118 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 and Javascript that tests whether an input is non-empty (with simple getElementById test of the value), numeric (by built-in function), or looks like a word: a string of letters, by using a Javascript pattern. Use the onsubmit event for the Form to control whether request actually submitted. Make the function return Boolean values to signal status of request. The Form structure below blocks the Form submission if the value returned for f is false. Otherwise it tries to transfer to a file (here a stub) identified in action. The onsubmit event of Form occurs when submit button is clicked. Its Boolean outcome determines whether the request is transmitted or not. <html><head> <script type="text/Javascript"> function f( ) { s = document.getElementById(1).value if ( s=="" ) { alert ("empty; fill in field") ; return false } //if ( isNaN(s)) { alert ("field not numeric") ; return false } //if ( !isNaN(s)) { alert ("field is numeric") ; return false } //if (s.search ( /^[A-Za-z]+$/) ==-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 Test"/> </form> </body></html> 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 languages. 1. Begins and ends with slash: / / 2. The symbols ^ and $ can be optionally used to force the patterns to match a string from the beginning ( ^ ) to the end ( $ ). 3. A-Z matches any single letter from A to Z; similarly a-z; 0-9 gives digits. 4. + means one or more matches (but not zero): so [A-Z]+ matches any string of capital letters 5. The period is a special character in JS patterns, so to use it as regular character need to say . 6. The square brackets are used to identify the pattern being repeated by the + 7. Single symbols like an @ can be used directly. 8. If s is string tested and p is where pattern is stored, then s.search(p) returns -1 if the pattern is not in the string s and otherwise the index of the location where the pattern occurs. 9. A notation like (.edu|.org|.com) matches any one of the alternatives. The vertical slash is like an or Notice there are no blanks present (since otherwise the blanks would be required as part of pattern too). 16
  • 17. 10. The notation {m,n} where m and n are integers matches m to n occurrences of the previous sub-pattern. For example [aeoiu]{1,2} matches one or two vowels. Simple examples done in class, such telephone no's like 973 596 3333, or (973)596-3333, or both – see below under next class. 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> mc@njit.edu <br> Recognized as Good mc@cs.njited <br> Not recognized mc@cs2.njit.edu <br> Not recognized (even though valid email address) mc@cs.njit.com <br> Not recognized but see * below. </body></html> Explain what the following pattern recognizes? pattern = /^[A-Za-z]+@([A-Za-z]+.)+(edu|org|com)$/ This pattern better illustrates a so-called 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. 17
  • 18. Class 12 Textual Pattern Recognition Continued, Exam Preview, Assignment 03 Continued • Try other patterns like parenthesized area codes and height in feet & inches. • See Midterm Sp 09 SAMPLE EXAM.doc under we site. • Continue work on Assignment 03 Additional Example - Area Code Validator 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 } //Remember that if s.search(p) fails to find p in s, then it returns -1. alert ("valid area code: request submitted") return true } Test results 973 valid 9734 invalid (973) valid 973) invalid Extend this pattern to a complete 10-digit telephone number. Thought Question Think of a pattern you would like to recognize and try to design a recognizer for it ? Height Pattern How about heights of people like recognizing height in feet and inches such as: 5'8" valid 5' 8" valid 5' 12" invalid 5' valid 5 ft. 8 in. valid 5 ft. valid 5ft. valid 5 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}[ ]*$/ 18
  • 19. Class 13 Exam Preview and Assignment 03 Continued Assignment 03 – Note the relevant documents under Assgt 03 on web site. This is due Saturday 14th noon. 3/14 (remember pi in geometry – 3.14) Asgt03.ppt Notes have been appended to these slides in the notes section of the PPT. For Honor's students version for encrypted passwords They should use the animated presentation in PHP 02.ppt in same directory. This entails storing an encrypted version of the passwords first in a Passwords table (or the Information table), and using the logic described in these slides to confirm whether the unencrypted password submitted by Form encrypts to the same encrypted password. Additional Background To the extent that it helps, remember the notes on Assignment 02 under PHP 01.ppt, slides 17-18 under the same directory Assgt 03. Exam Preview We will go over the sample template exam in class. It is located under AA Spring 09 directory on web site as Midterm Sp 09 SAMPLE EXAM.doc. Class 14-15 Exam 19
  • 20. Class 16 -17 Validation Homework Assignment 04 Honor' Chat Project Tutorial – must make your own/have command of technology Validation Homework Assignment 04 Review the development of the homework assignment in detail. Do extensive Lab assistance with students….most of 2nd class and part of 1st -- walk-around Lab. Carefully understand the structure of the implementation below. Some issues: Handling a zip code pattern: excluding all zeros – clean implementation Handling two-digit age: including 10,20, etc. – patterns with alternatives Zipcode (s.search(p) == -1) || (s == "00000") Notational comparison: … || ( s == "00000") versus ([1-9]{1,2}|[1-9]0) – operators, delimiters Keyboard focus – JS function focus( ) versus HTML/JS event onfocus Related events: onkeydown, onkeyup, onblur, etc DOM notation for highlighting – and un-highlighting DOM notation for changing properties of elements, rgb and hex color notation, Word color tool How the various returns are designed – task function returns, driver returns, onsubmit event Message utility function sendMessage(p, q) Pre element to list test cases: Task name test case Valid/Invalid Develop and discuss reference example <html><head><script type="text/Javascript"> function f() { if ( Name() == false ) return false return true } function Name() { s = document.getElementById(1).value p = /^[A-Za-z]+$/ if ( s.search(p) == -1 ) { alert ("bad name") document.getElementById(1).style.background = "#dddddd" return false } return true } </script></head><body> <form action="us.gif" onsubmit = "return f()" > <input type = text id=1 />Name <br> <input type = submit /> </form> <pre>Test Cases Name Joe Valid Joe3 Invalid </pre> </body></html> 20
  • 21. References Another useful link on basic matching is: http://www.sitepoint.com/article/expressions-javascript/ Chat Application in AJAX, MySQL and PHP - For Honor's students: I recommend that you work on a Javascript AJAX SQL based chat application - the following tutorial discusses and implements one. Modify, adapt it, but you must have a commanding understanding of the implementation (or perhaps your simplified variation of it). http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=9#start Time frame – during rest of term. 21
  • 22. Class 18 Media (sounds), Date and Time, Delayed function Execution, Recursion, Random effects Purpose of Media Topics 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 concepts. The implementation uses a fundamental technique called recursion to obtain a new Date and time every second. The setTimeout function makes a delayed invocation of a function. Be aware that setTimeout does not block code that occurs following the timeout statement. The media issues can be affected by the browser used with significant variations among browsers in how they handle media, such as differences between the Javascript functions used in IE and Firefox, though we do not address this here. --------------------------------------------------------------------- Sample Examples under Assgt 05 directory Playing Sound Files - Javascript methods & embed tag/attributes <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 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> --------------------------------------------------------------------- Simple Clock (current seconds) with Alarm Sound <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 } 22
  • 23. 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: 1. invoke and display Date result without recursion – give v as result in alert 2. get / store clock seconds in text field – compare system clock 3. use recursive call to iterate update of Date results 4. onload event to trigger initial function call 5. embed element for media, id, autostart, hiding display icon 6. identifying alarm condition --------------------------------------------------------------------- Syntax notes The timer created by the setTimeout function also returns an identifier which can be used to eliminate the timer before it goes off. Thus t = setTimeout ( "function call" , milliseconds ) saves the identifier for the timer in t. If the indicated delay passes, this timer goes off with the function call executed. However prior to that happening, the timer itself can be removed using: clearTimeout ( t ) which kills the timer and prevents the scheduled function call. Use innerHTML to replace images in cells In-class Problem: Make a time-based game, like whack-a-mole as illustrated, using above techniques: Design (see whack00.html for skeletal prototype under Assignment 05 – and sound/image files there) HTML Infrastructure Create table with id's and click events Agent-1 (computer move): function f: Move a picture randomly in table. Wait, then repeat. Agent-2 (player): Click a cell. Agent-3 (event-handler): function g(id): If user click catches picture id, stop the timer / replace picture. Or time on Assignment 04 on Data Validation. References: Assgt 05 directory – there is no assignment related to this yet. Manual pages 150-151 for basic HTML for handling sound media. Pages 157-158 for clock example with recursion, delays, dates. Note: AFS restricts types of sound files. mp3 not allowed there. 23
  • 24. Class 19 Uploading Files in PHP References: Manual pages 183 – 194 http://www.meandeviation.com/tutorials/learnphp/php-syntax-check/ http://us2.php.net/manual/en/ HTTP write privileges – run following Unix command in AFS terminal window. /usr/afsws/bin/fs sa ~/public_html/test http write Applies automatically to subdirectories of directory test. HTML Form <form action ="up00.php" method="post" enctype="multipart/form-data" > <input type = "file" name="A" /> <input type = "submit" name="submit" /> </form> Rudimentary PHP upload program (make sure to include password protection !) <?php move_uploaded_file ( $_FILES["A"]["tmp_name"] , "test.txt" ) ; ?> Understand Limits of above – and risks. Or: move_uploaded_file ( $_FILES["A"]["tmp_name"] , $_FILES["A"][ "name" ] ) ; Or: move_uploaded_file ( $_FILES["A"]["tmp_name"] , "upload/" . $_FILES["A"][ "name" ] ) ; Where upload is a subdirectory under test. Built-in associative array (compare $_GET["B"]): $_FILES["A"][ "name" ] $_FILES["A"][ "tmp_name" ] $_FILES["A"][ "size" ] number of bytes $_FILES["A"][ "type" ] MIME types like: text/html, image/gif, image/pjpeg $_FILES["A"][ "error " ] 0 if successful Filtering upload request (especially important to always include a good password !!!) – or-die hurdles ( $_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" ) ; In class Exercise: Implement a simple upload program and Form. Make sure to authorize the Unix write privileges first. Can also work on Assignment 04. 24
  • 25. Classes 20 - 23 – Ajax-based assignment, styles, SQL, MySQL, Javascript, dynamic HTML 1. Assignment objective: simulate AJAX effects on Google home page search field 2. SQL like operator – MS Access 3. Google - piggy-back Form on search engine – Google search variables 4. Menu code populated from database 5. or HTML div elements populated dynamically 6. - div with rollover highlight on/off 7. - div with click and move contents to field 8. AJAX programming model 1. Demo Google home page Ajax effects 2. SQL like operator Select * from table1 where name like 'N*' [in MS Access] In MySQL the notation % is used instead of * Try Like.mdb query Sample database contents 3. Desired building Blocks Instructor demo: div0.html, div1.html, div2.html div elements mouseover / out for highlight / un-highlight functions onclick to move contents (HTML text) to Form field innerHTML (div), value (text field) styles / border / border-top shorthand notation /class / border-top-width / border-bottom-width -------- 4. Importing text file in MySQL, CSV (comma separated values) Some SQL – order by, Limit 10, table is named dict , attribute is name, file word.txt where name like 'dahdah%' Limit 10 5. Ajax examples Refer to Mx.html, .txt, .php under directory 07 Sends <br> separated data back to Ajax function – without otherwise disturbing original page. Refer to M03.html, .txt, .php under directory 07 Sends div elements – does not use database, just uses Ajax and PHP Demo P02.html & P02.php - P02.html embeds Ajax framework – the PHP code is NOT disclosed her [and will not be given]. Class Exercises Upload words.txt to MySQL table for use in assignment 05 Run Ajax examples above References See Asgt 05.doc -- under Assignment 07 directory (This makes only 5th assignment by the way. The previous assignment was Assignment 04 on data validation.) 25
  • 26. 6. Form to piggy-back on Google search0.html Google hl (hidden?) and q search engine variables; en & ru language codes getElementById(200).submit ( ) to submit Form element menu, onchange event calls f which calls Google (with data) 7. Wrapper for div 's Demo P1a.html & P1a.php under Assignment 07 directory Username=mchugh password= I9S84aXJ6 to access database required. Warning: this uses an HTML Form to start the PHP so the original page is destroyed. This is different from the desired AJAX model where the original page is not Destroyed and the results from the server are just embedded in the page. NO Ajax is used here. Demonstrates part of the features required for assignment 05: - retrieves words beginning with fixed prefix (here ba) - with fixed SQL statement: select word from dict where word like 'ba%' Limit 15 - PHP builds div elements containing the retrieved dict word contents - these are sent by print to browser as usual - the elements have onmouseover effects but only partial onmouseout and onclick effects - these are placed in div elements that follow a style also given on the page - the click event in a div just puts the fixed word House in the input text field - the source page view shows the HTML constructed in the PHP code - this helps you to "reverse-engineer" back to the PHP code needed to make these elements P1a.php uses database table dict – with column word – retrieves Limit 15 This illustrates HTML wrapping process –not the Ajax interface. The PHP page discloses some of the style rules and JS related to assignment 05 – it does not reveal the PHP code itself….but you do see the HTML constructed by the PHP code ! Simpler versions First see if you can make an analog of P1a.php that just sends the data (that begins with ba ) back from database but just separates the data with <br> statements. You can use the same HTML Form page as above. Then modify this so it also sends the search text (not just fixed data ba) when you click. If you try to modify this so it sends the search text when there is an onkeyup event in the text field, you run into the paradox that you can only type a letter and it already triggers the PHP call from the Form and wipes out the Form contents! -- so you can't type a whole string, which defeats the purpose! The only exit from this paradox is to remodel the HTML page into an Ajax framework.) 26
  • 27. M02.html & .php Ajax Interface – not HTML Form – so you do not see the generated HTML code ! The HTML page input lets the user type text – like say ab, and the PHP code retrieves a list of words beginning with ab from the database dictionary table. Unlike the P1a.html example above you do not see the dynamically generated code from the PHP program because this is a live Ajax interface, not an HTML page constructed from the PHP side. Use View > Refresh. Exercises Modify the HTML page above so it triggers a call at each onkeyup event. To do this easily first, just copy the HTML page to your desktop. BUT change the reference to the target PHP file M02.php (which is in my directory !) from: http.open('get' , 'M02.php?v=' + z + "&sid="+Math.random( ) ); to instead use: http://www.cs.njit.edu/mchugh/psswrd/web-course-materials/IT202/Fall2003/A- assignments/Sp06/AA%20Spring%2009/Assgt%2007/M02.php Also use an onkeyup = "sndReq( )" in text field. Also colorize the target div container with a style to better see where the response is placed. Re-focus Key Board input in text field. Security issues remain here. To test it just use the desktop environment for the HTML and drop the HTML file in the browser (if you upload to your web site you may get a security error). When you type text, you will see the Ajax effect. Then: try to define and upload to your web site your own PHP file that does this….BUT FIRST try the following simpler problem using the basic Ajax framework above. Just define a PHP file that prints the text entered in the text field back to the browser. Notice from the Ajax + HTML source that the PHP deposits the results "printed" from the PHP to the id=200 container in the HTML page. Colorize the container so it is more apparent where the results go. 8. Assignment 07 directory Animated PowerPoint diagram.ppt Examples on web site Understand the styles Understand the Javascript user-defined functions Understand the Ajax framework functions Understand how the Ajax + PHP exchange works – what remains & what returns Understand how the Form + PHP exchange works – what returns Understand how to construct useful HTML widgets like div with events Understand onkeyup in Ajax framework Understand Ajax http.open piggy-back effect Integrate with diagram.ppt 27
  • 28. http://web.njit.edu/mysql/phpMyAdmin/Last assignment will be pure Javascript -- to be assigned this Thursday Timed quiz example. Classes 24 – Assignment 06 Briefly overview the Ajax-Google Project using animated PPT. ` Discuss: Random timed quiz application Refer to manual - pages 139-145 Uses: Random numbers Arrays [at least the random picture assignment does] Delays innerHTML Assignment 06 random picture identification quiz with timer and score tally Make it a problem where random pictures are displayed and the user has to enter the name of the person (like presidents, etc). You could give the user multiple choices. Alternative make a good variation of the number quiz for [possibly] simple fractions [?]. Other games that you want to make up are also OK. You can also have some fun and use this to explore ideas that you might be interested in. Subsequent classes will continue to introduce new ideas having to do with other related HTML/JS topics. Possibly look at http://www.developertutorials.com/scripts/7/ For example applications. 28
  • 29. Classes 25 – Image Maps in HTML, Ajax and picture quiz Image maps Refer to Manual pages 130-131 Manual pages 70-72 window.open(p) open method's parameters (p,'', 'width =300, height=300' ) win.close( ) method where the "result" of window.open has been saved in the user defined variable win if (win != null) – to ensure there is a defined open window [named win] that can be closed <img src = "A.gif" usemap = "#BMap" /> -- usemap is the sub-partition of the image <map name= "BMap "> -- cross-reference in the map element that defines the image regions <area shape="rect" coords = "0,0,100,330" – sub-element for rectangles <area shape = "circle" coords = "218,180,10" <area shape = "polygon" coords = "10,400,55,395 -- beginning of sub-element for polygonal regions href="Jupiter.jpg" -- allowed hyperlink in area Refer to ImageMaps under directory for this semester – such as ImageMaps02.html Assignment Random Picture Quiz Arrays Random indices Avoiding repetitions Down-counter Ajax assignment – see diagram.ppt animation under Assignment 07 directory. 29
  • 30. 30
  • 31. 31
  • 32. 32
  • 33. http://en.wikipedia.org/wiki/Document_Object_Model Assignment 03 Discussion to be continued ---- Database Passwords – Require this (or next) technique for Assignment 03 Verify username / password on HTML Form lie in database Password table to obtain service. Built-in function: mysql_affected_rows ( ) returns number rows affected by select execution Use: ( mysql_affected_rows ( ) > 0 ) or ( die ( "no service for you with this password" ) ) ; Demonstrate R. Acosta's work on Assignment 02 (implemented in perl) I will base future assignment but done in PHP on this. Password from database - mysql_affected_rows ( ) http://web.njit.edu/mysql/phpMyAdmin/ Encrypted passwords – Optional alternative for Assignment 03 password handling Uses encrypted password + user name stored in database (one way encryption). 1st: Encrypt Form's password with crypt function (and no 2nd salt parameter). Insert associated username + encrypted password into database table. 2nd: To allow password-protected data retrieval: Get username and password from Form. Retrieve row(s) from database with matching username, and include encrypted password. Observe that: The PHP crypt function has the property: $w = crypt ("your_password"); crypt ( "your_password", copy of $w from database) equals $w This fails if "your_password" is invalid. Assume usernames in Password table are unique. The SQL / PHP construction is: $x = Execute: select * from Password table (attributes username & password-EC) where username = 'name-on-form' ( mysql_affected_rows( ) > 0 ) or ( die ("Invalid password – username") ) ; $y = mysql_fetch_array ( $x ) ; ( crypt ( "your_password" , $y["EC"] ) == $y["EC"] ) or ( die ("Invalid password - username") ) ; A match in the first term occurs only if the 1st argument of crypt originally encrypted to the 2nd argument. See PHP 02.ppt under Assignment 03 33
  • 34. http://www.w3.org/TR/WCAG20-TECHS/SCR29.html 3. Div element (container – tables etc), document.getElementById ( id ).style.property, style properties – color, fontSize, background. 4. innerHTML, Javascript Strings, concatenation operator in JS: + 5. arrays, randomly assigned values, Math.floor ( 4*Math.random ( ) ) HTML container elements div and span spelling conventions in JS versus styles such as: fontSize (JS) versus font-size (CSS) .innerHTML - replacement HTML for containers arrays built-in functions for random numbers – random whole numbers & array indices details below Dynamic HTML Control style properties (like text color, font) and HTML contents (innerHTML) of a div container. Make a container: <br><br><div id=4> Hello </div> element Apply dynamic styles to div text: document.getElementById(4).style.color= "pink" Apply font and background color to div element document.getElementById(4).style.fontSize ="36pt" fontSize (JS spelling) ---- font-size (CSS spelling) document.getElementById(4).style.background = '#dddddd' (RGB hex notation shade of gray) Replace HTML inside div area: innerHTML – replace current HTML contents of target element document.getElementById(4).innerHTML ="<br><br>" + u*v +"<br><br>" document.getElementById(4).innerHTML ="<img src='us.png' height=100 width=100 >Hello" Typical Built-in Function Popup for random number: Math.random( ) alert ("random " + Math.random( ) ) Change to: 4* Math.random( ) -- test it Change to: Math. floor ( 4* Math.random( ) ) - test, case-sensitive, 0..3 Javascript arrays Array – of strings var A = [ 'red', 'cyan', 'green' , 'brown' ] – define outside f - variable scope issues here? Move random expression outside alert w = Math. floor (4* Math.random( ) ) //random index c = A[w] //random color alert( "random " + c ) document.getElementById(4).style.color= c References text pages 118-127, 115-118 Examples prototypeJavaScript 01.html & templateJS01.html -- under Assgt 04 on web site 34
  • 35. mysql_real_escape_string use around input string to avoid so-called SQL injection security attack 35
  • 36. OLD NOTES Fall 08 OLD NOTES Fall 08 OLD NOTES Fall 08 36
  • 37. http://www.ajaxprojects.com/ajax/tutorialdetails.php? itemid=9#start Class 02 Intro -- Thursday January 22nd Exercise for Tuesday – does not have to be handed in but is relevant to class, assignments, and exams. I may ask to see your work at random and its performance will then be recorded. 3. Access your MySQL database with the account name and password sent to you by the system administrator before the semester started. Make a table with a few columns and enter some rows of data. Execute an SQL Select query (the details depend on the table and column names) like Select * from People where Age > 10. Snapshot the screen for the SQL results. http://web.njit.edu/mysql/phpMyAdmin/. Remember student accounts use sql2.njit.edu 4. Post an HTML page under your web site containing a link to the image of the MySQL page with the results of the SQL query. 5. The page should be in a directory with an index.html file and no link to it. Send link to me by email when done. Work thru exercise in class: 12. Demo assignment solution. 13. Simple HTML page with img tag and hyperlink. 14. Logon to MySQL (open source database) 15. Create table (make up one) with data types 16. Populate table manually (SQL inserts). 17. Browse table 18. Use SQL Select query to list contents of table. 19. Snapshot table - <alt> Prnt Scrn 20. Save snapshot as PNG file (properties) – versus bit map, run paint.exe, etc. 21. Drag-and-drop display of HTML page. 22. Validate HTML page – http://validator.w3.org/ -- correct errors. – DOCTYPE, meta charset, title, / > tags, alt ------ 37
  • 38. 23. Upload files(s) to web site and retrieve using http request. SSH, public_html, subfolders, Unix capitalization sensitivity vs. Windows. 24. Use telnet and direct HTTP request to GET file. Demo with test/b.html & us.gif on web site ( telnet web.njit.edu 80 ; GET /~mchugh/test/b.html HTTP/1.0 ) – use terminal from SSH. Image not included in HTTP response message. Display message as HTML Page! 25. Consider details of saving web copy of file – test/b.html -- such as in IE. Class 03 Continued -- Tuesday Sept 9th Previous class covered items 1-10 but only initiated item 11. Continue with: 11. Validate HTML page – http://validator.w3.org/ -- correct errors. – DOCTYPE, meta charset, title, /> tags, alt. Compare introducing bgcolor="red" in p element. 12. Upload files(s) to web site and retrieve using http request. SSH, public_html, subfolders, Unix case sensitivity vs. Windows. 13. HTTP exchanges under the browser hood: Use telnet and direct HTTP request to GET (retrieve) file on web. Try such as: mchugh/test/b.html on web site: (1) telnet web.njit.edu 80 ; (2) GET /~mchugh/test/b.html HTTP/1.0 – use terminal window acquired from SSH. Telnet establishes two- way TCP connection over which HTTP messages are exchanged with remote computer (like web.njit.edu or google.com) on port 80 (where web servers listen by convention). Or try: telnet google.com 80 and request: GET /index.html HTTP/1.0 to retrieve Google home page. Or use numeric IP address for google.com: 74.125.19.103 instead of symbolic name (can get IP from http://whois.ws/ ). Images referred to in these HTML pages (like us.gif in same dir as b.html) are not included in HTTP response message. Display response message (copy from command prompt) as HTML Page! 14. Saving web copy of HTML files – test/b.html – notice browser side-effects -- such as in IE. Validation (11) For character encoding tag see http://www.w3.org/International/O-charset and <meta http-equiv="Content-Type" content="text/html; charset=utf-8" > For DOCTYPE see http://www.w3.org/QA/2002/04/valid-dtd-list.html and <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> Book p. 64-71 but primarily: p. 65 (items 1,2,3,4) and 66-68 on HTML/XHTML and strict HTML. For list of deprecated attributes see http://www.codehelp.co.uk/html/deprecated.html. I9S84aXJ6 http://web.njit.edu/mysql/phpMyAdmin/ 38
  • 39. Telnet Remarks (13) Web site > Introductory Survey > Internet Exercises > pages 4-9 on telnet Note web.njit.edu domain has IP address 128.235.251.25 Saving HTML Files (14) Be aware that when saving a file that you have opened with a URL, browsers create folders for referenced images and also alter hyperlinks so that what you see is not necessarily the same as what was posted. The side-effects depend on the browser. To get the original HTML either download it directly or look at its source using the browser View option. Examples from Book Notes HTML, Javascript, and other files are posted under the Book Directory under the A Fall 08 Assignments on web site. !!! First Assignment to "Hand in": HTML { Forms, validation }– PHP – SQL - MySQL Book References – Most of the sections below will be revisited repeatedly during the term: Exercise01 Part I Basic Markup, Hyperlinks, Images (will continue to go over these) HTML and XHTML, Standards, Validation Part VI SQL/MySQL For Assgt01 Part V PHP – Web Scripting Language Part VI SQL/MySQL Part VII PHP II – PHP and databases Note html effects like Omitted " Omitted > 39
  • 40. Class 04 -- 3-Tier Example (Browser – Web Server – MySQL) Assignment 01 -- http://cs.njit.edu/mchugh/notesIT202.html > Problems Solutions > Class Notes > A Fall 08 Assignments > Assgt01 > materials – due: Friday September 19th 6PM Requires 1. HTML Form to send data and request PHP program. 2. PHP program for calculations and database access. 3. Acquiring Form data by PHP program. 4. Screening right to get the calculation by password. 5. Simple calculations and response to browser from PHP. 6. Creating and verifying inserts into MySQL table. 7. Creating and Validating strict HTML pages. Prototype examples ( Get the a.txt and b.txt files under directory above and rename as a.html & b.php. ) Form to start program & trivial PHP program file Introduce PHP segment in b.php with print "hello" ; make HTML form in a.html that starts PHP { form: form action attribute; input element type submit with value (?) } – upload/test (Modify) Form to send data to server and PHP to receive/echo Add input type text to form, with name ! & make PHP acquire data sent to web server { form: form input element type text with name (?) , PHP: $u = $_GET["A"] ; print back what $u is to browser } , upload/test – test syntax using site below - check source results in browser (Modify) php to connect to database $hostname -- $username -- $password -- $project mysql_connect (arguments) – mysql_connect( $hostname, $username, $password ) or die ( "Unable to connect to MySQL database" ); //Connect or exit message construction: ( --- ) OR die ( --- ) Identify database project: mysql_select_db ( $project ) or die ( mysql_error ( ) ) ; Make MySQL that has one element table Manually create database table test / one column type text. (Modify) php to insert data Add single quotes to text data -- $s = "insert into test values ( $u )" ; //Defines query mysql_query ( $s ) or die (mysql_error ( ) ); //Runs query. Run code & verify against database. Reference Refer to http://www.meandeviation.com/tutorials/learnphp/php-syntax-check/ to check syntax. Check book chapters and http://us2.php.net/manual/en/ for general guidance on PHP syntax. 40
  • 41. Class 05 - 06 3-Tier Example (Browser – Web Server – MySQL) Purpose This illustrates a three-tier architecture for a toy application, as well as some basic PHP control structures. The PHP date function serves to illustrate how to garner syntactical information from Internet web sites. The or die construction is a useful PHP idiom for filtering out circumstances you want to avoid. The program flow view provides a pseudo-code like preview of the design of the program. The logic has been kept simple based on the or-die construct. Assignment 01 -- http://cs.njit.edu/mchugh/notesIT202.html > Problems Solutions > Class Notes > A Fall 08 Assignments > Assgt01 > materials – due: Friday September 19th 6PM Plan for PHP Assignment Program 0. MySQL Log Table: Create MySQL table to Log the Form requests with columns for user name, M, N, status (valid/invalid), time and date of request. 1. Form data: GET Form data (name, request password, M, N) and prep text values for database. 2. Time & Validity: Get time & date, as well as password validity and save as variables. 6. Log Entry: Connect to database and insert (Log) request: name, M, N, status of password's (valid/invalid), time/date entry. Note: Doing the database above before the processing below simplifies program logic. 4. Password: If password for request is invalid, send message and exit. 5. M & N Validity: If M & N for request are invalid, send message and exit. 6. Output products from: 2 x 2 = 4 … to: M x N = M*N on separate lines. Date and Time Refer for PHP function date to: http://www.w3schools.com/PHP/func_date_date.asp The date function has confusing options. The link gives examples like: date ("l dS of F Y h:i:s A") that give you what you need. You would save the function value as a PHP variable and insert that is its proper column in the database table: $v = date ("l dS of F Y h:i:s A") ; Don't be concerned with format details (like that the first lowercase "L" in above means the day of the week spelt out) – you can apply it like an off-the-shelf product that you can use without necessarily understanding how it is manufactured. The key point is to understand its availability, how it is used, and where to look for further information. . 41
  • 42. Password Status Assume the hard-coded password is (say) "zebra" and the password fed from the Form is stored in a PHP variable $pass. An if-else or similar construct can be used to define a $status variable as "valid" or "invalid" depending on whether $pass equals "zebra" or not. The if is: if (condition) { statements ; } Log Entry This just requires an insert into the database of the vector of data acquired from the Form page. The date / time is just another text field, as is the valid / invalid status value. Useful PHP construction The statement: ( expression ) or die ( string ) ; evaluates expression and falls through to the succeeding statement if expression is True, but otherwise it executes the die statement which sends the enclosed string message to the browser and then terminates the PHP program. This shortcut evaluation of an or condition is widely used in PHP. Password Validity Assuming again a hard-coded password like "zebra" and a password value from the Form stored in $pass. The or-die construction provides a clean way to handle this authentication check at this point in the program flow (item 3): ( $pass = "zebra" ) or die ( " Bad password. Bye. <br><br>" ) ; This password is separate from the password to access the database which is used to connect to the database. It is used to determine whether your request for the times table should be honored. M & N Validity Require the user's M and N values to be > 1. This simplifies starting the outputs at 2 x 2. The or-die construction provides a clean way to handle this (item 4): ( M > 1 && N > 1 ) or die ( " M and N values must be greater than 1. <br>" ) ; Results for Browser A stream of print statements have to be generated using appropriate for-loops. Mathematically the for-loops are: I = 2 .. M J = 2 .. N Syntactically: for ( $I = 2; $I < $M + 1 ; $I++ ) for ( $J = 2; $J < $N + 1 ; $J++ ) { … ; } 42
  • 43. where the body { … } of the loop contains the statement(s) that generate the calculations and HTML code sent to browser via print statements. The output should look like: 3 x 4 = 12 3 x 5 = 15 How is this done? Program Flow Get Form data Determine date /time Determine password validity for status Connect to database Insert Log or description of request: name, M, N, status, time/date The processing above is always done. The processing below is only done if the conditions are passed. Continue on only if the password is valid, else exit with message. Continue on only if M & N are in accepted range, else exit with message. If you get this far, then you can generate the results for browser from 2 x 2 = 4 up to M x N = M*N. Simplified Code Stream 1. mysql_connect 2. mysql_select_db 3. GET $pass -- and prep 4. GET $M -- no prep 5. define insert 6. mysql_query 7. password barrier --- ( pass test ) or die 8. number barrier --- ( pass test ) or die 9. for $I = 2…$M … print --- concatenation operator dot ( . ) 10. date function argument http://www.w3schools.com/PHP/func_date_date.asp 11. define $status (as text) 12. mysql_error( ) -- syntax: http://www.meandeviation.com/tutorials/learnphp/php-syntax-check/ 43
  • 44. Class 07 HTML Tools – High Level Editor - Styles Purpose High level HTML Editors like FrontPage (or Dreamweaver) are software tools that dramatically increase the productivity of anyone writing HTML applications. They do this by providing menus of specialized tools for common tasks like making tables, visually changing text (rather than directly going into the HTML code that does this), providing popup menus that prompt the developer with options for HTML tags or attributes that can be used at a certain point, and so on. We illustrate this for the case of HTML tables especially (which we will use frequently). HTML editors also provide aid in construction the relative paths that may be required to locate image files or a document that is hyperlinked to. We also introduce how styles work by way of some examples. Style rules are required for most appearance effects in strict HTML where they have replaced the traditional presentational attributes and elements like font tags. Software Development Tools: HTML Editors – like MS FrontPage Purpose: high-level tools like HTML editors are useful for increasing the productivity of HTML developers and also as learning tool for beginners. - how editor environment works – code and design views, can introduce content either interface Then check the effect on the other interface - skeletal HTML tags (head, body, etc), meta tag for character encoding - illustrate editor's tag prompting capability for typical elements like: paragraph element (p) and preformatted element (pre) – also how each of those behave HTML Tables and other Basic Elements Purpose: Tables are a basic HTML element for presenting arrays of data and organizing the information on a web page. - element for data presentation as well as page layout - making table via editor – dialog window for setting basic preferences - table, tr, td, th tags, th element's bold/center behavior - attributes for table tag border, bordercolor RGB notation for colors generated by Editor, RGB color model, hex notation, standard colors Table align attribute [deprecated] – tag prompts guide its implementation cellspacing, cellpadding - td cell colspan, rowspan design view's merge tool including img and hyperlink elements in cells of table - img tag width, height src URL paths – automatically generated based on user navigation in Editor ../ notation advantage of relative paths versus absolute paths, relocatability alt - hyperlink tag: a element 44
  • 45. Styles Purpose: Styles are the preferred alternative to attributes for specifying presentational details about how HTML elements appear. Styles and style sheets are basically required in more recent versions of HTML. Style sheets can be used the unify the appearance of pages on a web site, since the same style sheet can control the appearance of many different pages. - via element in head of page or as style sheet - style rules, properties & values - examples for table element (replacing deprecated attributes for that tag) for strict HTML, also for image tags, cells - sample syntax and effects <style type=text/css> table { border: 3px solid red; color: blue; } – shortcut notation </style> - style properties for table element: font effects Examples -- under Assgt02 directory on web site: MS01.html, table01.html – also assgt02.html & make.html 45
  • 46. Class 08 Software Factory for HTML Code Topic How to manufacture a dynamically sized HTML table in PHP. Purpose A common Internet application requires retrieving data from a background database (such as by using a scripting language like PHP together with SQL to interact with MySQL) and then structuring the retrieved data for display in a browser. The data from a database is often displayed in a tabular layout as an HTML table sent to the browser by the PHP program. In addition to its practical significance, it is also intellectually interesting to realize that we can use one language (PHP) to construct the code in another language (HTML). Doing this requires one to understand not only PHP and the environment it operates in, but also HTML constructs like tables, and to understand how to manufacture the code for the table by a reasonable PHP algorithm. The PHP program thus becomes a sort of software factory which the developer designs that builds HTML code. Pseudo-code algorithm to construct HTML table -- the logic matches the table structure Start table For I = 1 .. 12 { Start row For K = 1 .. 10 { Start cell Make Product Stop cell } Stop row } Stop table The implementation requires converting the pseudo-code to PHP, like the pseudo-code: Start table becomes the PHP code: print "<table>" ; See example m1.html, .php and .txt (check browser view source) under Assgt02 on web site. The example make.html [ which runs make.php ] illustrates the objective. To complete 1. Parameterize solution with M and N: affects loops 2. Add spanning 1st row with centered name in top spanning cell: affects colspan Include style rule on PHP page too….illustrates intermixture of PHP and HTML codes Examples -- under Assgt02 directory on web site: m2.html, m2.php, m2.txt, also: m1.txt, etc 46
  • 47. Above results in response to Form below– see under Assgt 02 make.html on web site. Assgt02 Retrieve database table built for Asgt01 and display the results as an html table – see assgt.html02 illustration under Assgt 02 homework on web site for illustration (only) – test this sample using Joe for the name field and zebra for the password field's input. The password here is hardcode in the PHP and there are entries for Joe in the table used (Addresses). For the actual assignment, you must instead retrieve the table you built under Assgt 01 -- with the name input on the Form typically being one of the user names that were logged so you select only that user's log entries. The look of the table is obtained by styles included on the PHP page. See notes for Class 09 47
  • 48. Class 09 DB Retrieval from Program Purpose An essential capability of a three-tier environment is the ability to retrieve data from a database (previously we have only entered or inserted data into a database from a program). We consider the SQL and PHP tools required and adapt our previous discussion of how to construct dynamic HTML to translate the retrieved results into table code for a browser. Pseudo –code for Data Retrieval ----------------------------------------------------- Define select query string S Run query S Store results of query S in D Display D, row by row - use fetch method to get next row – repeat with while loop while ( R = fetch ( D ) ) { print R [ "name" ] print R [ "phone" ] } ----------------------------------------------------- Note on pseudo-code The PHP access methods used are: ROWS mysql_fetch_array ( D ) CELLS The fetched row R is an associative array accessed by names of database attributes. ----------------------------------------------------- Retrieving from database in PHP using SQL Select statement -- Paradigm - PHP Code $s = "Select * from Table1 where name = " . $u ; //define query $D = mysql_query( $s ) or die(mysql_error ( ) ) ; //run query & save while( $R = mysql_fetch_array ( $D ) ) //scan rows until done { print ( "<b>Name: </b> " . $R['name' ] . "<br>" ) ; //get value of name print ( "<b>Age: </b> " . $R['age' ] . "<br>" ) ; //get value of age } Relationships: Select > mysql_query > DB Table > $D > $R > $R ["attribute_name"] table > row > cell 48
  • 49. Defining SQL Select Statement $s = "Select * from Table1 where name = " . $u ; Executing SQL Select statement The responses are returned in variable $data. $D = mysql_query($s) or die (mysql_error( ) ); The resulting data object corresponds to the table that results from executing the Select statement. Scanning retrieved SQL results mysql_fetch_array ($data) returns next row of the table of results or False if no more. The while loop below repeats as long as mysql_fetch_array ( $data ) succeeds. while ( $R = mysql_fetch_array ( $D ) ) { } The assignment ( = ) statement above becomes False when the right hand side is False which occurs when there is no more row to retrieve from $data. The left hand side $info is an associative array – that is access to its values is based on the names of the columns retrieved. Acquiring retrieved data from SQL results The associative array $x accesses the value of column "age" of current row. while ( $R = mysql_fetch_array ( $D ) ) { print ( "<b>Name: </b> " . $R['name' ] . "<br>" ) ; print ( "<b>Age: </b> " . $R['age' ] . "<br>" ) ; } Solution for Assignment 01 See under Assgt 01 > materials > assgt01.html, .php, and .txt on web site. Also assgt01.ppt for PowerPoint display or view of program. Notes 1. Try assgt02A.html and its PHP partner under Assgt02 directory on web site to see an illustration of a solution of Assignment 02. Make yours look somewhat different using styles, etc. The User Name for the HTML Form is presumed to be some user entered into the LOG table. The Administrative password in this example is hardcoded in the PHP and is magic . 49
  • 50. 2. See also assgt02B.html where the password is now contained in a database table! Thus the password must be retrieved from the database to be compared to the one submitted from the Form – the password is not hardcoded in the PHP code. The function mysql_affected_rows( ) returns the number of rows returned in response to a Select command and can be used in combination with a select statement to see if the submitted password is right. Example: m5.html, .php, .txt are posted under Assgt02 Midterm Exam Announcement – sample & answers to be posted for study ! 50
  • 51. Class 10 Exercise related to Assignment 02. Purpose This continues our consideration of database retrieval. The retrieval request from the HTML Form is only serviced after the password on the Form is authenticated against a list of valid passwords in the database. Upon authentication, the validated request is extracted from the database and the retrieved data is wrapped in HTML table tags for shipment to the browser for display. The diagram below depicts the interaction between the Form, web server and PHP program. Topics 1. How to make Select SQL for retrieving rows where name = value from Form 2. How to retrieve password from database for authentication with user submitted password. 3. Barrier test for password. 4. How to wrap HTML table tags around data retrieved from the database. 5. Table and body styles – borders, colors, fonts, background-color. USE TEMPLATE02.HTML & .TXT U NDER ASSGT02 to start examples. 0. Query string http://www.cs.njit.edu/mchugh/psswrd/web-course-materials/IT202/Fall2003/A-assignments/Sp06/A %20Fall%2008%20Assignments/Assgt02/assgt02B.php?name=Bert&pass=lucky Name=Value pairs are: name=Bert and [&] pass=lucky 1. These are sent to the web server which stores the data in some area on the web server. 2. The server starts the requested PHP program assgt02.php. 3. The PHP program then picks up the data values from the data area on Server using $_GET. Web server Browser HTML Form PHP program $_GET ["A"] action = x.php data here input name="A" 51
  • 52. 1. Select: select attribute-list from table-name where --- some condition --- Define SQL: $s = "select * from LOG where name = " ---- what goes here? Run & store: $D = mysql_query ($s) 2. Password Authentication Use Select to retrieve PASSWORD table's rows that match submitted (alleged) password. 3. Barrier test – using PHP or-die construction Were there any matches? ( mysql_affected_rows( ) > 0 ) or … what goes here? ( number of rows > 0 ) or die ( "out of here" ) ; Control falls through to next line of code if 1st condition succeeds. mysql_affected_rows ( ) is relevant PHP tool: equals number of rows returned by previous Select. 4. Wrapping data in an HTML table The hierarchical access stream that drills down to the data in a cell: DB table > $D - PHP table > $R - PHP row/associative array > $R["attribute-title" ] - Cell contents Numerically: There is One table with as many rows as there are rows in DB table and as many cells per row (<td>…</td>) as attributes in DB table. HTML tags are output like: print "<table>" ; 5. Strict HTML wants styles rather than (presentational attributes inside tags) Styles can be is style sheets and referenced suitably by HTML pages Styles can be in head element like: <style type="text/css"> td { color: red ; background-color: silver ; } </style> How the while condition works for row & cell retrieval while ( $R = mysql_fetch_array ( $D ) ) { ---- ; } 52
  • 53. 1. If fetch fails it returns False – which makes $R false – which makes while condition False so the loop Exits. 2. If fetch succeeds then $R equals the next row in $D - this is non-empty – and the result is that the condition is treated as True ( empty strings and zero are treated as False – in the same way non-empty strings and non-zero numbers are treated as True in terms of the while condition. See Assgt02 example while01.html and .php for illustration of these issues. 53
  • 54. Class 11 Intro to Javascript 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 and asynchronous (but nonetheless expected) events on the browser (like mouse clicks on individual HTML elements) trigger Javascript actions 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. Sample Midterm Exam Distributed – see under Fall 08 assignments on web site Topics functions, definitions & activation where Javascript goes – script tags events to trigger functions – onclick, onload alert function – here, to test operation of the script setup & pop up messages to the user document.getElementById ( id ) -- key JS method or function id attribute – works in tandem with getElementById dotted, hierarchical notation .value (for input field contents) error diagnostic tools in Firefox (Error Console – also for style errors) and Internet Explorer HTML container elements div and span .style attribute style properties – color, fontSize, background spelling conventions in JS versus styles such as: fontSize (JS) versus font-size (CSS) live changes to styles using Javascript .innerHTML - replacement HTML for containers Javascript Strings, concatenation operator in JS: + arrays built-in functions for random numbers – random whole numbers & array indices style rules for body Problem Make a simple single operator calculator that: - accepts a pair of numbers from input text fields on a Form, - calculates their Product when a button is clicked, and - stores both original inputs and product in cells of a table with one row and three cells. The table and cell borders should be red, the color of the HTML body text randomly assigned in response to a function call, and the font size for the table should be 36pt. Exercise - prototypeJavascript 01.html & templateJS01.html -- under Assgt03 on web site References: Part III of Manual 54
  • 55. Development 3. function, definition, placement, HTML Form, button event, alert for test, syntax errors – Firefox tools – IE tools. 4. DOM method, input field with id, document.getElementById ( id ).value, retrieve/store based on id. 3. Div element (container – tables etc), document.getElementById ( id ).style.property, style properties – color, fontSize, background. 4. innerHTML, Javascript Strings, concatenation operator in JS: + 5. arrays, randomly assigned values, Math.floor ( 4*Math.random ( ) ) Development -- see details below Define function with alert message function f( ) { alert("hello") } Test – appears on page as text Place in script element, retest – does not appear, but does not execute <script type="text/Javascript"> function f ( ) { … } </script> Add function call in script element – 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 – add id=1 in input field, u = document.getElementById(1).value assignment statement, Put u in message with concatenation alert("hello " + u) Add id=2, 3 fields for u * v setup and answer Comment out alert: //alert("hello " + u) Add <br><br><div id=4> Hello </div> element Add style rule in style element in head (later we'll introduce dynamic styles) <style type="text/css"> body { color: blue ; } </style> Apply dynamic styles to div text: document.getElementById(4).style.color= "red" Replace HTML inside div area: innerHTML – replace current HTML contents of target element 55
  • 56. document.getElementById(4).innerHTML ="<img src='us.png' height=100 width=100 >Hello" document.getElementById(4).innerHTML ="<br><br>" + u*v +"<br><br>" Apply font and background color to div element document.getElementById(4).style.fontSize ="36pt" fontSize (JS spelling) ---- font-size (CSS spelling) document.getElementById(4).style.background = '#dddddd' (RGB hex notation) Popup for random number: Math.random( ) alert("random " + Math.random( ) ) Change to: 4* Math.random( ) -- test it Change to: Math. floor ( 4* Math.random( ) ) - test, case-sensitive, 0..3 Array – of strings var A = [ 'red', 'cyan', 'green' , 'brown' ] – define outside f - variable scope issues here? Move random expression outside alert w = Math. floor (4* Math.random( ) ) //random index c = A[w] //random color alert( "random " + c ) document.getElementById(4).style.color= c 56
  • 57. Classes 12 & 13 Sample Midterm Exam Distributed – see under Fall 08 assignments on web site Exam schedule - 1/2 hour at end of class next Tuesday. Entire class next Thursday Class 12 1/2 - class - Javascript Tic Toc Toe Example 1/2 - class on Midterm Exam Basic Problem: Make simple tic-toc-toe board/table with cells that turn yellow or red depending on whose turn it is. Distinguish between cells that have been selected [clicked in by either player] versus empty cells. Only empty cells can be selected for a move. Use a toggle (like a variable whose value alternates at each function call from 1 to 0 and back again, repeatedly, to keep track of whose turn it is. This variable represents the player who move it is (say 0 for red, and 1 for yellow). Use FrontPage [or equivalent] to quickly make a Tic-Toc-Toe board, table or grid, then enhance that with multiple id's and onclick's for the individual cells. Syntactical tools: document.getElementById(k).style.background, title attribute for table cells, document.getElementById(k).title. Assignment 03: Demo and post a prototype solution in class. Later just demo functionality of a complete solution and explain ways to implement the various features. The initial behavior (after the HTML table view is setup) is to use Javascript to change the background appearance of cells selected for a move, alternate between players appropriately, and block players from selecting a cell that has already been moved into. 1. whose turn it is (alternation) 2. which cell has been clicked (id recognition) 3. whether the move is valid (accepted) or not (detect occupied cell, and block cells moved in). Uses 1. initialize variable – once only (why, where) 2. toggle variable defined by user 5. title attribute to make cell available or blocked – warn/return if occupied 6. parameterize function with id's Reference example: See tictoctoe.html under Assgt03. Class 13 2nd half of Midterm Exam 57
  • 58. Class 14 - 15 - 16 Javascript Continued – Tic Toc Toe Assignment 03 features (40 points) The assignment solution should include several of the following features: Due date: two weeks - November 1st -- SATURDAY Functionality or Behavior 1. record moves 2. recognize won game (and block further moves) or automatically recognize stalemate 3. impose time limit on moves 4. reset variables, tables, HTML fields/attributes to original values 1. Log of moves made Uses: textarea, value attribute, string contents for value, newline character to advance Lines of string "cat" + "n" + "dog" Record: move number, cell id, player color Use font shortcut style for text in textarea Skip lines Maintained automatically as moves attempted (log invalid requests also) 2. Test for win (rows, columns, diagonals) A. set title (for moved in cell) to reflect player who moved there – such as color – when move recorded. B. at any win-test, define an array of cell contents C. check at end of move operation for win situation D. scan array of contents for equalities that reflect win (like same [nonzero] values in cells 4, 5, and 6 - that is row2) – one can check equality without knowing color. Try this 1st with one row and complete the idea. E. Lock the board title attributes on win to prevent further moves F. Output result as message in div area. 3. Reset/clear/re-initialize variables and textarea on event request This includes anything that should be reset to some initial value so you don't have to refresh the page to replay the game: toggle variable, all cell title attributes, textarea, move number, delay default, timer identifier reference, array of cell contents to empty strings. 4. Time Limits for choice of move Uses: setTimeout function setTimeout( "h ( )" , milliseconds) -- delay before function called. Do at end of move handling – before or after win-test? Remember identifier reference for timer: ref = setTimeout ( …) Kill old timer before starting new timer to keep temporal logic simple / understandable: clearTimeout(ref) ref=setTimeout ( --- ) The function clearTimeout(ref) removes the designated active timer. When does setTimeout call function h( )? –only when move wait is too long – at which point h( ) can declare other player winner or let the other player move instead. Time limit logic: acknowledgements to Vincent Couto. Get new delay for time limit from user input and reset delay variable Optional: Make tic-toc-toe cells get a letter X or O depending on whose turn it is. Optional: computer generated moves in response to human player. 58
  • 59. Illustration of possible board configuration after too late move decision by Yellow. Review other required elements of the TTT assignment: Win & stalemate (use a table with its artificially title fields set manually -- as a stub to test the win-algorithm, for acquiring the titles into an array ( denoted say by v) that stores each cell's title values, use for-loop to capture the title value, watch out for the connection between the cell id's, the array indices, and the fact that array indices start at 0, test win algorithm logic on a sample row or diagonal of the HTML table, be aware that also need to "lock down" the board so play cannot continue after a win. Know how to post the outcome of the game in a div area. Also know where to invoke the win function – after the move is made. There are Extensive re-initializing chores: flags, array, styles, fields, title values, clearing timers, etc. I. Additional In-class Exercise below: Clock starts timer using the delay in milliseconds from the text field and posts "too late" message if Stop not hit in time, while Stop kills the timer – or resets message to "on time". This Example is posted under both assignments 03 & 04 because it is relevant to each of their timing logics: basicTime – there are two event stream scenarios in this example. The idea is that one button starts a timer -- while another button when invoke can stop or clear that same timer – provided the stop button is pressed in time. The Javascript uses: ref = setTimeout (---) to create a timer & clearTimeout(ref) to destroy the timer The following diagram illustrates the two independent event stream scenarios: 59
  • 60. start ------------- f --------------- timer ------------ g activates creates | | stop ------------- h ----------------- (race situation activates destroys between f & h) See Assgt03 folder on web site for Javascript code. This code can assist you to understand how to Do the move timing in the Tic Toc Toe assignment Assgt03. II. Demo gambling game – Assignment 04 Due date: about two weeks – Saturday November 8th Start button starts a timer with random delay (such as 1-3 seconds). At the end of the delay, a scheduled function starts another random time delay (such as 1-3 seconds). Effectively, a timeline is divided into three intervals: before the 1st timer goes off, after the 2nd timer goes off, and between those two points. A stop button event should kill the timers. The script defines a game where a reward/penalty depends on where on the timeline (with its unknown two points of division) the Stop occurs, that is what state the script is in when the Stop occurs. Note the following diagram. ---------------------------||-----------------------------||--------------------------------- I. Stop here II. Stop here III. Stop here Looses $5 Wins $10 Looses $5 The code should use two successive timers and a function activated by stop button should kill both the timers and decide the gambling outcome (I, II, or III) based on a "state" variable's value. In the picture below, the text field actually shows the actual random delays in milliseconds for the intervals I & II. The actual game would not display these values -- since they would help a player determine when to click the stop button so as to hit the "sweet" spot in interval II where the player wins. But they should be visible in your solution. See template.html for template example under Assgt03. An enhanced version of above game generates a dynamic timeline as shown below. The caret ^ shows where stop was clicked: in the picture it stopped in win zone. 60
  • 61. 61
  • 62. Class 17 - Media and Clocks - sounds, delays, recursion Purpose This class 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 introduce a simple seconds-based alarm clock example to illustrate the Date object. The implementation of the alarm clock uses the fundamentally important programming technique called recursion to repeatedly re-invoke a new Date once every second. There are significant variations among browsers, such as differences between the Javascript functions used in IE versus Firefox for media, but we do not consider these here. --------------------------------------------------------------------- Playing Sound Files <html><head> <script type="text/Javascript"> function playSound (p) { var x = document.getElementById(p) ; x.Play( ) } function stopSound (p) { var x = document.getElementById(p) ; x.Stop( ) } </script> </head><body> <embed src="flourish.mid" autostart=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 with Alarm, and Sounds <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 } 62
  • 63. 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> --------------------------------------------------------------------- Refer to: Manual pages 135-136 for basic HTML for sounds. Examples: See soundTest02.html & secondsAlarm.html under Assignment 05. Note: AFS restricts types of sound files. Definitely mp3 not allowed there. 63
  • 64. Class 18 - Events, rollovers, alarm clock assignment, recursion Purpose This reviews some basic HTML and Javascript syntax/tools and introduces the events (onmouseover, onmouseout). Applications like rollovers and a timed quiz illustrate their use. Note Assignment 04 is now optional – if done, it is due Saturday. We also describe and demonstrate the next homework assignment 05, a musical alarm clock. Examples Posted (under Assgt05 directory) rollover01.html -- adapt to random image selection from array of images rotatingImages.html Assignment 05 Demo – Alarm Clock See images and assignment requirements that follow. This assignment requires the use of sounds, recursion, Date object and methods, and style sheets Notes on assignment 1. Date gives military time – that is 0 to 23 hours 2. seconds 0-9 are single digit – so need to prepend leading 0 to make all seconds display uniform in length 3. Explain purpose of debug feature: allows testing without having to awkwardly reset the system clock to test the display of different times. Note how the button for this toggles. 5. Date object has methods for day of week and month which return integers starting at 0 that need to be converted to names of days and months. Comments on rollover01.html example 1. Introduce separate style sheet and link element to refer to sheet. 2. Emphasize how img element needs id to be used by Javascript. 3. Recall array syntax 4. Array of images (as needed for extension of the basic rollover example to a randomly selected replacement image). 5. Creating appropriate random whole numbers - range starts at 0, Math.random ( ) function and Math.floor ( ) function. 6. Redirecting src using getElementById 7. Initialization of array outside function f ( ). 8. Use of recursion to repeatedly execute f ( ) at delays. 9. Terminating repetition with clearTimeout ( ref ). 10. When are images downloaded for page? 11. Array can also contain hyperlinks as well as downloaded images. 64
  • 65. 65
  • 66. 66
  • 67. Class 19 - More examples Timed arithmetic quiz application uses - onfocus event getElementById(id).focus( ) onblur onload First consider the Look of the application 67
  • 68. Behavior is as shown in demo including Randomly generated addition problem Delayed checking of solution submitted Posted results – right or wrong Underlying Requirements Question button => question generating function => by delay triggers answer checking function Set speed button => picks up delay from text field Div element => where initial random question is posted by question function => results are posted after being checked by answer function Text field for user answer => where user answer entered and acquired after delay by answer function HTML and JS Syntax and tools required id's random indices pseudo-code: answer function get user answer compare user answer with true answer post results accordingly question function get question randomly post question clear text field and focus cursor there call answer function after delay Problem Exercise - Dynamically generated menu HTML menu syntax New entries added from text field and included by onclick event innerHTML update = "fixed lead part" + current string (initially empty) + addition-segment + "fixed tail part" where s is previous value of s [perhaps originally empty] the parts are the start and end of the select tags of a menu addition-segment is newly acquired part based on input from field - gives text for new menu entry 68
  • 69. AJAX – Javascript - PHP Purpose This is a brief introduction to AJAX based on an email written by Rasmus Lerdorf – the author of PHP and now Google software architect and developer. AJAX is a Javascript interface that lets an HTML page communicate behind-the-scene or asynchronously with a program script on a web server – without loosing the current HTML and Javascript context. --------------------------- Examples rpc01.html and rpc01.php under Assgt 06 We consider these modified examples based on that of Rasmus. Once you understand these you could Check out some of his other comments. Email on AJAX by Rasmus Lerdorf (the inventor of PHP) http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html --------------------------- Syntax references (relevant to understanding the example) PHP on line manual http://us2.php.net/manual/en/ $_REQUEST as used in PHP here http://www.w3schools.com/PHP/php_get.asp Can use to get data from either an HTTP post or an HTTP get. Syntax for PHP switch statement used in example See page 151 of manual --------------------------- PPT discussion – includes link to typing demo http://www.gpeters.com/present/ajax-php-article/ Video – may or may not be useful – I just glanced at it: http://www.youtube.com/watch?v=zJjvn77i-wU Source code for examples follows. 69
  • 70. rpc01.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; } var http = createRequestObject ( ); function sndReq ( p ) { http.open ( 'get', 'rpc01.php?u1=' + p ) ; http.onreadystatechange = handleResponse ; http.send (null) ; } function handleResponse ( ) { if (http.readyState == 4) { var response = http.responseText ; document.getElementById('foo').innerHTML = response } } </script></head><body > <a href="javascript:sndReq('foo')">[foo]</a><br><br> <input type = "button" onclick="sndReq('foo')" value = "AJAX request foo" > <input type = "button" onclick="sndReq('boo')" value = "AJAX request boo" > <input type = "text" value = "I am Sad." > <div id="foo"></div> </body></html> rpc01.php <?php //made contact switch ( $_REQUEST ['u1'] ) { case 'foo' : echo "I am case foo" ; break ; case 'boo' : echo "I am case boo"; break ; } show_source ( "rpc01.php" ) ; ?> 70
  • 71. Class 20 – AJAX Assignment Example – AJAX, PHP, MySQL, Javascript http://www.w3schools.com/PHP/php_ajax_database.asp This example uses a fixed menu of items from which it displays information about a selected item chosen from a database. The implementation of the AJAX is slightly different than the model described in class. The class model is preferred. --------------------------- Assignment 06 Modify the idea of the w3schools example (above) so it picks up a list (such as of states, countries, or whatever category you like to illustrate) from a database to create a menu. This can be done from an AJAX point of view -- or (which is recommended) as part of an initial HTML/PHP page. Use the PHP to retrieve the data from a database table (analogously to how the LOG table was acquired from a database in Assignment 02 except that here a menu (select element) is constructed rather than an HTML table). The database table can have two attributes which might be called NAME and CONTENT. The latter attribute should be of type text to allow a large amount of data for each named item. The NAME attribute's values are used to build the HTML menu. The menu created should be sensitive to an onchange event (as an attribute of the select element). Whenever a menu item is selected, a paragraph of text (the corresponding element's CONTENT) should be retrieved from the database table, using the value of the menu item to retrieve the CONTENT -- based on the value of NAME. The CONTENT results can be stored in a div field of the page. This retrieval should follow an AJAX approach so the behavior can be repeated without otherwise disturbing the HTML page. In summary: a menu is dynamically created when an initial PHP page is requested -- and subsequently selection of a menu item triggers a function that implements an AJAX request to retrieve the descriptive content associated with the selected menu item. initially = > establish a menu based on a database table via PHP menu selection event = > retrieves text related to the selected entry via AJAX and displays in page database = > table of menu entries and textual content that gives information about the selected item (the text data type in MySQL can have up to 65K characters). Thus the initial setup of the menu is based on the database and done in PHP. Subsequently, AJAX-driven requests can retrieve data from a database with a PHP script as the mediator. --------------------------- Syntax references Text length in MySQL http://www.ehow.com/how_2377307_common-mysql-string-data-types.html AJAX onreadystatechange property http://www.w3schools.com/ajax/ajax_xmlhttprequest.asp 71
  • 72. http://web.njit.edu/mysql/phpMyAdmin/ Refer to examples: menu0.html and menu1.txt under Assgt06 - menu0.html - provides menu syntax and onchange event - menu1.txt – parallels assignment 02 construction of table – but for menu 72
  • 73. Class 21 – AJAX Continued AJAX detailed discussion continued PHP Script 1: PHP code to generate dynamic menu + HTML skeleton including Javascript for AJAX. PHP Script 2: PHP code, invoked by Javascript AJAX function, that looks up CONTENT for selected menu row (whose value determines the attribute NAME which acts as SQL search key – that is the SQL where clause). The result from executing PHP script 1 sends an event sensitized menu to browser. The result from executing PHP script 2 sends a responseText that is planted in (say) a div area in the invoking page. PHP file 1 HTML plus AJAX Javascript code PHP code to generate menu from database Finish up HTML code including a div tag with an id PHP file 2 PHP code to access CONTENT from database table (for NAME value from menu) AJAX – The example at link is interesting – though in a way it is a bit silly since it uses hard-coded data in the PHP script invoked by the AJAX, while this kind of feature should be processed through a database.. http://daniel.lorch.cc/docs/ajax_simple/ Click ajax-cool.html and try example. Type in the proposed user name to see the AJAX dynamic results. The input text field: <input type="text" onkeyup="validate(this.value)" /> The text field is sensitive to an onkeyup event, which calls the function validate with the value from the field and so is activated whenever a depressed key is released. The PHP script validate.php checks the value at each such event and sends different responses depending on what the value is (empty, less than three characters in length, three or more characters in length (in which case here it is handled by a case analysis when there is a match with a name in the hardcoded list. If no match, then the "<span id="notice">Username ok!</span>n" is returned. In principle of course the name list of existing names should be checked against a database. How would that be done? This will be the next and probably final assignment. Compare Google automatic pop down menu. 73
  • 74. Class 22 – Alarm Clock Refer to AlarmClockTemplate.html example under Assignment 05. Comments on Clock Assignment Debug flag determines if displayed date/time comes from Date object or Debug fields. Date object gives hrs, min, second in military time. The Date minutes & seconds may have to be padded with leading 0. The hrs are in military time and have to be converted to 1-12 mode. There are several cases: 1. hrs = 0 => 12 am 2. hrs < 12 => hrs am 3. hrs = 12 => 12 pm 4. hrs > 12 => hrs – 12 pm The hrs for the alarm clock setting should be in non-military time (1-12 with am & pm) because that is more natural for users. This input is then compared with the clock hrs/minutes/seconds/am-pm to test for an alarm condition. The "civilian" hrs entered by the user to define the alarm should be compared with the converted hrs/min/sec/am-pm of the clock time. All four components – hrs, min, sec, am/pm have to match for an alarm to occur. The alarm test can occur any second, so it must be tested for every second. When an alarm condition occurs, the "music" or sound for the alarm should be started. The stop button on the clock can turn the sound file off when clicked. Of course, the sound file itself should be referenced using an HTML embed tag with an id (as discussed in Class 17). The time entered in the debug fields should be military time – since the purpose of this feature is to check if such time information (which is like what comes from the Date object) would be displayed correctly by the time display code. When the debug flag is set, the hrs/min/sec for the debug (military) time, should be used for the display, instead of the hrs/min/sec from the Date object. Refer to the AlarmClockTemplate.html for a basic structure for the program – the HTML part is largely omitted since it can be determined from the snapshot of the alarm clock and the requirements of the Javascript functions. 74
  • 75. Class 23 – 24 SQL (using MS Access as database) FINAL EXAM WILL INCLUDE Javascript AJAX SQL Basic HTML Solved examples will be posted for the exam just like for the midterm! Note: Access Database available in Fall08a.mdb (or Fall08a.zip) under Assignment 07 Purpose: This discussion extends our understanding of SQL including more advanced topics like nested queries, properly joining multiple tables, as well as useful syntactical features like sets (in operator) and retrieving based on patterns (like operator). MS Access is used as the database for convenience, even though it is primarily a desktop application, because its response is faster than the online MySQL, its interface is cleaner and sharper, and there is no network connection required (which again speeds it up). The SQL of both databases (Access and MySQL) are, with few exceptions, the same. Make a few tables Define a table Populate a table Execute a query [select] Introduce a few aggregate functions count function How many male students? (Query 1) avg What is average weight of students? (Query 2) sum What is average salary of students (Query 3) Distinct What are the different classes? (Query 4) in operator in ( 'NY', 'NJ' ) Who are the Female students (using in)? (Query 7) not in ( 'NY', 'NJ' ) Based on T2, what students have grades not equal to 2 or 3 (using Not in)? (Query 9) Simple nested query Using nested query who are the female students in T2? (Query 10) Introduce like operator and notation Link to usage Select name from T1 where like 'N*' What are the IT102 sections? (Query 5) What are the 001 sections? (Query 6) What are the IT sections? (Query 8) In MySQL SQL the % notation is used instead of * which works in MS Access SQL (http://infogoal.com/sql/sql-like.htm) Two tables – first without linking constraint, then with Analyze results (for *) when tables not joined properly (Query 11) Observe results when joined correctly (Query 12) Some more difficult queries 75
  • 76. What male students are taking IT 202 (Query 13) What courses have female students? (Query 14) What courses have only male students? (Query 15) Classes without Joe (Query 18, 18a) View the integrated data? (Query 19) Classes with Betty but without Joe (Query 16) like B-J in Venn diagrams T1 Extended T1 T1 name salary weight ssn gender Joe 100 100 1M Betty 150 150 2F Bert 200 200 3M Lois 40 10 4F ExtendedT1 name salary weight ssn gender Joe 100 100 1M Betty 150 150 2F Bert 200 200 3M Lois 40 10 4F Howie 40 20 5M T2 Extended T2 T2 classsection grade ssn IT102001 3 1 IT202002 3 1 CS115002 4 2 CS435001 4 3 IT102001 2 4 ExtendedT2 classsection grade ssn IT102001 3 1 IT202002 3 1 CS115002 4 2 CS435001 4 3 IT102001 2 4 IT202001 4 5 CS115002 3 1 IT102001 4 2 IT490 3 2 76
  • 77. 77
  • 78. Class 24 SQL Final Exam Prep: Next Tuesday – we go thru the sample Final Exam with solutions. Last Assignment – due by day of Final Exam Tuesday December 16th - 1130-2:00 – GITC 1400 Create an example along the lines of the Google search page – using AJAX. The test database should be large enough to demonstrate the ability to identify a few partial strings and display them [say in span elements] under the input text field. See partialStringSample.doc as sample for database. The AJAX triggered PHP generates span elements underneath a text input field. A click on a selected span element should move the contents to the form's input text field. – and thereby trigger a Form call to the Google search engine with the selected string as the data input. See the example search2.html under Assgt07 for a basic example [but without the AJAX component]. See if you can get this to act like the Google AJAX interface. Use IE [?] Link: http:// www.javascript-coder.com/javascript-form/javascript-form-submit.phtml <html><head><script type="text/Javascript"> function f(p) { document.getElementById(100).value=p document.getElementById(200).submit( ); } </script><style type="text/css">body { background: cyan ; } </style></head><body> <form action="http://www.google.com/search" id=200 > <input type="text" name="hl" value="en" /> <input type="text" name="q" id=100 /> </form> <select onchange="f(value)"> <option value='harp' > Harp </option> <option value='piano'> Piano</option> </select> <pre> - check google request to see how inputs variables h1 and q work - uses data acquired from the menu event here - the Form submission triggered by f - not submit button - the Google search program is identified in action - for last assignment you have to produce something like the AJAX partial string effect </pre> </body></html> Understand 1. Google interface [just as example to piggy back on its search engine] 2. Google input variables and default codes for language [again just to utilize] 3. menu onchange event and function/value call – should replace by AJAX dynamic effects 4. using f to pick up and deposit menu value selected 5. submit( ) function for menu object to submit Form 78
  • 79. Query solutions: Q1 SELECT count(*) FROM T1 WHERE gender='M'; Q2 SELECT avg(weight) FROM T1; Q3 SELECT sum(salary) FROM T1; Q4 SELECT DISTINCT classsection FROM T2; Q5 SELECT classsection FROM T2 WHERE classsection Like 'IT102*'; Q6 SELECT classsection FROM T2 WHERE classsection Like '*001'; Q7 SELECT * FROM T1 WHERE gender in ('F'); Q8 SELECT * FROM T2 WHERE classsection like 'IT*'; Q9 SELECT * FROM T2 WHERE grade Not In (2,3); Q10 SELECT * FROM T2 WHERE SSN in ( SELECT SSN from T1 where gender = 'F' ); Q11 SELECT * FROM T1, T2 WHERE name='Joe'; Q12 SELECT * FROM T1, T2 WHERE name='Joe' And T1.SSN=T2.SSN; Q13 SELECT * FROM T1, T2 WHERE gender='M' And T1.SSN=T2.SSN And classsection Like 'IT202*'; Q14 SELECT * FROM T1, T2 WHERE gender='F' And T1.SSN=T2.SSN; Q15 SELECT DISTINCT classsection FROM T1, T2 WHERE (T1.SSN = T2.SSN) and classsection not in ( SELECT classsection from T1, T2 where (T1.SSN = T2.SSN) and (Gender='F' ) ); Q16 SELECT * FROM T1, T2 WHERE (T1.SSN = T2.SSN) AND classsection in (Select classsection from T1, T2 where T1.SSN=T2.SSN and name='Betty' ) AND classsection Not in (Select classsection from T1, T2 where T1.SSN=T2.SSN and name='Joe' ); Q17 SELECT classsection FROM T1, T2 WHERE T1.SSN=T2.SSN and name='Betty'; Q18 SELECT * FROM T1, T2 WHERE (T1.SSN = T2.SSN) AND classsection Not in (Select classsection from T1, T2 where T1.SSN=T2.SSN and name='Joe' ); Q18A SELECT * FROM T2 WHERE classsection Not in (Select classsection from T1, T2 where T1.SSN=T2.SSN and name='Joe' ); Q19 SELECT * FROM T1, T2 WHERE T1.ssn=T2.ssn; 79
  • 80. Other queries: Which classes have some females? Which classes have no females? Which classes have only females? Which classes have some females and some males? MySQL AJAX PHP onkeyup Function like f that deposits selected value and submits Form from f ! Dynamic menu onchange event HTML Form that has google Search engine as action And approp Google var names 80
  • 81. All the courses with males with nested select * from Rosters, People where Rosters.SSN=People.SSN and Rosters.SSN in ( select Rosters.SSN from Rosters where Gender='M' ) Courses with females SELECT Course from Rosters, People where (Rosters.ssn = People.ssn) and (Gender='F' ) male only courses SELECT distinct Course from Rosters, People where (Rosters.ssn = People.ssn) and Course not in ( SELECT Course from Rosters, People where (Rosters.ssn = People.ssn) and (Gender='F' ) ) Course with Alice but not Jim SELECT * FROM People, Rosters WHERE ( Rosters.SSN=People.SSN ) AND Course in (Select Course from Rosters, People where Rosters.SSN=People.SSN and Name='Alice' ) AND Course NOT in (Select Course from Rosters, People where Rosters.SSN=People.SSN and Name='Jim' ); 81
  • 82. Saving HTML Files – Clarify Be aware that when saving a file that you have opened with a URL, browsers create folders for referenced images and also alter hyperlinks so that what you see is not necessarily the same as what was posted. The side-effects depend on the browser. To get the original HTML either download it directly or look at its source using the browser View option. Useful notation: the backward slash is an escape character that lets you include special characters like double quotes where it might be difficult to put them otherwise (like in quoted strings). For example, " lets you insert a quotation mark. For example, if you want to define <td style = "color: cyan" > as a string s you can use the notation: s = "<td style="color: cyan"" where the " puts a double-quote in the string in an acceptable way. http://userwww.sfsu.edu/~infoarts/technical/howto/sound/wilson.quicktimejavascript.html http://ajax-programming.suite101.com/article.cfm/the_5_elements_of_an_ajax_application http://www.degraeve.com/reference/simple-ajax-example.php 82

×