Professional Documents
Culture Documents
Web Designing
Web Designing
Web Designing
Internet and W3
By Pramudith Kandambi
Evaluation Criteria
Continues assessment
Assessment I Assessment II Micro Project
20%
Semester Examination
80%
References:
Internet & WWW, 3rd ed, 2005 - Deitel & Deitel PHP and MySQL Web Development - Luke Welling Laura Thomson
What is internet
The Internet is a network of computer networks.
It makes it possible for any computer connected to it to send and receive data from any other computer connected to it.
Pramudith_Kandambi Rajarata_University BIT_2009
What is Web
Using Internet transferring Fils, Data ect.
What is a Network?
A group of two or more devices, that are able to communicate with one another:
The telephone network: interconnection of telephones and switches Computer networks: interconnection of computers Between two and millions of devices interconnected
How it works
Computer Networks The computers in a network are connected via hardware and software Hardware Physically connects the computers together telephone lines, fiber-optic cables, routers and gateways, and the computers themselves Software Enables communication and exchange of by following a set of rules, called protocols
information,
Internet Protocols
A protocol is a standard set of rules that determines how computers communicate with each other across networks A protocol describes:
the format that a message must take the way in which computers must exchange a
message
Pramudith_Kandambi Rajarata_University BIT_2009
IP
TCP/IP- Transmission Control Protocol and Internet
Protocol .
FTP -
File Transfer Protocol to transfer files between computers information on the World Wide Web
HTTP - Hypertext Transfer Protocol to transmit NNTP - Network News Transfer Protocol to transmit
discussion forum messages
Pramudith_Kandambi Rajarata_University BIT_2009
IP Addresses
Every machine on the the Internet has a unique number assigned to it,
192.168.1.10
Class A B C D E Start address 0.0.0.0 128.0.0.0 192.0.0.0 224.0.0.0 240.0.0.0 Finish address 126.255.255.255 191.255.255.255 223.255.255.255 239.255.255.255 255.255.255.255
Domain Name
Domain Names are the unique name that identifies an entity whether that be an single individual or a company, on the Internet. Domain Names always have 2 or more parts seperated by the dots. The leftmost piece is the most specific part while the right part is the TLD or Top Level Domain.
Full Address www.bleepingcomputer.com bleepingcomputer.com www.google.net my.www.bleepingcomputer.com Hostname www bleepingcomputer.com www my.www Domain Name bleepingcomputer.com bleepingcomputer.com google.net bleepingcomputer.com TLD com com net com
Internet Architecture
Server/Client Interface
SERVERS
Hardware + Software
Software Protocols
CLIENTS
Hardware + Software
Web Browsers
Web Servers
This page is being viewed in the Internet Explorer Browser. Browsers allow computers to read Hyper Text Mark-up Language OR HTML.
After entering a URL address in the address box click Go or hit the RETURN key. In this example we have entered http://www.who.int for the WHO website
Hypertext links
The arrow buttons on the tool bar allow users to move Back and Forward to pages within the website.
The House icon on the tool bar will take you back to the browsers default Home Page.
This is the end of Module 1.1 There is a Work Book to accompany this part of the module. The workbook will take you through a live session covering the topics included in this demonstration with working examples. Updated 02 2008
HTML
Hyper Text Markup Language
By Pramudith Kandambi
What is HTML?
HTML is a language for describing web pages. HTML stands for Hyper Text Markup Language. HTML is not a programming language, it is a markup language. A markup language is a set of markup tags. HTML uses markup tags to describe web pages.
Pramudith_Kandambi Rajarata_University BIT_2009
HTML Tags
HTML markup tags are usually called HTML tags Keywords surrounded by angle brackets like <html> HTML tags normally come in pairs like <b> and </b>
HTML Headings
HTML headings are defined with the <h1> to <h6> tags. Example <h1> This is a heading</h1> <h2>This is a heading</h2> <h3>This is a heading</h3>
Pramudith_Kandambi Rajarata_University BIT_2009
HTML Paragraphs
HTML paragraphs are defined with the <p> tag. Example <p> This is a paragraph</p> <p>This is another paragraph</p>
HTML Links
HTML links are defined with the <a> tag. Example <a href="http://www.rjt.ac.lk">This is a link</a>
HTML Images
HTML images are defined with the <img> tag. Example <img src="w3schools.jpg" width="104" height="142" />
HTML Attributes
Attributes provide additional information about HTML elements. HTML elements can have attributes Attributes provide additional information about the element Attributes are always specified in the start tag Attributes come in name/value pairs like: name="value"
Pramudith_Kandambi Rajarata_University BIT_2009
An HTML Link
Link syntax: <a href="url">Link text</a>
Note: The element content doesn't have to be text. You can link from an image or any other HTML element.
The href Attribute The href attribute defines the link "address". This <a> element defines a link to RJT site <a href="http://www.rjt.ac.lk/">Visit Rajarata!</a> The code above will display like this in a browser:
<!--> <!DOCTYPE> <a> <abbr> <acronym> <address> <applet> <area> <b> <base> <basefont> <bdo> <big> <blockquote> <body> <br> <button> <caption> <center> <cite> <code> <col> <colgroup> <dd>
<dd> <del> <dfn> <dir> <div> <dl> <dt> <em> <fieldset> <font> <form> <frame> <frameset> <head> <h1> - <h6> <hr> <html> <i> <iframe> <img> <input> <ins> <kbd> <label>
<legend> <li> <link> <map> <menu> <meta> <noframes> <noscript> <object> <ol> <optgroup> <option> <p> <param> <pre> <q> <s> <samp> <script> <select> <small> <span> <strike> <strong>
<style> <sub> <sup> <table> <tbody> <td> <textarea> <tfoot> <th> <thead> <title> <tr> <tt> <u> <ul> <var>
HTML Part 2
Pramudith_Kandambi@MIT_IMdepartment
Objectives
In this lesson, you will learn:
To be able to create tables with rows and columns of data. To be able to control table formatting. To be able to create and use forms. To be able to create and use image maps to aid in Webpage navigation. To be able to use the frameset element to display multiple Web pages in a single browser window.
Introduction
Tables
Present information
Forms
Collect information from visitor
Frames
Display multiple documents in the browser
Attribute summary
Describes the tables contents
Attribute caption
Describes the tables content and helps text-based browsers interpret table data
Foot section (defined with a <tfoot> element) Table body (defined with a <tbody> element) Data cells (defined with <td> element)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- table1.html --> -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A simple XHTML table</title> </head> <body>
table.html <table border = "1" width = "40%" (1 of 3) summary = "This table provides information about
<!-- the <table> tag opens a table --> the price of fruit"> <!-- the <caption> tag summarizes the table's -->
<!-- contents (this helps the visually impaired) --> <caption><strong>Price of Fruit</strong></caption>
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
<! -- th e <t hea d> i s t he f irst se ctio n o f a tabl e - -> <! -- it for mat s th e t able hea der are a <t hea d> <t r> < th>P ric e</t h> </ tr > </ the ad > <!-- <tr > i nser ts a ta ble row --> < th>F rui t</t h> <!-- ins ert a h ead ing cell -- > - ->
<! -- th e <t foo t> i s t he l ast sec tion of a t able -- > <! -- it for mat s th e t able foo ter <t foo t> <t r> < th>T ota l</t h> < th>$ 3.7 5</t h> </ tr > </ tfo ot > <! -- al l ta ble con ten t is enc los ed <! -- wi thin th e <t bod y> <t bod y> <t r> < td>A ppl e</t d> <!-- ins ert a d ata cel l -- > < td>$ 0.2 5</t d> </ tr > --> --> -- >
table.html (2 of 3)
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 </body>
9
<tr> <td>Orange</td> <td>$0.50</td> </tr> <tr> <td>Banana</td> <td>$1.00</td> </tr> <tr> <td>Pineapple</td> <td>$2.00</td> </tr> </tbody> </table>
table.html (3 of 3)
69 </html>
10
Element <col>
Attribute align
Determines the alignment of text in the column
Attribute span
Determines how many columns the col element formats rowspan
and colspan
valign Aligns data vertically One of the four values: top, middle, bottom, baseline
11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- table2.html -->
<!-- Intermediate table design --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Internet and WWW How to Program - Tables</title> </head> <body> <h1>Table Example Page</h1> <table border = "1">
table2.html (1 of 4)
<caption>Here is a more complex sample table.</caption> <!-- <colgroup> and <col> tags are used to --> <!-- format entire columns <colgroup> -->
12
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
<!-- span attribute determines how many columns --> <!-- the <col> tag affects <col align = "right" span = "1" /> </colgroup> <thead> <!-- rowspans and colspans merge the specified <!-- number of cells vertically or horizontally <tr> <!-- merge two rows --> <th rowspan = "2"> <img src = "camel.gif" width = "205" height = "167" alt = "Picture of a camel" /> </th> <!-- merge four columns --> <th colspan = "4" valign = "top"> <h1>Camelid comparison</h1><br /> <p>Approximate as of 9/2002</p> </th> </tr> --> --> -->
table2.html (2 of 4)
13
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
<t r vali gn = "b ott om"> < th># of H um ps< /th> < th>I n d i g e n o u s r e g i o n </ th> < th>S pi t s ? </ th> < th>P r o d u c e s W o o l ?< /t h> </ tr > < / t h e ad > < t b o d y> <t r> < th>C a m e l s ( b a c t r i a n ) </ th> < td>2 </t d > < td>A f r i c a / A s i a </td > < td>Y es< /t d> < td>Y es< /t d> </ tr > <t r> < th>L la m a s </ th> < td>1 </t d > < td>A nd e s Mo unt ains < / t d > < td>Y es< /t d> < td>Y es< /t d>
table2.html (3 of 4)
14
73 74 75 76 77 78 79 80 </body> </html>
15
method = get
Appends form data directly to the end of the URL
Attribute action
Specifies the URL of a script on the Web server
input
Specifies data to provide to the script that processes the form
16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- form.html -->
<!-- Form Design Example 1 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Internet and WWW How to Program - Forms</title> </head> <body> <h1>Feedback Form</h1> <p>Please fill out this form to help us improve our site.</p> <!-- this tag starts the form, gives the <!-- location of form scripts --> -->
form.html (1 of 3)
<!-- method of sending information and the --> <form method = "post" action = "/cgi-bin/formmail">
17
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
<p> <!-- hidden inputs contain non-visual --> <!-- information value = "deitel@deitel.com" /> <input type = "hidden" name = "subject" value = "Feedback Form" /> <input type = "hidden" name = "redirect" value = "main.html" /> </p> <!-- <input type = "text"> inserts a text box --> <p><label>Name: <input name = "name" type = "text" size = "25" maxlength = "30" /> </label></p> <p> --> <input type = "hidden" name = "recipient"
<!-- input types "submit" and "reset" insert <!-- buttons for submitting and clearing the <!-- form's contents <input type = "submit" value = "Submit Your Entries" /> <input type = "reset" value = "Clear Your Entries" /> </p>
form.html (2 of 3)
--> --> -->
18
19
Attribute cols
Specifies the number columns
Input password
Inserts a password box with the specified size
Element <checkbox>
Enable users to select from a set of options
Element <select>
Provides a drop-down list of items
Element <option>
Adds items to the drop-down list Attribute selected
Specifies which item initially is displayed as the selected item
20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- form2.html -->
<!-- Form Design Example 2 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Internet and WWW How to Program - Forms</title> </head> <body> <h1>Feedback Form</h1> <p>Please fill out this form to help us improve our site.</p> <form method = "post" action = "/cgi-bin/formmail">
form2.html (1 of 4)
21
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
<p> <input type = "hidden" name = "recipient" value = "deitel@deitel.com" /> <input type = "hidden" name = "subject" value = "Feedback Form" /> <input type = "hidden" name = "redirect" value = "main.html" /> </p> <p><label>Name: <input name = "name" type = "text" size = "25" /> </label></p> <!-- <textarea> creates a multiline textbox --> <p><label>Comments:<br />
form2.html (2 of 4)
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
<!-- <input type = "password"> inserts a <!-- textbox whose display is masked with <!-- asterisk characters <p><label>E-mail Address: <input name = "email" type = "password" size = "25" /> </label></p> <p> <strong>Things you liked:</strong><br /> <label>Site design
<input name = "thingsliked" type = "checkbox" value = "Design" /></label> <label>Links <input name = "thingsliked" type = "checkbox" value = "Links" /></label> <label>Ease of use value = "Ease" /></label> <label>Images <input name = "thingsliked" type = "checkbox" value = "Images" /></label>
form2.html (3 of 4)
23
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 </body> 84 </html>
24
<label>Source code <input name = "thingsliked" type = "checkbox" value = "Code" /></label> </p> <p> <input type = "submit" value = "Submit Your Entries" /> <input type = "reset" value = "Clear Your Entries" /> </p> </form>
form2.html (4 of 4)
25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- form3.html -->
<!-- Form Design Example 3 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Internet and WWW How to Program - Forms</title> </head> <body> <h1>Feedback Form</h1> <p>Please fill out this form to help us improve our site.</p>
<form method = "post" action = "/cgi-bin/formmail"> <p> <input type = "hidden" name = "recipient" value = "deitel@deitel.com" /> <input type = "hidden" name = "subject"
form3.html (1 of 6)
26
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 <p> </p>
value = "Feedback Form" /> <input type = "hidden" name = "redirect" value = "main.html" />
<p><label>Name: <input name = "name" type = "text" size = "25" /> </label></p> <p><label>Comments:<br /> <textarea name = "comments" rows = "4" cols = "36"></textarea> </label></p> <p><label>E-mail Address: <input name = "email" type = "password" size = "25" /></label></p>
form3.html (2 of 6)
<strong>Things you liked:</strong><br /> <label>Site design <input name = "thingsliked" type = "checkbox" value = "Design" /></label>
27
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
<l ab el>L ink s < inpu t n ame = " thin gsli ked " ty pe = "c heck box " va lue = " Lin ks" /></ lab el> <l ab el>E ase of use < inpu t n ame = " thin gsli ked " ty pe = "c heck box " va lue = " Eas e" / ></l abe l> <l ab el>I mag es < inpu t n ame = " thin gsli ked " ty pe = "c heck box " va lue = " Ima ges" />< /la bel> <l ab el>S our ce c ode < inpu t n ame = " thin gsli ked " ty pe = "c heck box " va lue = " Cod e" / ></l abe l> </p> <! -- <i nput ty pe = "r adio " /> cr eate s a
<! -- bu tton . T he d iff eren ce b etw een rad io b utto ns --> <! -- an d ch eck boxe s i s th at o nly one ra dio butt on --> <! -- in a g rou p ca n b e se lect ed. <p > <s tr ong>How did yo u ge t to ou r si te? :</s tron g>< br / >
28
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
<label>Search engine <input name = "howtosite" type = "radio" value = "search engine" checked = "checked" /> </label> <label>Links from another site <input name = "howtosite" type = "radio" value = "link" /></label> <label>Deitel.com Web site <input name = "howtosite" type = "radio" value = "deitel.com" /></label> <label>Reference in a book <input name = "howtosite" type = "radio" value = "book" /></label> <label>Other value = "other" /></label> </p>
form3.html (4 of 6)
29
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
<p > <l ab el>R ate our si te: <!- - t he < sel ect> tag pr esen ts a dr op-d own --> <!- - l ist wit h ch oice s i ndic ate d by the <!- - < opti on> tag s <sel ect nam e = "ra ting "> < opt ion sel ecte d = "se lect ed" >Ama zing </o ptio n> < opt ion> 10< /opt ion> < opt ion> 9</ opti on> < opt ion> 8</ opti on> < opt ion> 7</ opti on> < opt ion> 6</ opti on> < opt ion> 5</ opti on> < opt ion> 4</ opti on> < opt ion> 3</ opti on> < opt ion> 2</ opti on> < opt ion> 1</ opti on> < opt ion> Awf ul</ opti on> </se lec t> </l abel > </p > --> -->
form3.html (5 of 6)
30
<p> <input <input </p> </form> </body> type type = = "submit" "reset" value /> = "Clear Your Entries" /> value = "Submit Your Entries"
131 </html>
form3.html (6 of 6)
31
Internal Linking
Enables the user to jump between locations in the same document
32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- links.html --> <!-- Internal Linking -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Internet and WWW How to Program - List</title> </head> <body> <!-- id attribute creates an internal hyperlink destination --> <h1 id = "features">The Best Features of the Internet</h1>
33
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
<ul> <li>New games</li> <li>New applications <ul> <li>For Business</li> <li>For Pleasure</li> </ul> </li> <li>Around the clock news</li> <li>Search Engines</li> <li>Shopping</li> <li>Programming <ul> <li>XHTML</li> <li>Java</li> <li>Dynamic HTML</li> <li>Scripts</li> <li>New languages</li> </ul> </li> </ul> </li> <li>Links</li>
links.html (2 of 3)
34
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
<li>Keeping in touch with old friends</li> <li>It is the technology of the future!</li> </ul> <!-- id attribute creates an internal hyperlink destination --> <h1 id = "bugs">My 3 Favorite Bugs</h1> <p> <!-- internal hyperlink to features --> <a href = "#features">Go to <em>Favorite Features</em> </a></p> <ol> <li>Fire Fly</li> <li>Gal Ant</li> <li>Roman Tic</li> </ol> </body>
71 </html>
links.html (3 of 3)
35
36
Element area
Defines hotspot Attribute shape and coords
Specify the hotspots shape and coordinates
37
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- picture.html -->
<!-- Creating and Using Image Maps --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Internet and WWW How to Program - Image Map </title> </head> <body> <p> <!-- the <map> tag defines an image map --> <map id = "picture"> <!-- shape = "rect" indicates a rectangular <!-- and lower-right corners --> -->
picture.html (1 of 3)
38
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
<area href = "form.html" shape = "rect" coords = "2,123,54,143" alt = "Go to the feedback form" /> <area href = "contact.html" shape = "rect" coords = "126,122,198,143" alt = "Go to the contact page" /> <area href = "main.html" shape = "rect" coords = "3,7,61,25" alt = "Go to the homepage" /> <area href = "links.html" shape = "rect" coords = "168,5,197,25" alt = "Go to the links page" /> <!-- value "poly" creates a hotspot in the shape --> <!-- of a polygon, defined by coords <area shape = "poly" alt = "E-mail the Deitels" coords = "162,25,154,39,158,54,169,51,183,39,161,26" href = "mailto:deitel@deitel.com" /> <!-- shape = "circle" indicates a circular <area href = "mailto:deitel@deitel.com" shape = "circle" coords = "100,36,33" alt = "E-mail the Deitels" /> </map> -->
picture.html --> (2 of 3)
39
50 51 52 53 54 55 56
<img src = =
src
=...
usemap map
= is
"#id"> used = =
that =
the
--> -->
specified
image
with "200"
image "144"
"deitel.gif" logo"
width usemap
alt
"Deitel
"#picture"
picture.html (3 of 3)
40
meta Elements
Specify information about a document
Attribute name
Identifies the type of meta element keywords ( name = keywords )
Provides search engines with a list of words that describe a page
Attribute content
Provides the information search engine use to catalog pages
41
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- main.html --> <!-- <meta> tag -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Internet and WWW How to Program - Welcome</title> <!-- <meta> tags provide search engines with --> <!-- information used to catalog a site --> <meta name = "keywords" content = "Web page, design, XHTML, tutorial, personal, help, index, form, contact, feedback, list, links, frame, deitel" />
main.html <meta name = "description" content = "This Web site will (1 of 2) help you learn the basics of XHTML and Web page design
through the use of interactive examples and instruction." /> </head>
42
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
<body> <h1>Welcome <p>We of better data XMLs will on have to Our Web Site!</h1> site to teach to about the wonders is of you complex Soon of
designed than
this
<strong><em>XHTML</em></strong>. equipped the strict know <em>HTML</em> to of ensure the Internet. syntax many <em>XHTML</em> great
advantage
about
main.html (2 of 2)
43
frameset Element
Allow browser display more than one document simultaneously
Element frameset
Attribute cols
Specifies the framesets column layout
Attribute rows
Specifies the number of rows and the size of each row
Element frame
Specifies the documents that will be loaded Attribute src
Specifies URL of the page to display
44
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> <!-- index.html --> <!-- XHTML Frames I -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Internet and WWW How to Program - Main</title> <meta name = "keywords" content = "Webpage, design, XHTML, tutorial, personal, help, index, form, contact, feedback, list, links, frame, deitel" /> <meta name = "description" content = "This Web site will help you learn the basics of XHTML and Web page design through the use of interactive examples and instruction." /> </head> <!-- the <frameset> tag sets the frame dimensions <frameset cols = "110,*"> -->
index.html (1 of 2)
45
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
<!-- frame elements specify which pages --> <!-- are loaded into a given frame --> <frame name = "leftframe" src = "nav.html" /> <frame name = "main" src = "main.html" /> <noframes> <body> <p>This page uses frames, but your browser does not support them.</p> <p>Please, <a href = "nav.html">follow this link to browse our site without frames</a>.</p> </body> </noframes> </frameset>
41 </html>
index.html (2 of 2)
46
47
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- nav.html -->
<!-- Using images as link anchors --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Internet and WWW How to Program - Navigation Bar </title> </head> <body> <p> <a href = "links.html" target = "main"> <img src = "buttons/links.jpg" width = "65" height = "50" alt = "Links Page" /> </a><br /> <a href = "list.html" target = "main"> <img src = "buttons/list.jpg" width = "65" height = "50" alt = "List Example Page" />
nav.html (1 of 2)
48
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
</a><br /> <a href = "contact.html" target = "main"> <img src = "buttons/contact.jpg" width = "65" height = "50" alt = "Contact Page" /> </a><br /> <a href = "header.html" target = "main"> <img src = "buttons/header.jpg" width = "65" height = "50" alt = "Header Page" /> </a><br /> <a href = "table1.html" target = "main"> <img src = "buttons/table.jpg" width = "65" height = "50" alt = "Table Page" /> </a><br /> <a href = "form.html" target = "main"> <img src = "buttons/form.jpg" width = "65" height = "50" alt = "Feedback Form" /> </a><br /> </p> </body>
nav.html (2 of 2)
50 </html>
49
Nested framesets
framesets within framesets
50
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> <!-- index2.html --> <!-- XHTML Frames II -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Internet and WWW How to Program - Main</title> <meta name = "keywords" content = "Webpage, design, XHTML, tutorial, personal, help, index, form, contact, feedback, list, links, frame, deitel" /> <meta name = "description" content = "This Web site will help you learn the basics of XHTML and Web page design through the use of interactive examples and instruction." /> </head> <frameset cols = "110,*"> <frame name = "leftframe" src = "nav.html" />
index2.html (1 of 2)
51
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
<!-- nested framesets are used to change the --> <!-- formatting and layout of the frameset <frameset rows = "175,*"> <frame name = "picture" src = "picture.html" /> <frame name = "main" src = "main.html" /> </frameset> <noframes> <body> <p>This page uses frames, but your browser does not support them.</p> <p>Please, <a href = "nav.html">follow this link to browse our site without frames</a>.</p> </body> </noframes> </frameset> -->
44 </html>
index2.html (2 of 2)
52
53
Web Resources
www.vbxml.com/xhtml/articles/xhtml_tables www.webreference.com/xml/reference/xhtml.html
54
What is HTML ?
HTML stands for Hyper Text Markup Language HTML is not a programming language, it is a markup language A markup language is a set of markup tags HTML uses markup tags to describe web pages
Pramudith_Kandambi@MIT_IMdepartment
HTML page
HTML
<html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>
Pramudith_Kandambi@MIT_IMdepartment
HTML Headings
Pramudith_Kandambi@MIT_IMdepartment
HTML Links
Pramudith_Kandambi@MIT_IMdepartment
HTML Links
<> attribute
Pramudith_Kandambi@MIT_IMdepartment
HTML image <br> or <br /> <hr /> <table> defines an HTML table. <table border="1"> Tag Description <b> Defines bold text <big> Defines big text <em> Defines emphasized text <i> Defines italic text <small> Defines small text <strong> Defines strong text <sub> Defines subscripted text Defines superscripted text <sup> <ins> Defines inserted text <del> Defines deleted text Pramudith_Kandambi@MIT_IMdepartment
HTML
Pramudith_Kandambi@MIT_IMdepartment
HTML
<table > <tr> <td>A</td> <td>B</td> </tr> <tr> <td>C</td> <td>D</td> </tr> </table>
Pramudith_Kandambi@MIT_IMdepartment
Outline
Introduction Inline Styles Embedded Style Sheets Conflicting Styles Linking External Style Sheets W3C CSS Validation Service Positioning Elements Backgrounds Element Dimensions Text Flow and the Box Model User Style Sheets Web Resources
To control the appearance of a Web site by creating style sheets. To use a style sheet to give all the pages of a Web site the same look and feel. To use the class attribute to apply styles. To specify the precise font, size, color and other properties of displayed text. To specify element backgrounds and colors. To understand the box model and how to control the margins, borders and padding. To use style sheets to separate presentation from content.
2
Grouping
h1,h2,h3,h4,h5,h6 { color: green }
p {text-align: right} p.right {text-align: right} p.center {text-align: center} Ex: HTML <p class="center"> This paragraph will be center-aligned. </p> <p class="right"> This paragraph will be right-aligned. </p>
</style> </head>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- inline.html --> <!-- Using inline styles -->
Outline
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Inline Styles</title> </head> <body> <p>This text does not have any style applied to it.</p> <!-- The style attribute allows you to declare --> <!-- inline styles. Separate multiple styles <!-- with a semicolon. <p style = "font-size: 20pt">This text has the <em>font-size</em> style applied to it, making it 20pt. </p> --> -->
24 25 26 27 28 29
<p style = "font-size: 20pt; color: #0000ff"> This text has the <em>font-size</em> and <em>color</em> styles applied to it, making it 20pt. and blue.</p> </body>
Outline
30 </html>
10
11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- declared.html -->
Outline
<!-- Declaring a style sheet in the header section. --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Style Sheets</title> <!-- this begins the style sheet section --> <style type = "text/css"> em { background-color: #8000ff; color: white } h1 p { font-family: arial, sans-serif } { font-size: 14pt }
12
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 <h1>Clients</h1> <p class = "special"> The company's clients include many <em>Fortune 1000 companies</em>, government agencies, branches of the military and business organizations. Through its publishing partnership with Prentice Hall, Deitel & Associates, Inc. publishes leading-edge programming textbooks, professional books, interactive CD-ROM-based multimedia Cyber Classrooms, satellite courses and World Wide Web courses.</p> <p>Deitel & Associates, Inc. is an internationally recognized corporate training and publishing organization specializing in programming languages, Internet/World Wide Web technology and object technology education. Deitel & Associates, Inc. is a member of the World Wide Web Consortium. The company provides courses on Java, C++, Visual Basic, C, Internet and World Wide Web programming, and Object Technology.</p> <!-- this class attribute applies the .special style --> <h1 class = "special">Deitel & Associates, Inc.</h1> <body>
Outline
13
51
</body>
52 </html>
Outline
14
Inheritance
15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- advanced.html -->
Outline
<!-- More advanced style sheets --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>More Styles</title> <style type = "text/css"> a.nodec a:hover { text-decoration: none } { text-decoration: underline; color: red; background-color: #ccffcc } li em { color: red; font-weight: bold } ul { margin-left: 75px }
16
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 <body>
ul ul
Outline
</style> </head>
<h1>Shopping list for <em>Monday</em>:</h1> <ul> <li>Milk</li> <li>Bread <ul> <li>White bread</li> <li>Rye bread</li> <li>Whole wheat bread</li> </ul> </li> <li>Rice</li> <li>Potatoes</li> <li>Pizza <em>with mushrooms</em></li> </ul>
17
49 50 51 52
Outline
53 </html>
18
19
1 2 3 4 5 6 7 8 9
/* styles.css
*/
Outline
a:hover { text-decoration: underline; color: red; background-color: #ccffcc } { color: red; font-weight: bold; background-color: #ffffff } { margin-left: 2cm } { text-decoration: underline; margin-left: .5cm }
10 li em 11 12 13 14 ul 15 16 ul ul 17
20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- external.html --> -->
Outline
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Linking External Style Sheets</title> <link rel = "stylesheet" type = "text/css" href = "styles.css" /> </head> <body> <h1>Shopping list for <em>Monday</em>:</h1> <ul> <li>Milk</li> <li>Bread <ul> <li>White bread</li> <li>Rye bread</li> <li>Whole wheat bread</li> </ul>
21
26 27 28 29 30 31 32 33 34 35 36 <p>
Outline
37 </html>
22
Validates external CSS documents Ensures that style sheets are syntactically correct
23
24
25
Absolute positioning
z-index attribute
Relative positioning
26
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- positioning.html -->
Outline
<!-- Absolute positioning of elements --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Absolute Positioning</title> </head> <body> <p><img src = "i.gif" style = "position: absolute; top: 0px; left: 0px; z-index: 1" alt = "First positioned image" /></p> <p style = "position: absolute; top: 50px; left: 50px; z-index: 3; font-size: 20pt">Positioned Text</p> <p><img src = "circle.gif" style = "position: absolute; top: 25px; left: 100px; z-index: 2" alt = "Second positioned image" /></p> </body>
25 </html>
27
28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- positioning2.html --> -->
Outline
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Relative Positioning</title> <style type = "text/css"> p { font-size: 1.3em; font-family: verdana, arial, sans-serif } span { color: red; font-size: .6em; height: 1em } .super { position: relative; top: -1ex } .sub { position: relative; bottom: -1ex }
29
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 <body>
.shiftleft
Outline
<p>The text at the end of this sentence <span class = "super">is in superscript</span>.</p> <p>The text at the end of this sentence <span class = "sub">is in subscript</span>.</p> <p>The text at the end of this sentence <span class = "shiftleft">is shifted left</span>.</p> <p>The text at the end of this sentence <span class = "shiftright">is shifted right</span>.</p> </body>
51 </html>
30
31
background-image Specifies the image URL background-position Places the image on the page background-repeat Controls the tiling of the background image background-attachment fixed scroll font-weight Specify the boldness of text
Dept. of Industrial Management-2008
32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- background.html -->
Outline
<!-- Adding background images and indentation --> <html xmlns = "http://www.w3 .org/1999/xhtml"> <head> <title>Background Images</title> <style type = "text/css"> body { background-image: url(logo.gif); background-position: bottom right; background-repeat: no-repeat; background-attachment: fixed; } p { font-size: 18pt; color: #aa5588; text-indent: 1em; font-family: arial, sans-serif; } .dark { font-weight: bold; }
33
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
</style> </head> <body> <p> This example uses the background-image, background-position and background-attachment styles to place the <span class = "dark">Deitel & Associates, Inc.</span> logo in the bottom, right corner of the page. Notice how the logo stays in the proper position when you resize the browser window. </p> </body>
Outline
42 </html>
34
35
CSS rules can specify the actual dimensions of each page element
36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- width.html --> -->
Outline
<!-- Setting box dimensions and aligning text <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Box Dimensions</title> <style type = "text/css"> div { background-color: #ffccff; margin-bottom: .5em } </style> </head> <body> <div style = "width: 20%">Here is some text that goes in a box which is set to stretch across twenty percent of the width of the screen.</div>
37
26 27 28 29 30 31 32 33 34 35 36 37 38 </body> 39 </html> <div style = "width: 20%; height: 30%; overflow: scroll"> This box is only twenty percent of the width and thirty percent of the height. What do we do if it overflows? Set the overflow property to scroll!</div> <div style = "width: 80%; text-align: center"> Here is some CENTERED text that goes in a box which is set to stretch across eighty percent of the width of the screen.</div>
Outline
38
Floating
Box model
Margins Padding Border
39
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- floating.html -->
Outline
<!-- Floating elements and element boxes --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Flowing Text Around Floating Elements</title> <style type = "text/css"> div { background-color: #ffccff; margin-bottom: .5em; font-size: 1.5em; width: 50% } p { text-align: justify }
</style> </head>
40
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
<body> <div style = "text-align: center"> Deitel & Associates, Inc.</div> <div style = "float: right; margin: .5em; text-align: right"> Corporate Training and Publishing</div> <p>Deitel & Associates, Inc. is an internationally recognized corporate training and publishing organization specializing in programming languages, Internet/World Wide Web technology and object technology education. The company provides courses on Java, C++, Visual Basic, C, Internet and World Wide Web programming, and Object Technology.</p> <div style = "float: right; padding: .5em; text-align: right"> Leading-Edge Programming Textbooks</div> <p>The company's clients include many Fortune 1000 companies, government agencies, branches of the military and business organizations.</p>
Outline
41
49 50 51 52 53 54 55 56
<p style = "clear: right">Through its publishing partnership with Prentice Hall, Deitel & Associates, Inc. publishes leading-edge programming textbooks, professional books, interactive CD-ROM-based multimedia Cyber Classrooms, satellite courses and World Wide Web courses.</p> </body>
Outline
57 </html>
42
Margin
Content
Border Padding
43
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- borders.html -->
Outline
<!-- Setting borders of an element --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Borders</title> <style type = "text/css"> body div { background-color: #ccffcc } { text-align: center; margin-bottom: 1em; padding: .5em } .thick { border-width: thick }
44
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
Outline
.outset { border-style: outset } .red .blue </style> </head> <body> <div class = "thick groove">This text has a border</div> <div class = "medium groove">This text has a border</div> <div class = "thin groove">This text has a border</div> <p class = "thin red inset">A thin red line...</p> <p class = "medium blue outset"> And a thicker blue line</p> </body> { border-color: red } { border-color: blue }
50 </html>
45
46
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- borders2.html --> -->
Outline
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Borders</title> <style type = "text/css"> body div { background-color: #ccffcc } { text-align: center; margin-bottom: .3em; width: 50%; position: relative; left: 25%; padding: .3em } </style> </head> <body>
47
26 27 28 29 30 31 32 33 34 </body> 35 </html> <div style = "border-style: solid">Solid border</div> <div style = "border-style: double">Double border</div> <div style = "border-style: groove">Groove border</div> <div style = "border-style: ridge">Ridge border</div> <div style = "border-style: inset">Inset border</div> <div style = "border-style: outset">Outset border</div>
Outline
48
49
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- user_absolute.html <!-- User styles --> -->
Outline
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>User Styles</title> <style type = "text/css"> .note { font-size: 9pt } </style> </head> <body> <p>Thanks for visiting my Web site. I hope you enjoy it. </p><p class = "note">Please Note: This site will be moving soon. Please check periodically for updates.</p>
50
24 25 </body> 26 </html>
Outline
51
1 2 3 4 5 6
/* Fig. 6.17: userstyles.css */ /* A user stylesheet body { font-size: 20pt; color: yellow; background-color: #000080 } */
Outline
52
53
54
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- user_relative.html <!-- User styles --> -->
Outline
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>User Styles</title> <style type = "text/css"> .note { font-size: .75em } </style> </head> <body> <p>Thanks for visiting my Web site. I hope you enjoy it. </p><p class = "note">Please Note: This site will be moving soon. Please check periodically for updates.</p>
55
24 25 </body> 26 </html>
Outline
56
57
58
Introduction to Scripting
By Pramudith Kandambi
Outline
Introduction Simple Program: Printing a Line of Text in a Web Page Obtaining User Input with prompt Dialogs Dynamic Welcome Page Adding Integers Memory Concepts Arithmetic Decision Making: Equality and Relational Operators Web Resources
2
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license
JavaScript's official name is ECMAScript. ECMAScript is developed and maintained by the ECMA organization. ECMA-262 is the official JavaScript standard. The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all Netscape and Microsoft browsers since 1996. The development of the standard is still in progress.
NO! Java and JavaScript are two completely different languages in both concept and design! Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.
6
JavaScript can be used to validate data A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies
A JavaScript can be used to store and retrieve information on the visitor's computer
Escape character ( \ )
Indicates special character is used in the string
alert method
Dialog box
The HTML <script> tag is used to insert a JavaScript into an HTML page.
<html> <head> <script type="text/javascript"> function message() { alert(Hello BIT !"); } </script> </head> <body onload="message()"> </body> </html>
Browsers that do not support JavaScript, will display JavaScript as page content.
To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript.
<html> <body> <script type="text/javascript"> <!-document.write("Hello World!"); //--> </script> </body> </html>
JavaScripts in the body section will be executed WHILE the page loads. JavaScripts in the head section will be executed when CALLED. Where to Put the JavaScript
JavaScript's in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.
If you want to run the same JavaScript on several pages, without having to write the same script on every page, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension. Note: The external script cannot contain the <script> tag!
Example <html>
Comments can be added to explain the JavaScript, or to make the code more readable. Single line comments start with //. Multi line comments
start with /* end with */.
Declaring (Creating) JavaScript Variables You can declare JavaScript variables with the var statement:
var x; var carname;
However, you can also assign values to the variables when you declare them:
var x=5; var carname=Mazda3;
As with algebra, you can do arithmetic operations with JavaScript variables: y=x-5; z=y+5;
Escape Description sequence \n Newline. Position the screen cursor at the beginning of the next line.
\t \r
\\ \"
Horizontal tab. Move the screen cursor to the next tab stop. Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. Backslash. Used to represent a backslash character in a string. Double quote. Used to represent a double quote character in a string contained in double quotes. For example,
window.alert( "\"in quotes\"" ); displays "in quotes" in an alert dialog.
\'
Single quote. Used to represent a single quote character in a string. For example,
window.alert( '\'in quotes\'' ); displays 'in quotes' in an alert dialog.
A script can adapt the content based on input from the user or other variables
19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- welcome5.html --> <!-- Using Prompt Boxes -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using Prompt and Alert Boxes</title> <script type = "text/javascript"> <!-var name; // string entered by the user // read the name from the prompt box as a string name = window.prompt( "Please enter your name", "GalAnt" ); document.writeln( "<h1>Hello, " + name + ", welcome to JavaScript programming!</h1>" ); // --> </script>
20
23 24 25 26 27 28 29 <body> <p>Click </body> </html> Refresh (or Reload) to run this script again.</p> </head>
21
When the user clicks OK, the value typed by the user is returned to the program as a string.
This is the default value that appears when the dialog opens.
This is the text field in which the user types the value.
22
Prompt user for two integers and calculate the sum NaN (not a number)
parseInt Converts its string argument to an integer
23
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Addition.html --> <!-- Addition Program -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>An Addition Program</title> <script type = "text/javascript"> <!-var firstNumber, secondNumber, number1, number2, sum; // first string entered by user // second string entered by user // first number to add // second number to add // sum of number1 and number2
// read in first number from user as a string firstNumber = window.prompt( "Enter first integer", "0" );
24
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
// read in second number from user as a string secondNumber = window.prompt( "Enter second integer", "0" ); // convert numbers from strings to integers number1 = parseInt( firstNumber ); number2 = parseInt( secondNumber ); // add the numbers sum = number1 + number2; // display the results document.writeln( "<h1>The sum is " + sum + "</h1>" ); // --> </script> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body>
44 </html>
25
26
Variable names correspond to locations in the computers memory Every variable has a name, a type, and a value Read value from a memory location
nondestructive
27
number1
45
28
number1 number2
45 72
Memory locations after values for variables number1 and number2 have been input.
29
45 72 117
30
31
Operator + * / % ++ --
Description Addition Subtraction Multiplication Division Modulus (division remainder) Increment Decrement
Order of evaluation (precedence) Evaluated second. If there are several such operations, xthey are evaluated from left to -y right. Evaluated last. If there are several such operations, they are evaluated from left to right. Precedence of arithmetic operators.
33
(Leftmost addition)
(Last addition)
(Last operationplace
34
35
Same As
Result x=5
Operator == ===
Description is equal to is exactly equal to (value and type) is not equal is greater than is less than is greater than or equal to is less than or equal to
Example x==8 is false x===5 is true x==="5" is false x!=8 is true x>8 is false x<8 is true x>=8 is false x<=8 is true
37
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- welcome6.html -->
<!-- Using Relational Operators --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using Relational Operators</title> <script type = "text/javascript"> <!-var name, // string entered by the user now = new Date(), // current date and time hour = now.getHours(); // current hour (0-23) // read the name from the prompt box as a string name = window.prompt( "Please enter your name", "GalAnt" ); // determine whether it is morning if ( hour < 12 ) document.write( "<h1>Good Morning, " );
38
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
// determine whether the time is PM if ( hour >= 12 ) { // convert to a 12 hour cl ock hour = hour - 12; // determine whether it is before 6 PM if ( hour < 6 ) document.write( "<h1>Go od Afternoon, " ); // determine whether it is after 6 PM if ( hour >= 6 ) document.write( "<h1>Go od Evening, " ); } do cument.writeln( name + ", welcome to JavaScript p rogramming!</h1>" ); // --> </scr ipt> </head>
39
47 48 49 50
<body> <p>Click </body> </html> Refresh (or Reload) to run this script again.</p>
40
Example (x < 10 && y > 1) is true (x==5 || y==5) is false !(x==y) is true
41
Use the if....else statement to execute some code if a condition is true and another code if the condition is not true. Syntax if (condition) { code to be executed if condition is true } else { }
Use the if....else statement to execute some code if a condition is true and another code if the condition is not true. Syntax if (condition) { code to be executed if condition is true } else { }
<script type="text/javascript"> var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("Good morning!"); } else { document.write("Good day!"); } </script>
Use the switch statement to select one of many blocks of code to be executed.
case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 }
First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.
<script type="text/javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date(); theDay=d.getDay();
switch (theDay) { case 5: document.write("Finally Friday"); break; case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); break; default: document.write("I'm looking forward to this weekend!"); } </script>
48
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- SwitchTest.html -->
<!-- Using the switch statement --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Switching between XHTML List Formats</title> <script type = "text/javascript"> <!-var choice, startTag, endTag, validInput = true, listType; // users choice // starting list item tag // ending list item tag // indicates if input is valid // list type as a string
choice = window.prompt( "Select a list style:\n" + "1 (bullet), 2 (numbered), 3 (lettered)", "1" );
49
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
switch ( choice ) { case "1": startTag = "<ul>"; endTag = "</ul>"; listType = "<h1>Bullet List</h1>"; break; case "2": startTag = "<ol>"; endTag = "</ol>"; listType = "<h1>Ordered List: Numbered</h1>"; break; case "3": startTag = "<ol type = \"A\">"; endTag = "</ol>"; listType = "<h1>Ordered List: Lettered</h1>"; break; default: validInput = false; } if ( validInput == true ) { document.writeln( listType + startTag ); for ( var i = 1; i <= 3; ++i ) document.writeln( "<li>List item " + i + "</li>" );
50
48 49 50 51 52 53 54 55 56 57 58 59 </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body> } else document.writeln( "Invalid choice: " + choice ); // --> </script> document.writeln( endTag );
60 </html>
51
52
53
case a false
true
case a action(s)
break
case b false
. . .
true
case b action(s)
break
true
case z action(s)
break
54
Syntax
function functionname (var1,var2,...,varX) { some code } The parameters var1, var2, etc. are variables or values passed into the function.
Note: A function with no parameters must include the parentheses () after the function name. Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.
<html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Click me! onclick="displaymessage()" /> </form> </body> </html>
By Pramudith Kandambi
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
Outline
Introduction Essentials of Counter-Controlled Repetition for Repetition Statement Examples Using the for Statement switch Multiple-Selection Statement dowhile Repetition Statement break and continue Statements Labeled break and continue Statements Logical Operators Summary of Structured Programming Web Resources
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 2
Objectives
End of this lesson, you will be able to:
to use the for and dowhile repetition statements to execute statements in a program repeatedly. To understand multiple selection using the switch selection statement. to use the break and continue program-control statements. to use the logical operators.
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
JavaScript Loops
In JavaScript, there are two different kind of loops: for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
for keyword
for ( var counter = 1; counter <= 7; ++counter ) Initial value of control variable Increment of control variable
Loop-continuation condition
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
counter <= 7
true
false
Determine if final value of control variable has been reached.
document.writeln( "<p style=\"font-size: " + counter + "ex\">XHTML font size " + counter + "ex</p>" ); Body of loop (this may be many statements)
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
Example
<html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=5;i++) { document.write("The number is " + i); document.write("<br />"); } </script> </body> </html>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- ForCounter.html -->
Outline
<!-- Counter-Controlled Repetition with for statement --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Counter-Controlled Repetition</title> <script type = "text/javascript"> <!-// Initialization, repetition condition and // incrementing are all included in the for // statement header. for ( var counter = 1; counter <= 7; ++counter ) document.writeln( "<p style = \"font-size: " + counter + "ex\">XHTML font size " + counter + "ex</p>" ); // --> </script> </head><body></body> </html>
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
Out Put
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
10
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Sum.html -->
Outline
<!-- Using the for repetition statement --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sum the Even Integers from 2 to 100</title> <script type = "text/javascript"> <!-var sum = 0; for ( var number = 2; number <= 100; number += 2 ) sum += number; document.writeln( "The sum of the even integers " + "from 2 to 100 is " + sum ); // --> </script> </head><body></body> </html>
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
12
Out Put
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Interest.html -->
Outline
<!-- Using the for repetition statement --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Calculating Compound Interest</title> <script type = "text/javascript"> <!-var amount, principal = 1000.0, rate = .05; document.writeln( "<table border = \"1\" width = \"100%\">" ); document.writeln( "<caption>Calculating Compound Interest</caption>" ); document.writeln( "<thead><tr><th align = \"left\">Year</th>" ); document.writeln( "<th align = \"left\">Amount on deposit</th>" ); document.writeln( "</tr></thead>" );
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
14
26 27 28 29 30 31 32 33 34 35 36 37 38
for
var
year =
1;
year *
<=
10;
++year 1.0 +
) + *
amount
principal +
Math.pow(
Outline
"</tbody></table>"
);
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
15
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
16
Example
<html> <body> <script type="text/javascript"> var i=0; while (i<=5) { document.write("The number is " + i); document.write("<br />"); i++; } </script> </body> </html>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- WhileCounter.html -->
Outline
<!-- Counter-Controlled Repetition --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Counter-Controlled Repetition</title> <script type = "text/javascript"> <!-var counter = 1; while ( counter <= 7 ) { // initialization // repetition condition
document.writeln( "<p style = \"font-size: " + counter + "ex\">XHTML font size " + counter + "ex</p>" ); ++counter; } // --> </script> // increment
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
18
25
</head><body></body>
26 </html>
Outline
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
19
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
20
Example
<html> <body> <script type="text/javascript"> var i=0; do { document.write("The number is " + i); document.write("<br />"); i++; } while (i<=5); </script> </body> </html>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 21
action(s)
condition false
true
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- DoWhileTest.html -->
Outline
<!-- Using the do...while statement --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using the do...while Repetition Statement</title> <script type = "text/javascript"> <!-var counter = 1; do { document.writeln( "<h" + counter + ">This is " + "an h" + counter + " level head" + "</h" + counter + ">" ); ++counter; } while ( counter <= 6 ); // --> </script>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 23
Outline
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
24
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
25
<script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) { break; } document.write("The number is " + i); document.write("<br />"); } </script>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 26
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- BreakTest.html --> -->
Outline
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Using the break Statement in a for Structure </title> <script type = "text/javascript"> <!-for ( var count = 1; count <= 10; ++count ) { if ( count == 5 ) break; // break loop only if count == 5
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
27
23 24 25 26 27 28
document.writeln( "Broke out of loop at count = " + count ); // --> </script> </head><body></body>
Outline
29 </html>
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
28
<script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) { continue; } document.write("The number is " + i); document.write("<br />"); } </script>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 29
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- ContinueTest.html --> -->
Outline
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Using the continue Statement in a for Structure </title> <script type = "text/javascript"> <!-for ( var count = 1; count <= 10; ++count ) { if ( count == 5 ) continue; // skip remaining code in loop // only if count == 5 document.writeln( "Count is: " + count + "<br />" ); }
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
30
24 25 26 27 28
Outline
29 </html>
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- BreakLabelTest.html -->
Outline
<!-- Using the break statement with a Label --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using the break Statement with a Label</title> <script type = "text/javascript"> <!-stop: { // labeled block for ( var row = 1; row <= 10; ++row ) { for ( var column = 1; column <= 5 ; ++column ) { if ( row == 5 ) break stop; // jump to end of stop block document.write( "* " ); } document.writeln( "<br />" ); }
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
33
26 27 28 29 30 31 32 33 34 35 36 </head><body></body> </html> document.writeln( "End of // --> </script> script" ); } // the following line is skipped should not print" ); document.writeln( "This line
Outline
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
34
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- ContinueLabelTest.html --> <!-- Using the continue statement -->
Outline
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using the continue Statement with a Label</title> <script type = "text/javascript"> <!-nextRow: // target label of continue statement for ( var row = 1; row <= 5; ++row ) { document.writeln( "<br />" ); for ( var column = 1; column <= 10; ++column ) { if ( column > row ) continue nextRow; // next iteration of // labeled loop document.write( "* " ); }
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
35
26 27 28 29 30
Outline
31 </html>
11/1/2009
Pramudith Kandambi_MIT_2009_BIT
36
By Pramudith Kandambi
Outline
Introduction Thinking About Objects String Object Fundamentals of Characters and Strings Methods of the String Object Character-Processing Methods Searching Methods Splitting Strings and Obtaining Substrings Math Object Date Object Boolean and Number Objects document Object window Object Web Resources
Pramudith_Kandambi_MIT_BIT_2009 2
Pramudith_Kandambi_MIT_BIT_2009
Properties
Properties are the values associated with an object. length property of the String object
Methods
Actions that can be performed on objects. ToUpperCase() method of the String object
String Object
Property constructor length prototype Description A reference to the function that created the object Returns the number of characters in a string Allows you to add properties and methods to the object FF 1 1 1 IE 4 3 4
Method anchor() big() blink() bold() charAt() charCodeAt() concat() fixed() fontcolor() fontsize()
Description Creates an HTML anchor Displays a string in a big font Displays a blinking string Displays a string in bold Returns the character at a specified position Returns the Unicode of the character at a specified position Joins two or more strings Displays a string as teletype text Displays a string in a specified color Displays a string in a specified size
Pramudith_Kandambi_MIT_BIT_2009
FF 1 1 1 1 1 1 1 1 1 1
IE 3 3 3 3 4 4 3 3 3
6
14 13 13 13 13 14 14 14 14 13 14 13 13 14 13 13 13 13 114
7
Pramudith_Kandambi_MIT_BIT_2009
Pramudith_Kandambi_MIT_BIT_2009
13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- SearchingStrings.html --> <!-- Searching Strings -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Searching Strings with indexOf and lastIndexOf </title> <script type = "text/javascript"> <!-var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm"; function buttonPressed() { searchForm.first.value = letters.indexOf( searchForm.inputVal.value ); searchForm.last.value = letters.lastIndexOf( searchForm.inputVal.value ); searchForm.first12.value = letters.indexOf( searchForm.inputVal.value, 12 );
< fo rm n a m e = " s ea r c hF o r m " a c t io n = " " > <h 1> T h e s t r i ng t o s e a rc h is : < b r / > a b c de f g h ij k l mn o p q rs t u vw x y z ab c d ef g h i jk l m < /h 1 > <p >E n t e r s u b st r i ng t o s e a r ch f or <i np u t na m e = " i np u t V al " t yp e = " t ex t " / > <i np u t n am e = " s ea r c h " t y pe = "b u t to n " va l u e = " Se a r ch " o nc l i ck = " b u t to n P re s s e d( ) " / > < b r / > < /p > <p >F i r s t o c c ur r e nc e l oc a t e d a t i n d ex <i np u t na m e = " f ir s t " t y p e = " te x t " s i z e = " 5" / > <b r / > L a st o cc u r re n c e l o c a te d at i nd e x <i np u t n am e = " l as t " ty p e = " t ex t " s i z e = " 5 " / > <b r / > F i rs t oc c u rr e n c e f r o m i n de x 12 l o ca t e d a t in d e x <i np u t n am e = " f ir s t 1 2" t y pe = " t e xt " s i ze = " 5 " / > <b r / > L a st o cc u r re n c e f r o m i n d ex 1 2 l o c at e d at i nd e x <i np u t n am e = " l as t 1 2 " t y pe = "t e x t" s i ze = "5 " /> < / p>
51 52
</form> </body>
53 </html>
Pramudith_Kandambi_MIT_BIT_2009
17
Pramudith_Kandambi_MIT_BIT_2009
18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- SplitAndSubString.html --> <!-- String Method split and substring --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>String Method split and substring</title> <script type = "text/javascript"> <!-function splitButtonPressed() { var strings = myForm.inputVal.value.split( " " ); myForm.output.value = strings.join( "\n" ); myForm.outputSubstring.value = myForm.inputVal.value.substring( 0, 10 ); } // --> </script> </head>
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
<body> <form name = "myForm" action = ""> <p>Enter a sentence to split into words<br /> <input name = "inputVal" type = "text" size = "40" /> <input name = "splitButton" type = "button" value = "Split" onclick = "splitButtonPressed()" /></p> <p>The sentence split into words is<br /> <textarea name = "output" rows = "8" cols = "34"> </textarea></p> <p>The first 10 characters of the input string are <input name = "outputSubstring" type = "text" size = "15" /></p> </form> </body>
42 </html>
Pramudith_Kandambi_MIT_BIT_2009
21
Math Object
Allow the programmer to perform many common mathematical calculations
Pramudith_Kandambi_MIT_BIT_2009
22
Math Object
Method abs( x ) Example abs( 7.2 ) is 7.2 abs( 0.0 ) is 0.0 abs( -5.6 ) is 5.6 ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0 integer not less than x ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0 (x in radians) exp( x ) exponential method ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 floor( x ) rounds x to the largest floor( 9.2 ) is 9.0 integer not greater than x floor( -9.8 ) is -10.0 log( x ) natural logarithm of x log( 2.718282 ) is 1.0 (base e) log( 7.389056 ) is 2.0 max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3
Math object methods.
Pramudith_Kandambi_MIT_BIT_2009 23
min( x, y ) smaller value of x and y pow( x, y ) x raised to power y (xy) round( x ) rounds x to the closest integer sin( x ) trigonometric sine of x (x in radians) sqrt( x ) square root of x
min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7 pow( 2.0, 7.0 ) is 128.0 pow( 9.0, .5 ) is 3.0 round( 9.75 ) is 10 round( 9.25 ) is 9 sin( 0.0 ) is 0.0
sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent tan( 0.0 ) is 0.0 of x (x in radians) Math object methods.
Pramudith_Kandambi_MIT_BIT_2009
24
Constant Math.E
Description Base of a natural logarithm (e). Math.LN2 Natural logarithm of 2. Math.LN10 Natural logarithm of 10. Math.LOG2E Base 2 logarithm of e. Math.LOG10E Base 10 logarithm of e. Math.PI the ratio of a circles circumference to its diameter. Math.SQRT1_2 Square root of 0.5. Math.SQRT2 Square root of 2.0. Properties of the Math object.
Value Approximately 2.718. Approximately 0.693. Approximately 2.302. Approximately 1.442. Approximately 0.434. Approximately 3.141592653589793. Approximately 0.707. Approximately 1.414.
Pramudith_Kandambi_MIT_BIT_2009
25
Method
Description
getDate() getUTCDate() getDay() getUTCDay() getFullYear() getUTCFullYear() getHours() getUTCHours() getMilliseconds() getUTCMilliSeconds()
Returns a number from 1 to 31 representing the day of the month in local time or UTC, respectively. Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC, respectively. Returns the year as a four-digit number in local time or UTC, respectively.
Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively. Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively. The time is stored in hours, minutes, seconds and milliseconds. getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time getUTCMinutes() or UTC, respectively. getMonth() Returns a number from 0 (January) to 11 (December) representing the month in getUTCMonth() local time or UTC, respectively. getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time getUTCSeconds() or UTC, respectively. getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object. getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTCpreviously known as Greenwich Mean Time (GMT). setDate( val ) Sets the day of the month (1 to 31) in local time or UTC, respectively. setUTCDate( val ) Methods of the Date object. Pramudith_Kandambi_MIT_BIT_2009 26
Method
Description
Sets the year in local time or UTC, respectively. The second and third setFullYear( y, m, d ) setUTCFullYear( y, m, d ) arguments representing the month and the date are optional. If an
setHours( h, m, s, ms ) setUTCHours( h, m, s, ms )
optional argument is not specified, the current value in the Date object is used. Sets the hour in local time or UTC, respectively. The second, third and fourth arguments representing the minutes, seconds and milliseconds are optional. If an optional argument is not specified, the current value in the Date object is used.
Sets the number of milliseconds in local time or UTC, respectively. setMilliSeconds( ms ) setUTCMilliseconds( ms ) Sets the minute in local time or UTC, respectively. The second and setMinutes( m, s, ms ) setUTCMinutes( m, s, ms ) third arguments representing the seconds and milliseconds are optional.
If an optional argument is not specified, the current value in the Date object is used. Sets the month in local time or UTC, respectively. The second argument representing the date is optional. If the optional argument is not specified, the current date value in the Date object is used.
Sets the second in local time or UTC, respectively. The second argument representing the milliseconds is optional. If this argument is not specified, the current millisecond value in the Date object is used.
27
Pramudith_Kandambi_MIT_BIT_2009
Method
Description
setTime( ms ) toLocaleString()
Sets the time based on its argumentthe number of elapsed milliseconds since January 1, 1970. Returns a string representation of the date and time in a form specific to the computers locale. For example, September 13, 2001 at 3:42:22 PM is represented as 09/13/01 15:47:22 in the United States and 13/09/01 15:47:22 in Europe. Returns a string representation of the date and time in the form: 19 Sep 2001 15:47:22 UTC Returns a string representation of the date and time in a form specific to the locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United States). The time in number of milliseconds since midnight, January 1, 1970.
Pramudith_Kandambi_MIT_BIT_2009
28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- DateTime.html --> <!-- Date and Time Methods -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Date and Time Methods</title> <script type = "text/javascript"> <!-var current = new Date(); document.writeln( "<h1>String representations and valueOf</h1>" ); document.writeln( "toString: " + current.toString() + "<br />toLocaleString: " + current.toLocaleString() + "<br />toUTCString: " + current.toUTCString() + "<br />valueOf: " + current.valueOf() ); document.writeln( "<h1>Get methods for local time zone</h1>" );
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
do cu m e n t. w r i te l n ( " g e tD a t e: " + c u rr e n t .g e t D at e ( ) + " < b r /> g e tD a y : " + c u r r en t . ge t D ay ( ) + " < b r /> g e tM o n th : " + c ur r e n t. g e tM o n t h( ) + " < b r /> g e tF u l lY e a r : " + c u r re n t .g e t F ul l Y e ar ( ) + " < b r /> g e tT i m e: " + c u rr e n t .g e t Ti m e ( ) + " < b r / > g e tH o u rs : " + c ur r e n t. g e tH o u r s( ) + " < b r /> g e tM i n ut e s : " + c u r r en t . ge t M i nu t e s( ) + " < b r /> g e tS e c on d s : " + c u r r en t . ge t S e co n d s( ) + " < b r /> g e tM i l li s e c on d s : " + c u r r e nt . g et M i ll i s e co n d s () + " < b r /> g e tT i m ez o n e Of f s e t: " + c u r r en t . g et T i me z o n eO f f se t ( ) ) ; do cu m e n t .w r i te l n ( " < h 1 > Sp e c if y i ng a r gu m e n ts f or a n e w Da t e < /h 1 > " ) ; va r a n o t he r D at e = n e w D a t e( 2 0 01 , 2, 1 8 , 1 , 5, 0 , 0 ); do cu m e n t. w r i te l n ( " D a te : " + a no t h er D a t e ) ; do cu m e n t. w r i te l n ( " < h 1 >S e t me t h od s f or l oc a l ti m e z o n e </ h 1 > " ) ; an ot h e r Da t e . se t D at e ( 31 ) ; an ot h e r Da t e . se t M on t h ( 1 1 ) ; an ot h e r Da t e . se t F ul l Y e ar ( 2 00 1 ); an ot h e r Da t e . se t H ou r s ( 2 3 ) ; an ot h e r Da t e . se t M in u t e s( 5 9 ) ;
50 51 52 53 54 55 56
anotherDate.setSeconds( 59 ); document.writeln( "Modified date: " + anotherDate ); // --> </script> </head><body></body> </html>
Pramudith_Kandambi_MIT_BIT_2009
32
Description Returns the string representation of the number. The optional radix argument (a number from 2 to 36) specifies the numbers base. For example, radix 2 results in the binary representation of the number, 8 results in the octal representation, 10 results in the decimal representation and 16 results in the hexadecimal representation. See Appendix E, Number Systems for a review of the binary, octal, decimal and hexadecimal number systems. valueOf() Returns the numeric value. Number.MAX_VALUE This property represents the largest value that can be stored in a JavaScript programapproximately 1.79E+308 Number.MIN_VALUE This property represents the smallest value that can be stored in a JavaScript programapproximately 2.22E308 Number.NaN This property represents not a numbera value returned from an arithmetic expression that does not result in a number (e.g., the expression parseInt( "hello" ) cannot convert the string "hello" into a number, so parseInt would return Number.NaN. To determine whether a value is NaN, test the result with function isNaN, which returns true if the value is NaN; otherwise, it returns false. Number.NEGATIVE_INFINITY This property represents a value less than -Number.MAX_VALUE. Number.POSITIVE_INFINITY This property represents a value greater than Number.MAX_VALUE. Number object methods and properties.
Pramudith_Kandambi_MIT_BIT_2009 33
document Object
Manipulate document that is currently visible in the browser window
Method or Property write( string ) Description Writes the string to the XHTML document as XHTML code. writeln( string ) Writes the string to the XHTML document as XHTML code and adds a newline character at the end. document.cookie This property is a string containing the values of all the cookies stored on the users computer for the current document. See Section 12.9, Using Cookies. document.lastModified This property is the date and time that this document was last modified. Important document object methods and properties.
Pramudith_Kandambi_MIT_BIT_2009 34
window Object
Provides methods for manipulating browser window
Pramudith_Kandambi_MIT_BIT_2009
35
Description Creates a new window with the URL of the window set to url, the name set to name, and the visible features set by the string passed in as option. prompt( prompt, default ) Displays a dialog box asking the user for input. The text of the dialog is prompt, and the default value is set to default. close() Closes the current window and deletes its object from memory. window.focus() This method gives focus to the window (i.e., puts the window in the foreground, on top of any other open browser windows). window.document This property contains the document object representing the document currently inside the window. window.closed This property contains a boolean value that is set to true if the window is closed, and false if it is not. window.opener This property contains the window object of the window that opened the current window, if such a window exists. Important window object methods and properties.
Pramudith_Kandambi_MIT_BIT_2009 36
1 2 3 4 5 6 7 8 9
<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- window.html --> -->
10 <title>Using the Window Object</title> 11 12 <script type = "text/javascript"> 13 14 15 16 17 18 19 20 21 22 23 24 25 function createChildWindow() { // these variables all contain either "yes" or "no" // to enable or disable a feature in the child window var toolBar // specify if toolbar will appear in child window var menuBar; // specify if menubar will appear in child window var location; // specify if address bar will appear in child window var scrollBars; // specify if scrollbars will appear in child window var status; // specify if status bar will appear in child window var resizable; // specify if the child window will be resizable <!-var childWindow; // variable to control the child window
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 / / d e t er mi n e w h et he r t h e S c r ol l Ba r ch e c kb o x i s c h e ck e d i f ( s cr o l l Ba r s Ch ec kB o x . ch e c ke d ) s c r ol lB a rs = " ye s" ; e l se s c r ol lB a rs = " no "; / / d e t er mi n e w h et he r t h e A d d re ss B a r c h e ck b ox i s c h ec k e d i f ( l oc a t i on C h ec kB ox . c h ec k e d ) l o c at io n = " ye s" ; e l se l o c at io n = " no "; / / d e t er mi n e w h et he r t h e M e n u Ba r c h ec k bo x is c he c k ed i f ( m en u B a rC h e ck Bo x. c h e ck e d ) m e n uB ar = " y es " ; e l se m e n uB ar = " n o" ; / / d e t er mi n e w h et he r t h e T o o l Ba r c h ec k b ox is c he c k ed i f ( t oo l B a rC h e ck Bo x. c h e ck e d ) t o o lB ar = " y es " ; e l se t o o lB ar = " n o" ;
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
// determi ne w hether the Sta tus Bar checkbox is checked if ( statusCheckBox.chec ked ) status = "yes"; else status = "n o"; // determi ne w hether the Res izab le checkbox is che cked if ( resizableCheckBox.c heck ed ) resizab le = "yes"; else resizab le = "no"; // display win dow with s elec ted features childWindo w = window.ope n( " ", " ", "resizable = " + resizable + ", tool bar = " + tool Bar + ", menubar = " + menuBar + ", stat us = " + statu s + ", l ocation = " + location + ", scro llba rs = " + s crol lBar s ); // disable but tons closeButto n.di sabled = f alse ; modifyButt on.d isabled = fals e; getURLButt on.d isabled = fals e; setURLButt on.d isabled = fals e; } // end function createChi ldWi ndow
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
// insert text from the textbox into the child window function modifyChildWindow() { if ( childWindow.closed ) alert( "You attempted to interact with a closed window" ); else childWindow.document.write( textForChild.value ); } // end function modifyChildWindow // close the child window function closeChildWindow() { if ( childWindow.closed ) alert( "You attempted to interact with a closed window" ); else childWindow.close(); closeButton.disabled = true; modifyButton.disabled = true; getURLButton.disabled = true; setURLButton.disabled = true; } // end function closeChildWindow
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
// copy the U RL o f the chil d wi ndow into the parent windows myChildURL function getChildWindowURL() { if ( childWindow .closed ) alert( "You attempted to intera ct w ith a closed windo w" ); else myChildURL.value = childWindow. loca tion; } // end function getChildWindowURL // set the URL of the child window to the URL // in the parent wi ndow s myChildURL function setChildWindowURL() { if ( childWindow .closed ) alert( "You attempted to intera ct w ith a closed windo w" ); else childWindow.location = myChildU RL.v alue; } // end function setChildWindowURL //-->
118 </script> 119 120 </head> 121 122 <body> 123 <h1>Hello, This is the main window</h1>
1 24 <p>Please ch eck the features to e nabl e f or the child wi ndo w <br/> 1 25 1 26 1 27 1 28 1 29 1 30 1 31 1 32 1 33 1 34 1 35 1 36 1 37 1 38 1 39 1 40 1 41 1 42 1 43 1 44 <p>Please en ter the text that you wou ld like to display 1 45 1 46 1 47 in the ch ild win dow<br/> <input id = "tex tForChild" typ e = "te xt" val ue = " <h1> Hello, I am a chi ld window</h1> <br \>" /> <input id = "too lBarCheckBox" type = "checkbox" valu e = "" che cke d = "checked" /> <la bel >To ol B ar</label> <input id = "men uBarCheckBox" type = "checkbox" valu e = "" che cke d = "checked" /> <la bel >Me nu B ar</label> <input id = "loc ationCheckBox" typ e = "checkbox" val ue = "" che cke d = "checked" /> <la bel >Ad dres s Bar</label>< br/> <input id = "scr ollBarsCheckBo x" t ype = "checkbox" v alu e = "" che cke d = "checked" /> <la bel >Sc roll Bars</label> <input id = "sta tusCheckBox" t ype = " checkbox" value = "" che cke d = "checked" /> <la bel >St atus Bar</label> <input id = "res izableCheckBox " ty pe = "checkbox" va lue = "" che cke d = "checked" /> <la bel >Re siza ble</label><br /></ p>
<input id = "createButton" type = "button" value = "Create Child Window" onclick = "createChildWindow()" /> <input id= "modifyButton" type = "button" value = "Modify Child Window" onclick = "modifyChildWindow()" disabled = "disabled"/> <input id = "closeButton" type = "button" value = "Close Child Window" onclick = "closeChildWindow()" disabled = "disabled"/></p>
155 <p>The other window's URL is: <br/> 156 157 158 159 160 161 162 </body> 163 </html> <input id = "myChildURL" type = "text" value = "./"/> <input id = "setURLButton" type = "button" value = "Set Child URL" onclick = "setChildWindowURL()" disabled = "disabled"/> <input id = "getURLButton" type = "button" value = "Get URL From Child" onclick = "getChildWindowURL()" disabled = "disabled"/></p>
Pramudith_Kandambi_MIT_BIT_2009
44
Pramudith_Kandambi_MIT_BIT_2009
45
Web Resources
www.javascript.com www.iboost.com/build/programming/js/tutorial/885.htm www.javascriptsearch.com www.a1javascripts.com
Pramudith_Kandambi_MIT_BIT_2009
46
By Pramudith Kandambi
JavaScript: Arrays
Outline
Introduction Arrays Declaring and Allocating Arrays Examples Using Arrays Random Image Generator Using Arrays References and Reference Parameters Passing Arrays to Functions Sorting Arrays Searching Arrays: Linear Search and Binary Search Multidimensional Arrays Building an Online Quiz Web Resources
Array
In this section, you will learn:
To introduce the array data structure. To understand the use of arrays to store, sort and search lists and tables of values. To understand how to declare an array, initialize an array and refer to individual elements of an array. To be able to pass arrays to functions. To be able to search and sort an array. To be able to declare and manipulate multi-dimensional arrays.
An array is a special variable, which can hold more than one value, at a time. If you have a list of items. However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The best solution here is to use an array!
cars1="Saab"; cars2="Volvo"; cars3="BMW";
Name of array
c[ 0 ] c[ 1 ] c[ 2 ] c[ 3 ] c[ 4 ] c[ 5 ] c[ 6 ] c[ 7 ] c[ 8 ]
c[ 9 ] c[ 10 ] c[ 11 ]
A 12-element array.
The following code creates an Array object called myCars: var myCars=new Array(); There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
Normal way var myCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; You could also pass an integer argument to control the array's size: var myCars=new Array(3); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; var myCars=new Array("Saab","Volvo","BMW"); Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0. EX The following code line: document.write(myCars[0]); will result in the following output: Saab
To modify a value in an existing array, just add a new value to the array with a specified index number: EX myCars[0]="Opel"; Now, the following code line: document.write(myCars[0]); will result in the following output: Opel
<html> <body> <script type="text/javascript"> var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (i=0;i<mycars.length;i++) { document.write(mycars[i] + "<br />"); } </script> </body> </html>
<html> <body> <script type="text/javascript"> var x; var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (x in mycars) { document.write(mycars[x] + "<br />"); } </script> </body> </html>
<html> <body> <script type="text/javascript"> var arr = new Array(3); arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; document.write(arr.join("-") + "<br />"); document.write(arr.join("")); </script> </body> </html>
<html> <body> <script type="text/javascript"> var arr = new Array(6); arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; arr[5] = "Tove"; document.write(arr + "<br />"); document.write(arr.sort()); </script> </body> </html>
Arrays
15
Arrays in JavaScript
16
Arrays in memory
Objects Operator new
Allocates memory for objects Dynamic memory allocation operator
17
Default value is undefined for loops convenient Referring to uninitialized elements or elements outside array bounds is an error
18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- InitArray.html --> <!-- Initializing an Array -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Initializing an Array</title> <script type = "text/javascript"> <!-// this function is called when the <body> element's // onload event occurs function initializeArrays() { var n1 = new Array( 5 ); var n2 = new Array(); // allocate 5-element Array // allocate empty Array
Array n1
Array n2
is an empty array.
The for loop initializes the elements in n1 to their subscript numbers (0 to 4). Array n1
19
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 // output "header" followed by a two-column table // containing subscripts and elements of "theArray" function outputArray( header, theArray ) { document.writeln( "<h2>" + header + "</h2>" ); document.writeln( "<table border = \"1\" width =" + "\"100%\">" ); } outputArray( "Array n1 // create and initialize five-elements in Array n2 for ( i = 0; i < 5; ++i ) n2[ i ] = i;
The for loop adds Eachelements to Array n2 and five function displays the initialize each element to itsof its respective (0 to contents subscript number contains", n1 ); 4). Array in an XHTML table.
The second time function ouputArray is first time function ouputArray is called, variable header gets the value of Array n2 "<thead><th width = \"100\"" + n1 document.writeln( contains and variable theArray gets the value of n2+ n1 "align = \"left\">Subscript</th>" .
20
44 45 46 47 48 49 50 51 52 53 54 </head><body onload = "initializeArrays()"></body> 55 </html> } // --> </script> document.writeln( "</tbody></table>" ); for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<tr><td>" + i + "</td><td>" + theArray[ i ] + "</td></tr>" );
21
22
var n = [ 10, 20, 30, 40, 50 ]; var n = new Array( 10, 20, 30, 40, 50 ); Also possible to only initialize some values
Leave uninitialized elements blank Uninitialized elements default to undefined
23
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- InitArray2.html -->
<!-- Initializing an Array with a Declaration --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Initializing an Array with a Declaration</title> <script type = "text/javascript"> <!-function start() { // Initializer list specifies // value for each element. "yellow", "black" ); var integers1 = [ 2, 4, 6, 8 ]; var integers2 = [ 2, , , 8 ]; outputArray( "Array colors contains", colors ); outputArray( "Array integers1 contains", integers1 ); outputArray( "Array integers2 contains", integers2 ); }
Array integers1
Two values are not supplied for number of elements and will be displayed as integers2, which undefined.
24
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 </head><body onload = "start()"></body> 49 </html> } // --> </script> document.writeln( "</tbody></table>" ); for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<tr><td>" + i + "</td><td>" + theArray[ i ] + "</td></tr>" ); // output "header" followed by a two-column table // containing subscripts and elements of "theArray" function outputArray( header, theArray ) { document.writeln( "<h2>" + header + "</h2>" ); document.writeln( "<table border = \"1\"" + "width = \"100%\">" ); document.writeln( "<thead><th width = \"100\" " + "align = \"left\">Subscript</th>" + "<th align = \"left\">Value</th></thead><tbody>" );
25
26
forin statement Perform an action for each element in an array Iterates over array elements
Ignores non-existent elements
27
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- SumArray.html -->
<!-- Summing Elements of an Array --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sum the Elements of an Array</title> <script type = "text/javascript"> <!-function start() { var total1 = 0, total2 = 0; for ( var i = 0; i < theArray.length; i++ ) total1 += theArray[ i ]; document.writeln( "Total using subscripts: " + total1 );
The for loop sums the values contained in the 10-element integer array called theArray.
var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
28
24 25 26 27 28 29 30 31 32 33 }
for ( var element in theArray ) total2 += theArray[ element ]; document.writeln( "<br />Total using for...in: " + total2 ); // --> </script> </head><body onload = "start()"></body>
Variable element is assigned a subscript in the range of 0 up to, but not including, theArray.length.
34 </html>
29
30
Arrays can provide shorter and cleaner substitute for switch statements
Each element represents one case
31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- RollDie.html -->
<!-- Roll a Six-Sided Die 6000 Times --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Roll a Six-Sided Die 6000 Times</title> <script type = "text/javascript"> <!-var face, frequency = [ , // summarize results for ( var roll = 1; roll <= 6000; ++roll ) { face = Math.floor( 1 + Math.random() * 6 ); ++frequency[ face ]; }
Referencing Array frequency replaces the switch statement 0, 0 in 0, 0, 0, 0, used ]; Chapter 10s example.
32
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
document.writeln( "<thead><th width = \"100\"" + " align = \"left\">Face<th align = \"left\">" + "Frequency</th></thead></tbody>" ); for ( face = 1; face < frequency.length; ++face ) document.writeln( "<tr><td>" + face + "</td><td>" + frequency[ face ] + "</td></tr>" ); document.writeln( "</tbody></table>" ); // --> </script> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body>
40 </html>
33
34
Specify any file name rather than integers 1-7 Result of Math.random call is index into array of image file names
35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- RandomPicture2.html -->
<!-- Randomly displays one of 7 images --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Random Image Generator</title> <script type = "text/javascript"> <!-var pictures = [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ];
36
16 17 18 19 20 21 22 23 24 25 26 27 <body> <p>Click Refresh (or Reload) to run the script again</p> </body> </head> document.write ( "<img src = \"" + pictures[ Math.floor( Math.random() * 7 ) ] + ".gif\" width = \"105\" height = \"100\" />" ); // --> </script>
28 </html>
37
38
Pass-by-reference
39
40
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- PassArray.html --> <!-- Passing Arrays -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Passing Arrays and Individual Array Elements to Functions</title> <script type = "text/javascript"> <!-function start() {
The first call to function outputArray displays the contents of the Array a before it is modified.
var a = [ 1, 2, 3, 4, 5 ]; document.writeln( "<h2>Effects of passing entire " + "array call-by-reference</h2>" ); outputArray( "The values of the modifyArray( a );
41
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 } }
outputArray( "The values of the modified array are: ", a ); document.writeln( "<h2>Effects of passing outputArray array " +
Again, function is called to show that "element call-by-value</h2>" + the contents of Array a have been "a[3] before modifyElement: " + a[ 3 ] ); modified. Function modifyElement multiplies the contents of a[ 3 ] by 2. The value of a[ 3 ] is output to show its contents before it is modified.
modifyElement( a[ 3 ] ); document.writeln(
// outputs "header" followed by the contents of "theArray" function outputArray( header, theArray ) { document.writeln( header + theArray.join( " " ) + "<br />" );
Method join takes as its argument a string containing a separator that should be used to separate the elements of the array in the string that is returned.
42
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
// function that modifies the elements of an array function modifyArray( theArray ) { for ( var j in theArray ) theArray[ j ] *= 2; } // function that attempts to modify the value passed function modifyElement( e ) { e *= 2; document.writeln( "<br />value in modifyElement: " + e ); } // --> </script> </head><body onload = "start()"></body>
63 </html>
43
44
Sorting
Important computing task Array.sort Defaults to string comparison Optional comparator function
Return negative if first argument less than second Return zero if arguments equal Return positive if first argument greater than second
45
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- sort.html --> <!-- Sorting an Array -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sorting an Array with Array Method sort</title> <script type = "text/javascript"> <!-function start() {
Method sort takes as its optional argument the name of a function that compares two arguments and returns a value of 1, 0 or 1.
var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; document.writeln( "<h1>Sorting an Array</h1>" ); outputArray( "Data items in original order: ", a ); a.sort( compareIntegers ); } // sort the array outputArray( "Data items in ascending order: ", a );
46
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 </head><body onload = "start()"></body> 40 </html> } // --> </script> // comparison function for use with sort function compareIntegers( value1, value2 ) { return parseInt( value1 ) - parseInt( value2 ); } // outputs "header" followed by the contents of "theArray" function outputArray( header, theArray ) { document.writeln( "<p>" + header + theArray.join( " " ) + "</p>" );
Function compareIntegers calculates the difference between the integer values of its arguments.
47
Fig. 11.9
48
Searching
Linear search
Look for matching key value Iterate through each element until match found Inefficient
Worst case scenario, must test entire array
Binary search
Requires sorted data Cuts search range in half each iteration Efficient
Only look at small fraction of elements
49
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- LinearSearch.html --> <!-- Linear Search of an Array -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Linear Search of an Array</title> <script type = "text/javascript"> <!-var a = new Array( 100 );
Array a
198.
// fill Array with even integer values from 0 to 198 for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i;
50
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
// function called when "Search" button is pressed function buttonPressed() { var searchKey = searchForm.inputVal.value; // Array a is passed to linearSearch even though it // is a global variable. Normally an array will // be passed to a method for
Get value of search key from the input searching. field in the XHTML form. Calling function linearSearch and passing it the Array a and the value of variable " + element; searchKey as an integer.
var element = linearSearch( a, parseInt( searchKey ) ); if ( element != -1 ) searchForm.result.value = "Found value in element else }
51
37
// Search "theArray" for the specified "key" value function linearSearch( theArray, key ) { for ( var n = 0; n < theArray.length; ++n ) if ( theArray[ n ] == key ) return n; return -1; } // --> </script> </head> <body> <form name = "searchForm" action = ""> <p>Enter integer search key<br /> <input name = "inputVal" type = "text" /> <input name = "search" type = "button" value = "Search" onclick = "buttonPressed()" /><br /></p> <p>Result<br /> <input name = "result" type = "text" size = "30" /></p> </form> </body>
38
39
40
41
42
43
44
45
46
47
Variable theArray gets the value of Array a and variable key gets Function linearSearch compares the value of variable searchKey. each each element with a search key.
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 </html>
52
53
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- BinarySearch.html --> <!-- Binary search -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Binary Search</title> <script type = "text/javascript"> <!-var a = new Array( 15 ); for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i;
54
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
// function called when "Search" button is pressed function buttonPressed() { var searchKey = searchForm.inputVal.value; searchForm.result.value = "Portions of array searched\n"; // //
Function binarySearch receives two Array a is passed to binarySearch arguments: it even though the Array a and the search key, is a global variable. This is done because searchKey.
// normally an array is passed to a method // for searching. var element = binarySearch( a, parseInt( searchKey ) ); if ( element != -1 ) searchForm.result.value += "\nFound value in element " + element; else searchForm.result.value += "\nValue not found"; }
55
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
// Binary search function binarySearch( theArray, key ) { var low = 0; var middle; while ( low <= high ) { middle = ( low + high ) / 2; // The following line is used to display the // part of theArray currently being manipulated // during each iteration of the binary // search loop. buildOutput( theArray, // low subscript // middle subscript var high = theArray.length - 1; // high subscript
If the key matches the middle element of a subarray, the subscript of the current element is high ); low, middle, less than the middle element, the If key is returned. high subscript is set to middle 1.
// match
If is greater then the middle elements, the high subscript is set to middle + 1.
56
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 } // --> </script> </head> searchForm.result.value += "\n"; } else searchForm.result.value += theArray[ i ] + ( theArray[ i ] < 10 ? " " : " " ); // Build one row of output showing the current // part of the array being processed. function buildOutput( theArray, low, mid, high ) { for ( var i = 0; i < theArray.length; i++ ) { if ( i < low || i > high ) } return -1; // searchKey not found
Function buildOutput creates the markup searchForm.result.value += " the results of the search. that displays ";
searchForm.result.value += theArray[ i ] + ( theArray[ i ] < 10 ? "* " : "* " );
57
90
<body> <form name = "searchForm" action = ""> <p>Enter integer search key<br /> <input name = "inputVal" type = "text" /> <input name = "search" type = "button" value = "Search" onclick = "buttonPressed()" /><br /></p> <p>Result<br /> <textarea name = "result" rows = "7" cols = "60"> </textarea></p> </form> </body>
91
92
93
94
95
96
97
98
99
100
101 </html>
58
59
60
Column 1
Column 2
Column 3
a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ] a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript (or index) Row subscript (or index) Array name
61
Group by row in square brackets Treated as arrays of arrays Creating array b with one row of two elements and a second row of three elements:
var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];
62
Create array b with two rows, first with five columns and second with three:
var b; b = new Array( 2 ); b[ 0 ] = new Array( 5 ); b[ 1 ] = new Array( 3 );
63
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- InitArray3.html -->
<!-- Initializing Multidimensional Arrays --> <html xmlns = "http://www.w3.org/1999/xhtml"> Array array1 <head>
in two rows.
Array array2
<title>Initializing Multidimensional Arrays</title> <script type = "text/javascript"> <!-function start() { var array1 = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]; var array2 = [ [ 1, 2 ], // first row // second row // first row
three rows.
Function outputArray row displays each arrays [ 3 ], // second Web page. [ elements ]; a // third row 4, 5, 6 ] in
outputArray( "Values in array1 by row", array1 ); outputArray( "Values in array2 by row", array2 ); }
64
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 </head><body onload = "start()"></body> 44 </html> } // --> </script> document.writeln( "</tt>" ); } document.writeln( "<br />" ); for ( var j in theArray[ i ] ) document.write( theArray[ i ][ j ] + " " ); for ( var i in theArray ) { function outputArray( header, theArray ) { document.writeln( "<h2>" + header + "</h2><tt>" );
65
66
Radio buttons
Represented as an array
XHTML Forms
Name of radio buttons is name of array One element per button checked property is true when selected
Contain controls, including radio buttons action property specifies what happens when submitted
Can call JavaScript code
67
1 2 3 4 5 6 7 8 9
<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- quiz.html --> <!-- Online Quiz -->
10 <title>Online Quiz</title> 11 12 <script type = "text/JavaScript"> 13 14 15 16 17 18 19 20 21 22 23 </script> 24 25 </head> } function checkAnswers() { // determine whether the answer is correct if ( myQuiz.radiobutton[ 1 ].checked ) document.write( "Congratulations, your answer is correct" ); else // if the answer is incorrect document.write( "Your answer is incorrect. Please try again" );
68
26 27 <body> 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 <input type = "submit" name = "submit" value = "Submit" /> <input type = "reset" name = "reset" value = "Reset" /> </p> </form> <input type = "radio" name = "radiobutton" value = "PORT" /> <label>Portability Tip</label><br /> <input type = "radio" name = "radiobutton" value = "PERF" /> <label>Performance Tip</label> <input type = "radio" name = "radiobutton" value = "EPT" /> <label>Error-Prevention Tip</label> <input type = "radio" <form id = "myQuiz" action = "JavaScript:checkAnswers()"> <p>Select the name of the tip that goes with the image shown:<br /> <img src="EPT.gif" width="108" height="100" alt="mystery tip"/> <br />
Call the checkAnswers function when the form is submitted. name = "radiobutton" value = "CPE" />
49 </body> 50 </html>
69
70
By Pramudith Kandambi
Detect the visitor's browser, and then serve up the appropriate information. JavaScript includes an object called the Navigator object, that can be used for this purpose. The Navigator object contains information about the visitor's browser name, version, and more.
<html> <body> <script type="text/javascript"> var browser=navigator.appName; var b_version=navigator.appVersion; var version=parseFloat(b_version); document.write("Browser name: "+ browser); document.write("<br />"); document.write("Browser version: "+ version); </script> </body> </html>
A cookie is often used to identify a user. A cookie is a variable Stored on the visitor's computer. Each time the same computer requests a page with a browser, It will send the cookie too.
Name cookie
The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome Omana The name is retrieved from the stored cookie The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday june 11, 2009!" The date is retrieved from the stored cookie
Password cookie
Date cookie
JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be:
has has has has the the the the user user user user left required fields empty? entered a valid e-mail address? entered a valid date? entered text in a numeric field?
Client-side form validation (usually with JavaScript embedded in the Web page)
<script type="text/javascript"> function validate_form ( ) { if ( document.contact_form.contact_name.value == "" ) { alert ( "Please fill in the 'Your Name' box." ); } } </script>
<script type='text/javascript'> function notEmpty(elem, helperMsg) { if(elem.value.length == 0) { alert(helperMsg); elem.focus(); return false; } return true; } </script> <form> Required Field: <input type='text' id='req1'/> <input type='button' onclick="notEmpty(document.getElementById('req1'), 'Please Enter a Value')" value='Check Field' /> </form>
<script type='text/javascript'> function isNumeric(elem, helperMsg) { var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)) { return true; } Else { alert(helperMsg); elem.focus(); return false; } } </script> <form> Numbers Only: <input type='text' id='numbers'/> <input type='button' onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only Please')" value='Check Field' /> </form>
<script type='text/javascript'> {
Else
} </script>
<input type='button' onclick="isAlphabet(document.getElementById('letters'), 'Letters Only Please')" value='Check Field' /> </form>
<script type='text/javascript'> function lengthRestriction(elem, min, max) { var uInput = elem.value; if(uInput.length >= min && uInput.length <= max) { return true; } Else { alert("Please enter between " +min+ " and " +max+ " characters"); elem.focus(); return false; } } </script> <form> Username(6-8 characters): <input type='text' id='restrict'/> <input type='button' onclick="lengthRestriction(document.getElementById('restrict'), 6, 8)" value='Check Field' /> </form>
http://www.tizag.com/javascriptT/java scriptform.php
It is possible to use JavaScript to create animated images. The trick is to let a JavaScript change between different images on different events.
<html> <head> <script type="text/javascript"> function mouseOver() { document.getElementById("b1").src ="b_blue.gif"; } function mouseOut() { document.getElementById("b1").src ="b_pink.gif"; } </script> </head> <body> <a href="http://www.w3schools.com" target="_blank"> <img border="0" alt="Visit W3Schools!" src="b_pink.gif" id="b1" width="26" height="26" onmouseover="mouseOver()" onmouseout="mouseOut()" /></a> </body> </html>
With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events. The two key methods that are used are:
setTimeout() - executes a code some time in the future clearTimeout() - cancels the setTimeout()
Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.
Syntax
var t=setTimeout("javascript statement",milliseconds);
The setTimeout() method returns a value In the statement above, the value is stored in a variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable name.
<html> <head> <script type="text/javascript"> function timedMsg() { var t=setTimeout("alert('5 seconds!')",5000); } </script> </head> <body> <form> <input type="button" value="Display timed alertbox!" onClick="timedMsg()" /> </form> </body>
</html>
Syntax clearTimeout(setTimeout_variable) Example The example below is the same as the "Infinite Loop" example above. The only difference is that we have now added a "Stop Count!" button that stops the timer:
By Pramudith Kandambi
What is PHP?
PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software PHP is free to download and use
What is MySQL?
MySQL MySQL MySQL MySQL MySQL is a database server is ideal for both small and large applications supports standard SQL compiles on a number of platforms is free to download and use
PHP + MySQL
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)
Why PHP?
PHP PHP PHP PHP runs on different platforms (Windows, Linux, Unix, etc.) is compatible with almost all servers used today (Apache, IIS, etc.) is FREE to download from the official PHP resource: www.php.net is easy to learn and runs efficiently on the server side
Where to Start?
Install Apache (or IIS) on your own server, install PHP, and MySQL
PHP code is executed on the server, and the plain HTML result is sent to the browser. Basic PHP Syntax
A PHP scripting block always starts with
*/
When a variable is declared, it can be used over and over again in your script. All variables in PHP start with a
sign symbol.
A variable name should not contain spaces. If a variable name is more than one word,
it should be separated with an underscore
($my_string),
or with capitalization
($myString)
String variables are used for values that contains characters. After we create a string we can manipulate it.
A string can be used directly in a function it can be stored in a variable
There is only one string operator in PHP. The concatenation operator(.) is used to put two string values together.
?>
The strlen() function is used to return the length of a string. Let's find the length of a string:
<?php echo strlen("Hello world!"); ?> The output of the code above will be: 12
The strpos() function is used to search for character within a string. If a match is found, this function will return the position of the first match. If no match is found, it will return FALSE. Let's see if we can find the string "world" in our string:
<?php echo strpos("Hello world!","world"); ?> The output of the code above will be:
6
Operator + * / %
++ --
Example x=2 x+2 Subtraction x=2 5-x Multiplication x=4 x*5 Division 15/5 5/2 Modulus (division remainder) 5%2 10%8 10%2 Increment x=5 x++ Decrement x=5 x--
Description Addition
Operator = += -= *= /= .= %=
Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or 5>=8 returns false equal to <= is less than or equal to 5<=8 returns true
Operator
Description
Example
&&
and
x=6 y=3 (x < 10 && y > 1) returns true x=6 y=3 (x==5 || y==5) returns false x=6 y=3 !(x==y) returns true
||
or
not
if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false if...elseif....else statement - use this statement to select one of several blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed
Syntax if (condition) code to be executed if condition is true; The following example will output "Have a nice weekend!" if the current day is Friday: <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!";
Syntax if (condition) code to be executed if condition is true; else code to be executed if condition is false;
<html> <body> <?php $d=date("D"); ?> if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!";
</body> </html>
Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false;
<html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!";
?>
</body> </html>
Syntax
switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; }
<html> <body>
<?php switch ($x) { case 1: echo "Number 1"; break; ?> case 2: break; case 3: break; default: } echo "Number 2";
</body> </html>
What is an Array?
An array is a special variable, which can hold more than one value, at a time.
Numeric array - An array with a numeric index Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays
A numeric array stores each array element with a numeric index. There are two methods to create a numeric array.
1. automatically assigned (the index starts at 0):
$cars=array("Saab","Volvo","BMW","Toyota");
referring to the array name and index: <?php $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars."; ?>
An associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it. Example 1 In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2 This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";
<?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?>
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.
fox"=>array("Glenn"), "Brown"=>array("Cleveland","Loretta") );
while
loops through a block of code while a specified condition is true
do...while
loops through a block of code once, and then repeats the loop as long as a specified condition is true
for
loops through a block of code a specified number of times
foreach
loops through a block of code for each element in an array
The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?>
</body> </html>
Output:
is is is is is
1 2 3 4 5
The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true. Syntax do { code to be executed; } while (condition);
<html> <body> <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> </body> </html>
Output: The number The number The number The number The number chapter. is is is is is 2 3 4 5 6 The for loop and the foreach loop will be explained in the next
The for loop is used when you know in advance how many times the script should run. Syntax
<html> <body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; }
?>
</body> </html> Output: The number The number The number The number The number
is is is is is
1 2 3 4 5
The foreach loop is used to loop through arrays. Syntax foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
<html> <body> <?php $x=array("one","two","three"); ?> foreach ($x as $value) { echo $value . "<br />"; }
The real power of PHP comes from its functions. In PHP, more than 700 built-in functions.
A function will be executed by a call to the function. Syntax function functionName() { code to be executed; } Give the function a name that reflects what the function does The function name can start with a letter or underscore (not a number)
<html> <body> <?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is "; writeName();
?>
Example 1 The following example will write different first names, but equal last name: <html> <body>
<?php function writeName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale");
?>
</body> </html> Output: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes. My brother's name is Stale Refsnes.
<?php function writeName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br />"; } echo "My name is "; writeName("Kai Jim","."); echo "My sister's name is "; writeName("Hege","!"); echo "My brother's name is "; writeName("Stle","?");
My name is Kai Jim Refsnes. My sister's name is Hege Refsnes! My brother's name is Stle Refsnes?
To let a function return a value, use the return statement. Example <html> <body>
<?php
?>
The most important thing to notice when dealing with HTML forms. PHP is that any form element in an HTML page will automatically be available to your PHP scripts.
Example The example below contains an HTML form with two input fields and a submit button: <html> <body> <f orm ac t i on=" w c om php" el e. m hod=" pos t " > et Name: <input type="text" name="fname" / > Age: <input type="text" name="age" / > <input type="submit" / > </f orm > </ body> </ html> When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "welcome.php":
<html> <body> Welcome <?php echo $_POST["fname"]; ?>!<br/> You are <?php echo $_POST["age"]; ?> years old. </body> </html> Output W elcome John! You are 28 years old.
Description Data about the currently running server. Data about the clients environment. Data posted to the server by the get method. Data posted to the server by the post method. Data contained in cookies on the clients computer. Array containing all global variables. Some useful global arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- env.php -->
<!-- Program to display environment variables --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Environment Variables</title> </head> <body> <table border = "0" cellpadding = "2" cellspacing = "0" width = "100%"> <?php // print the key and value for each element // in the $_ENV array foreach ( $_ENV as $key => $value ) print( "<tr><td bgcolor = \"#11bbff\"> <strong>$key</strong></td> <td>$value</td></tr>" ); ?> </table> </body>
26 </html>
The built-in $_GET function. Used to collect values from a form sent with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send (max. 100 characters).
<form action="welcome.php" method="get"> Name:<input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> The URL sent to the server could look something like this: http://www.w3schools.com/welcome.php? fname=Peter&age=37 The "welcome.php" Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!
Note: should not be used when sending passwords or other sensitive information!
However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
Note: not suitable for large variable values; the value cannot exceed 100 characters.
The built-in $_POST function. used to collect values from a form sent with method="post". Information sent from a form with the POST method is invisible to others. Has no limits on the amount of information to send.
Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
<form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> The URL will look like this: http://www.w3schools.com/welcome.php Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old.
Information sent from a form with the POST method is invisible. Has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST function can be used to collect form data sent with both the GET and POST methods. Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old.
Server side programming Server software IIS -ASP Apache --PHP Tomcat --JSP Server technologies
Macromedia ColdFusion Microsoft ASP.NET Microsoft Active Server Pages (ASP) Sun JavaServer Pages (JSP) PHP: Hypertext Preprocessor (PHP) Server executes the script and send the HTML results to the clients browser
What is PHP PHP (Hypertext Preprocessor") is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.
How we include PHP code 1. <?php echo("if you want to serve XHTML or XML documents, do like this\n"); ?> is the preferred method, as it allows the use of PHP in XML-conformant code such as XHTML. 2. <? echo ("this is the simplest, an SGML processing instruction\n"); ?>
3. <script language="php"> echo ("some editors (like FrontPage) don't like processing instructions"); </script> 4. <% echo ("You may optionally use ASP-style tags"); %>
<html> <head> <title>Example</title> </head> <body> <?php echo This is my first PHP script!"; ?> </body> </html> What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server. If you were to have a script similar to the above on your server, the client would receive the results of running that script, with no way of determining what the underlying code may be
Five important characteristics of PHP Familiarity Simplicity Efficiency Security Flexibility its free!
Familiarity Many of the languages constructs are borrowed from C and Perl, and in many cases PHP code is almost indistinguishable from that found in the typical C or Pascal program. This minimizes the learning curve considerably. Simplicity A PHP script can consist of 10,000 lines or one line: whatever you need to get the job done. There is no need to include libraries, special compilation directives, or anything of the sort. The PHP begins executing the code included between (<?) and ?>) tags
Efficiency Efficiency is an extremely important consideration for working in a multi user environment such as the WWW. resource allocation mechanisms and more pronounced support for object-oriented programming, in addition to session management features and also eliminate unnecessary memory allocation.
Security PHP provides developers and administrators with a flexible and efficient set of security safeguards. Two types system level and application level. System-Level Security Safeguards PHP furnishes a number of security mechanisms that administrators can manipulate, providing for the maximum amount of freedom and security when PHP is properly configured. (refer programmers Introduction to PHP4 Page 409)
How to embed PHP code <? $site_title = "PHP code "; $bg_color = "cian"; $user_name = "Amara"; ?> <html><head> <title><? print $site_title; ?></title> </head> <body bgcolor="<? print $bg_color; ?>" > <? print " Today's date is ".date("F d, Y")." <br> Welcome , $user_name! <br> "; ?> </body></html>
When PHP parses a file, it simply passes the text of the file through until it encounters one of the special tags which tell it to start interpreting the text as PHP code. The parser then executes all the code it finds, until it runs into a PHP closing tag, which tells the parser to just start passing the text through again. This is the mechanism which allows you to embed PHP code inside HTML: everything outside the PHP tags is left utterly alone, while everything inside is parsed as code.
Terminate each statement with a semicolon. Commnets // This is a one-line c++ style comment /* This is a multi line comment yet another line of comment */ Eg. <?php echo "This is a test"; // This is a one-line comment /* This is a multi line comment yet another line of comment */ echo multi line test"; ?>
Data types in PHP Four scalar types: boolean integer float (floating-point number, aka 'double') string Two compound types: array object
Boolean Syntax To specify a boolean literal, use either the keyword TRUE or FALSE. Both are caseinsensitive. <?php $res = TRUE; If(res): echo it is boolean; endif; ?>
Integer type An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}. The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). (octal started with 0, hexadecimal started with 0x ) Floating point numbers Floating point numbers ("doubles" or "real numbers") can be specified using any of the following syntaxes: copy to clipboard <?php $a = 1.234; $b = 1.2e3; $c = 7E-10; ?>
String Values A string is a group of characters that are represented as a single entity but can also be examined on a character-by-character basis. String Assignments Strings can be delimited in two ways, using either double quotation marks () or single quotation marks (). There are two fundamental differences between the two methods. First, variables in a double-quoted string will be replaced with their respective values, whereas the single-quoted strings will be interpreted exactly as it is, even if variables are enclosed in the string.
eg. $name="Jaja"; $name='jaya'; Both are same but .. echo "myname is $name"."<br>"; echo 'myname is $name'."<br>"; Rsults are different Myname is Jaya mynameis$name while a double quoted string recognizes all available delimiters, a single-quoted string recognizes only the delimiters \\ and \. $double_list = "item1\nitem2\nitem3"; $single_list = 'item1\nitem2\nitem3'; (take it as a character)
Strings can be accessed on a character-bycharacter basis, much like a sequentially indexed array. $sequence_number = "04efgh"; $letter = $sequence_number[4]; echo $letter .resulted g Variable Declaration A variable is a named memory location that contains data that may be manipulated throughout the execution of the program. A variable always begins with a dollar sign, $. Eg. $name
Variable Scope Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types: Local variables Function parameters Global variables Static variables Local Variables A variable declared in a function is considered local; that is, it can be referenced solely in that function.
Function parameters Function parameters are declared after the function name and inside parentheses. They are declared much like a typical variable would be: function myfunc ($value) { $value = $value * 10; return $value; }
Global Variables In contrast to local variables, a global variable can be accessed in any part of the program. by placing the keyword GLOBAL in front of the variable that should be recognized as global. <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?>
An alternative method for declaring a variable to be global is to use PHPs Static variable a static variable will not lose its value when the function exits and will still hold that value should the function be called again. You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.
Syntax :STATIC $somevar; function keep_track() { STATIC $count = 0; $count++; print $count; print "<br>"; } keep_track(); keep_track(); keep_track(); Output is 1 2 3
Cast Operators for Variables CAST OPERATORS CONVERSION (int) or (integer) Integer (real) or (double) or (float) Double (string) String (array) Array (object) Object $variable1 = 13; // $variable1 is assigned the integer value 13. $variable2 = (double) $variable1; // $variable2 is assigned the value 13.0
$variable1 = 4.0; $variable2 = 5; $variable3 = (int) $variable1 + $variable2; // $variable3 = 9 It is also possible to cast a string or other data type to be a member of an array. The variable being cast simply becomes the first element of the array: $variable1 = 1114; $array1 = (array) $variable1; print $array1[0]; // The value 1114 is printed.
Constants A constant is essentially a value that cannot be modified throughout the execution of a program. constants are defined using the define() function. define("PI", "3.141592"); And subsequently used in the following listing: print "The value of pi is". PI.".<br>"; $pi2 = 2 * PI;
Assignment Operators $a = 5; Assignment $a equals 5 $a += 5; Addition-assignment $a equals $a plus 5 $a *= 5; Multiplication-assignment $a equals $a multiplied by 5 $a /= 5; Division-assignment $a equals $a divided by 5 $a .= 5; Concatenation-assignment $a equals $a concatenated with 5
String Operators $a = abc.def; Concatenation $a equals the concatenation of the two strings $a and $b $a .= ghijkl; Concatenation-assignment $a equals its current value concatenated with ghijkl. Output is abcdefghijk
Logical Operators $a && $b - True if both $a and $b are true. $a AND $b - True if both $a and $b are true. $a || $b Or True if either $a or $b are true. $a OR $b Or True if either $a or $b are true. ! $a Not True if $a is not true. NOT $a Not True if $a is not true. $a XOR $b Exclusive or True if only $a or only $b is true.
Equality Operators EXAMPLE LABEL OUTCOME $a == $b Is equal to True if $a and $b are equivalent. $a != $b Is not equal to True if $a is not equal to $b $a === $b Is identical to True if $a and $b are equivalent and $a and =$b have the same type.
Arrays An array in PHP is actually an ordered map. A map is a type that maps values to keys.
A single-dimension array can be created as follows: Arrays $meat[0] = "chicken"; An array in PHP is actually an ordered map. A map is a type that maps values to keys. $meat[1] = beef"; $meat[2] = mutton"; If you execute this command: print $meat[1];
Single-Dimension Associative Arrays Associative arrays are particularly convenient when it makes more sense to map an array using words rather than integers.
An array can be created by the array() languageconstruct. It takes a certain number of commaseparated key => value pairs. <?php $arr = array(name" => "Sunil" , "pass" => true ,"marks" => 50); echo 'Name ' .$arr[name"]. '<br>'; echo 'pass '. $arr["pass"]. '<br>' ; echo 'marks '. $arr["marks"] ; ?>
If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
Multidimensional Indexed Arrays Multidimensional indexed arrays function much like their single-dimension counterparts, except that more than one index array is used to specify an element. There is no limit as to the dimension size, although it is unlikely that anything beyond three dimensions would be used in most applications. The general syntax of a multidimensional array is: $name[index1] [index2]..[indexN]; $student = $tudrec[5][4];
Multidimensional Associative Arrays Multidimensional associative arrays are also possible (and quite useful) in PHP. $stud[batch1"] [sad"] = 55; $stud[batch3"] [web"] = 60; $stud[batch2"] [bio"] = 40; print $stud[batch1][sad];
Control Structures Selection if (expression): statement block; endif; If else if (expression) { statement block } else { statement block; endif; }
elseif The elseif statement provides another level of evaluation for the if control structure, adding depth to the number of expressions that can be evaluated: if (expression) { statement block } elseif (expression) { statement block }
while The while structure provides a way to repetitively loop through a statement block. The number of times the statement block is executed depends on the total times the expression evaluates to true. The general form of the while loop is: while (expression) : statement block endwhile;
$n = 1; $ncopy = $n; $factorial = 1; // set initial factorial value while ($n >1 0) : $sum = $n + sum; $n++; endwhile; print "The sum is $sum.";
do : statement block while (expression); for ($i = 10; $i <= 100; $i+=10) : print "\$i = $i <br>"; endfor; $x = 5; for (; ; $x += 2) : print " $x "; if ($x == 15) : break; // break out of this for loop endif; endfor; (output will be 5 7 9 11 13 15)
foreach The foreach construct is a variation of the for structure, included in the language. There are two general forms of the foreach statement, each having its own specific purpose: Expressions, Operators, and Control Structures 1 foreach (array_expression as $value) { statement } foreach (array_expression as $key => $value) { statement }
1. $menu = array("pasta", "steak", "potatoes", "fish", "fries"); foreach ($menu as $item) { print "$item <BR>"; } 2. <? $submarks = array ( "phy" => 55, "com" => 47, "che" => 32 ); foreach ($submarks as $i => $item_count) { print " sub marks of $i $item_count "; } ?>
switch The switch statement functions much like an if statement, testing an expression value against a list of potential matches. It is particularly useful when you need to compare many values, as the switch statement provides clean and compact code. The t of the switch statement is: switch (expression) { case (condition) : statement block case (condition) : statement block ... default : statement block }
$user_input = "recipes"; // assume $user_input is passed in to the script switch ($user_input) : case("search") : print "Let's perform a search!"; break; case("dictionary") : print "What word would you like to look up?"; break; case("recipes") : print "Here is a list of recipes"; break; default: print "Here is the menu"; break; endswitch;
Functions Variable Functions An interesting capability of PHP is the possibility to execute variable functions. A variable function is a dynamic call to a function whose name is determined at the time of execution. Although not necessary in most Web applications, variable functions can significantly reduce code size and complexity, often eliminating unnecessary if conditional statements.
<? function computer() { print "I do computer."; } function phy() { print "i do physics."; } $subject = "phy"; // execute the variable function $subject(); ?> Variablefunc.php
String-Specific Functions chop() The chop() function returns a string minus any ending whitespace and newlines. Its syntax is: string chop (string str) This example uses chop() to remove unnecessary newlines: $header = "Table of Contents:\n\n"; $header = chop($header); // $header = "Table of Contents"
trim() The trim() function will remove all whitespace from both the left and right sides of string, returning the resulting string. syntax string trim (string string) It will also remove the special characters \n, \r, \t, \v and \0. Finding Out the Length of a String You can determine the length of a string through use of the strlen() function. This function returns the length of a string $length=strlen (string str)
Comparing Two Strings String comparison is arguably one of the most important features of the string handling two strings can be compared for equality PHP provides four functions for performing this task: strcmp() strcasecmp() strspn() strcspn()
strcmp() The strcmp() function performs a case-sensitive comparison of two strings. syntax int strcmp (string string1, string string2) On completion of the comparison, strcmp() will return one of three possible values: 0 if string1 and string2 are equal < 0 if string1 is less than string2 > 0 if string2 is less than string1 $string1=nimal,$string2 = nimal"; if ((strcmp($string1, $string2)) == 0) : print "Strings are equivalent!"; endif; Strcmp.php
strcasecmp() The strcasecmp() function operates exactly like strcmp(), except that its comparison is case insensitive. syntax int strcasecmp (string string1, string string2) The following example compares two equivalent string values: $string1 = "butter"; $string2 = "Butter"; if ((strcasecmp($string1, $string2)) == 0) : print "Strings are equivalent!"; endif; // If statement will evaluate to true
strcspn() The strcspn() function returns the length of the first segment in string1 containing characters not in string2. Its syntax is: $password = "12345"; if (strcspn($password, "1234567890") ==strlen($password)) : print "Password cannot consist only numbers!"; endif; Strcspn.php
strstr() The strstr() function returns the remainder of string beginning at the first occurrence. syntax string strstr (string string, string occurrence) This example uses strstr() to return the domain name of a URL: $url = "http://www.apress.com"; $domain = strstr($url, "."); // $domain = ".apress.com"
substr() The substr() function returns the part of the string between the start and start+length parameters. syntax string substr (string string, int start[,int length] ) $car = laserFord"; $yr = substr($car, 0, 4); // $yr = laser" Substr.php
Converting a String into Uppercase and Lowercase Letters Four functions are available to aid you in accomplishing this task: strtolower() strtoupper() ucfirst() ucwords()
The strtolower() function does exactly what you would expect it to: it converts a string to all lowercase letters. Its syntax is: string strtolower (string string) Non alphabetical characters are not affected. The following example uses strtolower() to convert a string to all lowercase letters: $sentence = "COOKING and PROGRAMMING PHP are my TWO favorite pastimes!"; $sentence = strtolower($sentence);
ucfirst() The ucfirst() function capitalizes the first letter of a string, provided that it is alphabetical. Its syntax is: string ucfirst (string string) $sentence = programming and analisyss!"; $sentence = ucfirst($sentence); == Programming and analisyss!";
<? $n=$_POST["name"]; $age=$_POST["age"]; print "your entered name is $n <br>"; print "entered age is $age<br>"; print "good luck"; ?>
Files Opening and Closing I/O Before you can perform any I/O operation on a file, you must open it using the fopen() function. fopen() The fopen() function opens a file, assuming that it exists, and returns an integer, better known as a file handle. syntax $handler= fopen (file name(string) ,mode(string)
MODE MEANING r Read only. The file pointer is placed at the beginning of the file. r+ Reading and writing. The file pointer is placed at the beginning of the file. w Write only. The file pointer is placed at the beginning of the file, and the file contents are erased. If the file does not exist, create it. w+ Reading and writing. The file pointer is placed at the beginning of the file, and the file contents are erased. If the file does not exist, create it. a (append)Write only. The file pointer is placed at the end of the file. If the file does not exist, create it. a+ Reading and writing. The file pointer is placed at the end of the file. If the file does not exist, create it.
fwrite() The fwrite() function will simply write the contents of string to the file specified by filepointer. syntax fwrite (file handler, string string) Read file $fh = fopen('pastry.txt', "r") or die("Can't open file!"); $file = fread($fh, filesize($fh)); print $file; fclose($fh);
<? $file = "dat.txt"; if (is_file($file)) : print "The file $file is valid and exists!"; $data = "this is record"; $fh= fopen("dat.txt","w"); fwrite($fh, $data); else : print "Either $file does not exist or it is not a valid file!"; endif; fclose($fh); ?>
<? $file = "dat.txt"; if (is_file($file)) : print "The file $file is valid and exists!<br>"; $fh= fopen("dat.txt","r"); $success = fread($fh, 2040); print "read ok<br>"; print $success."<br>"; else : print "Either $file does not exist or it is not a valid file!"; endif; fclose($fh); ?>
$fh = fopen('pastry.txt', "r") or die("Can't open file!"); $file = fread($fh, filesize($fh)); print $file; fclose($fh); By using filesize() to retrieve the byte size of pastry.txt, you ensure that fread() will read in the entire contents of the file.
File related functions file_exists() The file_exists() function will ensure that file exists, returning true if it does, and false otherwise. $filename = "userdata.txt"; if (! file_exists ($filename)) : print "File $filename does not exist!"; endif;
is_file() The is_file() function will return true if file exists and is a readable/writable file. Essentially, is_file() is a bullet-proof version of file_exists(), verifying not only the files existence but also whether it can be read from or written to: bool is_file (string file) This example shows how to verify the existence and validity of a file: $file = "somefile.txt"; if (is_file($file)) : print "The file $file is valid and exists!"; else : print "Either $file does not exist or it is not a valid file!"; endif;
filesize() The filesize() function will return the size, in bytes, of the file designated by filename, or false should an error occur. Its syntax is: int filesize (string filename) Assume that you want to know the size of a file named pastry.txt. You can use filesize() to retrieve this information: $fs = filesize("pastry.txt"); print "Pastry.txt is $fs bytes.";
fputs() The fputs() function is an alias to fwrite() and is implemented in exactly the same way. Its syntax is: int fputs (int filepointer, string string [, int length]) fgets() The fgets() function returns a string read from a file pointed to by the file pointer. The file pointer must point to an opened file that is readable fgets (int filepointer, int length)
Reading will stop when one of the following conditions has been met: Length: 1 byte is read. A newline is read (returned with the string). An end of file (EOF) is read. $fh = fopen("pastry.txt", "r"); while (! feof($fh)) : $line = fgets($fh, 4096); print $line."<br>"; endwhile; fclose($fh);
<? $file = "dat.txt"; if (is_file($file)) : //print "The file $file is valid and exists!<br>"; $fh= fopen("dat.txt","r"); $success = fread($fh, 1080); $success=$success+1; fclose($fh); $fh= fopen("dat.txt","w"); fwrite ($fh,$success); print "number of hits = $success <br>"; print "write ok"; else : print "Either $file does not exist or it is not a valid file!"; endif; fclose($fh); ?>
Database-PHP The general order of events that take place during the MySQL server communications process: 1. Establish a connection with the MySQL server. If the connection attempt fails, display an appropriate message and exit process. 2. Select a database on the MySQL server. If you cannot select the database, display an appropriate message and exit process. Its possible to simultaneously have several databases open for querying. 3. Perform necessary queries on selected database(s). 4. Once the querying is complete, close the database server connection.
mysql_connect() The function mysql_connect() is used to establish an initial connection with the MySQL server. Once a successful connection is established, a database residing on that server can be selected. An example connection call follows: @mysql_connect("localhost", username", password") or die("Could not connect to MySQL server!"); mysql_select_db() Once a successful connection is established with the MySQL server, a database residing on that server can be selected.
@mysql_select_db("company") or die("Could not select company database!"); mysql_close() Once you have finished querying the MySQL server, you should close the connection. Example <? @mysql_connect("localhost", user", amara") or die("Could not connect to MySQL server!"); @mysql_select_db("company") or die("Could not select company database!"); print "You're connected to a MySQL database!"; mysql_close(); ?>
mysql_query() The function mysql_query() provides the functional interface from which a database can be queried. int mysql_query (string query ) The input parameter query corresponds to an SQL query. If you are concerned that you are using up too much memory when making various query calls, call the predefined PHP function mysql_free_result(). This function, which takes as input the result_id returned from mysql_query(), will free up all memory associated with that query call.
mysql_query() The function mysql_query() provides the functional interface from which a database can be queried. <? @mysql_connect("localhost", root", abcd") or die("Could not connect to MySQL server!"); @mysql_select_db(student") or die("Could not select company database!"); $query = "SELECT stud_marks FROM marks WHERE name=amara; // execute the query $result = mysql_query($query); print amaras marks is ($result); mysql_close();?>
Example 2 <? @mysql_connect("localhost", root", "fabcd") or die("Could not connect to MySQL server!"); @mysql_select_db("company") or die("Could not select company database!"); // Select all rows in the products table $query = "SELECT * FROM stuent"; $result = mysql_query($query); $x = 0; print "<table>"; print "<tr><th>Product ID</th><th>Product Name</th><th>Product Price</th></tr>"; while ($x < mysql_numrows($result)) : $name = mysql_result($result, $x, 'name'); $price = mysql_result($result, $x, marks'); print "<tr>"; print "<td>$id</td><td>$name</td><td>$marks</td>"; print "</tr>"; $x++; endwhile; </table> mysql_close(); ?>
mysql_fetch_array() It is typically much more convenient to simultaneously assign an entire row to an indexed array (starting at offset 0), rather than make multiple calls to mysql_result() to assign column values. $query = "SELECT * FROM products"; $result = mysql_query($query); while ($row = mysql_fetch_array($result)) : print "<tr>\n"; print "<td>".$row["prod_id"]."</td>\n <td>".$row["prod_name"]."</td>\n <td>".$row["prod_price"]."</td>\n"; print "</tr>\n"; endwhile;
Microsoft Access and PHP how you can connect to an MS Access database using PHP. odbc_connect() Before querying an ODBC-enabled database, you must first establish a connection. odbc_connect(). $conn = new COM("ADODB.Connection") or die("Cannot start ADO"); // Microsoft Access connection string. $conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=.realpath(student.mdb"); // SQL statement to build recordset. $rs = $conn->Execute("select * from marks");
<? $conn = new COM("ADODB.Connection") or die("Cannot start ADO"); $conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=d:\phptute\student.mdb"); $rs = $conn->Execute("select * from marks"); echo "<p>Below is a list of values in the student.MDB database, Marks table.</p>"; while (!$rs->EOF) { $fv = $rs->Fields("name"); echo "Value: ".$fv->value."<br>\n"; $fa=$rs->Fields("age"); echo "Value: ".$fa->value."<br>\n"; $fad=$rs->Fields("add"); echo "Value: ".$fad->value."<br>\n"; $fmk=$rs->Fields("marks"); echo "Value: ".$fmk->value."<br>\n"; $rs->MoveNext(); } $rs->Close();
$conn = new COM("ADODB.Connection") or die("Cannot start ADO"); $conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=d:\phptute\student.mdb"); $conn->Execute(insert into marks values ($nm,$add,$age,$marks);
$conn = new COM("ADODB.Connection") or die("Cannot start ADO"); $conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=.realpath(student.mdb"); $conn->Execute(update marks set marks=$mks where name=$na);
Cookies What Is a Cookie? A cookie is nothing more than a small parcel of information that is sent by a Web server and stored on a client browser. Cookie Components Interestingly, other pieces of information are also stored in the cookie, enabling the developer to tailor its usage in terms of domain, time frame, path, and security.
nameThe cookie name is a mandatory parameter because the name is the parameter from which the cookie is referenced. valueA cookie value is simply a piece of data mapped to the cookie name. expiration dateThis date defines the lifetime of the cookie. domainThis is the domain that both created and can read the cookie. pathThe path setting specifies the URL path from which the cookie is valid. securityThis determines whether or not the cookie can be retrieved in a nonsecure setting.
The function setcookie() stores a cookie on a users machine. $uid = abcs"; $cookie_set = setcookie ("uid", $value, time()+3600, "/", ".rusl.lk", 0); After reloading or navigating to any subsequent page, the variable $uid becomes available, producing the user id abcs This cookie will expire (thus be rendered unusable) exactly one hour (3600 seconds) after it has been sent. The cookie is available for retrieval in all directories on the server. This cookie is only accessible via the rusl.lk domain. This cookie is accessible via a nonsecured protocol.
<? if(isset($unic_id)): print $unic_id; else: $uniq_id="aaa"; setcookie ("myfirst", $uniq_id, time()+2592000); print "ok set"; endif; ?>
Example <?php $Month = 2592000 + time(); //this adds 30 days to the current time setcookie(AboutVisit, date("Y-m-d H:i:s"), $Month); ?> <?php if(isset($_COOKIE['AboutVisit'])) { $last = $_COOKIE['AboutVisit']; echo "Welcome back! <br> You last visited on ". $last; } else { echo "Welcome to our site!"; } ?>
Session Handling A session is best defined as the period of time beginning when a user enters your site and ending when the user exits. The first concept that you need to know is that a session is initiated with the function session_start() The function session_start() is twofold in purpose. Once called, it checks to see if the user has already started a session, and if the user has not, it starts one.
session_destroy() The function session_destroy() will destroy all persistent data corresponding to the current user session. session_id() The function session_id() returns the users SID originally created by session_start(). <? session_start (); print "Your session identification number is ".session_id(); session_destroy(); ?>
creating your own session variables using The function session_ register() The function session_register() registers one or more variable names with the users current session. <?php session_start(); $my_session_variable = username"; session_register("my_session_variable"); ?> <?php session_start(); print "Value of 'my_session_variable': $my_session_variable"; ?>
<?php session_start(); ($_SESSION['count']) ? $_SESSION['count']++ : $_SESSION['count'] = 1; ?> <html> <head> <title>Stuff by tedd</title> </head> <body> <h1>tedd's session stuff (page 2)</h1> <hr> <h3>PHPSESSID = <?php echo session_id(); ?></h3> <hr> <h2>You have been here <?php echo( $_SESSION['count'] ); ?> times in this session.</h2> <a href="session1.php?<?php echo( SID ); ?>">Previous page</a> </body> </html> </html>
<?php session_start(); ?> <html> <head> <title>Stuff by tedd</title> </head> <body> <h1>tedd's session stuff (page 1)</h1> <hr> <h3>PHPSESSID = <?php echo session_id(); ?></h3> <hr> <h2>Click the next page and see numbr of visits during this visit.</h2> <a href="session2.php?<?php echo( SID ); ?>">Next page</a> </body> </html>
Applets import javax.swing.JApplet; import java.awt.Graphics; public class HelloWorld extends JApplet { public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); g.drawString("Hello world!", 5, 15); } }
<Html> <Head> <Title>Java Example</Title> </Head> <Body> This is my page<br> Below you see an applet<br> <br> <Applet Code=HelloWorld.class" width=200 Height=100> </Applet> </Body> </Html>
Width=n n=Width of applet -------- Width=200 Height=n . n=Height of applet ------ Height=100 Codebase .. Library where the applet is stored. If the applet is in same directory as your page this can be omitted. Codebase="applets/"
Alt="Text
Align= Left Right,Top,Texttop Middle,Absmiddle Baseline,Bottom Absbottom
alt="Menu Applet
Justifies the applet according to the text and images surrounding it.
Align=Right
V/hspace=n
V/Hspace=20
GOOD LUCK
By Pramudith Kandambi
The PHP date() function is used to format a time and/or date. The PHP date() function formats a timestamp to a more readable date and time. A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred. Syntax date(format,timestamp)
Description Required. Specifies the format of the timestamp Optional. Specifies a timestamp. Default is the current date and time
Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting:
<?php echo date("Y/m/d") . "<br />"; echo date("Y.m.d") . "<br />"; echo date("Y-m-d") ?> The output of the code above could be something like this:
2009/05/11 2009.05.11 2009-05-11
The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used. The mktime() function returns the timestamp for a date. Syntax for mktime()
mktime(hour,minute,second,month,day,year,is_dst)
<?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?> The output of the code above could be something like this:
Tomorrow is 2009/05/12
You can insert the content of one PHP file into another PHP file before the server executes it, with the
include() require() .
include() generates a warning, but the script will continue execution require() generates a fatal error, and the script will stop These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages.
The include() function takes all the content in a specified file and includes it in the current file. If an error occurs, the include() function generates a warning, but the script will continue execution.
Example 1 Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function: <html> <body> <?php include("header.php"); ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html>
The require() function is identical to include(), except that it handles errors differently
Now, let's run the same example with the require() function. <html> <body>
The echo statement is not executed, because the script execution stopped after the fatal error. It is recommended to use the require() function instead of include(), because scripts should not continue after an error.
The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:
<html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html> Note: If the fopen() function is unable to open the specified file, it returns 0 (false).
Databases
Store and maintain data MySQL is a free database product PHP supports many database operations
Access databases from Web pages
10
12
The free MySQL database is very often used with PHP. Before you can access data in a database, you must create a connection to the database.
Description Optional. Specifies the server to connect to. Default value is "localhost:3306" Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process Optional. Specifies the password to log in with. Default is ""
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?>
<?php
?>
mysql_close($con);
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')"); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33')"); mysql_close($con); ?>
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con); ?>
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons WHERE FirstName='Peter'"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } ?>
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons ORDER BY age");
while($row = mysql_fetch_array($result)) { echo $row['FirstName']; echo " " . $row['LastName']; echo " " . $row['Age']; echo "<br />"; } mysql_close($con); ?>
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
Cookies
Store information on client computer Track preferences and other information Stored as text files on hard drive Never store sensitive information, such as credit card numbers, in a cookie
Security risk
setcookie function
22
Note: The setcookie() function must appear BEFORE the <html> tag. Syntax setcookie(name, value, expire, path, domain);
You can also set the expiration time of the cookie in another way. It may be easier than using seconds.
<?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> <html> ..... In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).
How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page:
<?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE);
?>
<html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html>
Example: <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>
27
1 2 3 4 5 6 7 8 9 10
<?php // Fig. 26.21: cookies.php // Program to write a cookie to a client's machine extract( $_POST ); // write each form fields value to a cookie and set the // cookies expiration date setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 ); setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 ); setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );
11 ?> 12 13 14 15 16 17 18 19 20 21 22 23
Function setcookie takes the name of the cookie to be set as the first <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" argument, followed by the value to be "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> stored in the cookie. The optional third argument specifies the expiration date of <html xmlns = "http://www.w3.org/1999/xhtml"> the cookie. <head>
<title>Cookie Saved</title> </head> <body style = "font-family: arial, sans-serif"> <p>The cookie has been set with the following data:</p>
28
24 25 26 27 28 29 30 31 32 33 34 35 36 37
<!-- print each form fields value --> <br /><span style = "color: blue">Name:</span> <?php print( $NAME ) ?><br /> <span style = "color: blue">Height:</span> <?php print( $HEIGHT ) ?><br /> <span style = "color: blue">Favorite Color:</span> <span style = "color: <?php print( "$COLOR\">$COLOR" ) ?> </span><br /> <p>Click <a href = "readCookies.php">here</a> to read the saved cookie.</p> </body>
Each form fields value is printed to confirm the data that has been set as a cookie with the user.
38 </html>
Hyperlink to readCookies.php.
29
30
Reading cookies
Array foreach loop to access each element Split into key and value
31
Cookie storage
Internet Explorer
32
33
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- readCookies.php -->
<!-- Program to read cookies from the client's computer --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>Read Cookies</title></head> <body style = "font-family: arial, sans-serif"> <p> <strong> The following data is saved in a cookie on your computer. </strong> </p>
34
19 20 21 22 23 24 25 26 27 28 29 30 31 32
The foreach loop iterates through the which PHP creates array $_COOKIE $_COOKIE array andall cookie valuesand value contains prints the name indexed by iterate through array $_COOKIE and print of each cookie names. their name and value of each cookie in an XHTML table.
print( "<tr> <td bgcolor=\"#F0E68C\">$key</td> <td bgcolor=\"#FFA500\">$value</td> </tr>" );
33 </html>
35
36
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?> <html> <body> </body> </html> The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html> Output:
Pageviews=1
40
By Pramudith Kandambi
Outline Introduction HTTP Request Types System Architecture Client-Side Scripting versus Server-Side Scripting Accessing Web Servers Microsoft Internet Information Services (IIS) Microsoft Internet Information Services (IIS) 5.0 Microsoft Internet Information Services (IIS) 6.0 Apache Web Server Requesting Documents XHTML ASP.NET Perl PHP Python Web Resources
To understand a Web servers functionality. To introduce Microsoft Internet Information Services (IIS) and Apache Web server. To learn how to request documents from a Web server.
Web server
URI (Uniform Resource Identifier) Web server and client communicate with platform-independent Hypertext Transfer Protocol (HTTP)
Apache Web server Apache Software Foundation 2.0.47 7/10/03 Windows NT/2000/XP, Mac OS X, Linux and other UNIX-based platforms, experimentally supports Windows 95/98 The most popular The newest release of Currently the most IIS from Microsoft. popular Web server. Web server for Windows 2000. Included with Freeware. Included with Windows Server 2003 Windows 2000 and Windows XP. Web servers discussed in this chapter.
Request methods
Retrieve and send client form data to Web server Post data to a server-side form handler
get post
Middle tier
Applications user interface Users interact directly with the application through the client tier
Client-side scripts
Validate user input
Reduce requests needed to be passed to server Access browser Enhance Web pages with DHTML, ActiveX controls, and applets
Server-side scripts
Executed on server Generate custom response for clients Wide range of programmatic capabilities Access to server-side software that extends server functionality
10
FTP Site
HTTP Site
Used for transferring large files across the Internet Used most frequently to request documents from Web servers Sends and receives electronic mail Directory containing the documents that clients will view
11
12
13
14
Web Site Content Directory dialog of the Virtual Directory Creation Wizard.
15
16
17
18
19
Web Site Content Directory dialog of the Virtual Directory Creation Wizard.
20
21
Currently the most popular Web server Stability Efficiency Portability Open-source
22
23
24
25
26
Request ASP.NET document from IIS 5 or 6 Apache support ASP Classic but doesnt support ASP.NET
27
Launch Internet Explorer Enter the Perl documents location in the Address field
29
30
31
Request PHP documents from IIS 5 and 6 Request PHP documents from Apache
Launch Internet Explorer Enter PHP documents location in the Address field
Save PHP documents in the htdocs directory Launch Internet Explorer Enter PHP documents location in Address field
32
33
34
35
36
37
38