Escolar Documentos
Profissional Documentos
Cultura Documentos
ITM 4132
Internet and W3
By Pramudith Kandambi
Introduction
HTML/XHTML
Cascading Style Sheets (CSS)
JavaScript: Object-Based Scripting for the Web
Dynamic HTML
Web Servers
PHP: Database Programming
References:
Hardware
Physically connects the computers together
telephone lines, fiber-optic cables, routers and
gateways, and the computers themselves
Software
Enables communication and exchange of information,
by following a set of rules, called protocols
A protocol describes:
the format that a message must take
the way in which computers must exchange a
message
192.168.1.10
Class Start address Finish address
A 0.0.0.0 126.255.255.255
B 128.0.0.0 191.255.255.255
C 192.0.0.0 223.255.255.255
D 224.0.0.0 239.255.255.255
E 240.0.0.0 255.255.255.255
• The leftmost piece is the most specific part while the right part is the TLD
or Top Level Domain.
Computer on the
Internet holding
information -
Desktop remote “server”
computer -
“client”
SERVERS
Hardware + Software
Software
Protocols
CLIENTS
Hardware + Software
By Pramudith Kandambi
<html>
<head>
</head>
<body>
This is area what we view
</body>
</html>
<html>
<head>
</head>
<body>
Hello Sri Lanka
</body>
</html>
Example
Example
Example
<a href="http://www.rjt.ac.lk">This is a
link</a>
Example
Adding a slash to the start tag, like <br />, is the proper way of
closing empty elements, accepted by HTML, XHTML and
XML.
Example
The browser will remove extra spaces and extra lines when the
page is displayed.
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
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text
<s> Deprecated. Use <del> instead
<strike> Deprecated. Use <del> instead
<u> Deprecated. Use styles instead
style="background-color:yellow"
style="font-size:10px"
style="font-family:Times"
style="text-align:center"
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.
Example
<a href="http://www.w3schools.com/"
target="_blank">Visit W3Schools!</a>
An HTML Link cont..
Example:
A named anchor inside an HTML document:
Introduction
Basic HTML Tables
Intermediate HTML Tables and Formatting
Basic HTML Forms
More Complex HTML Forms
Internal Linking
Creating and Using Image Maps
meta Elements
frameset Element
Nested framesets
Web Resources
2
Objectives
3
Introduction
` Tables
` Present information
` Forms
` Collect information from visitor
` Internal linking and image maps
` Enhance Web page navigation
` Frames
` Display multiple documents in the browser
4
Basic HTML Tables
` Organize data into rows and columns
` <table> element
` Attribute border
` Specifies the table’s border width in pixels
` Attribute summary
` Describes the table’s contents
` Attribute caption
` Describes the table’s content and helps text-based
browsers interpret table data
5
Basic HTML Tables
11
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- table2.html -->
6 <!-- Intermediate table design -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Tables</title>
11 </head>
12
13 <body>
14
15 <h1>Table Example Page</h1> table2.html
16
17 <table border = "1"> (1 of 4)
18 <caption>Here is a more complex sample table.</caption>
19
20 <!-- <colgroup> and <col> tags are used to -->
21 <!-- format entire columns -->
22 <colgroup>
23 12
24 <!-- span attribute determines how many columns -->
25 <!-- the <col> tag affects -->
26 <col align = "right" span = "1" />
27 </colgroup>
28
29 <thead>
30
31 <!-- rowspans and colspans merge the specified -->
32 <!-- number of cells vertically or horizontally -->
33 <tr>
34
35 <!-- merge two rows -->
36 <th rowspan = "2">
37 <img src = "camel.gif" width = "205"
38 height = "167" alt = "Picture of a camel" />
39 </th> table2.html
40
41 <!-- merge four columns -->
(2 of 4)
42 <th colspan = "4" valign = "top">
43 <h1>Camelid comparison</h1><br />
44 <p>Approximate as of 9/2002</p>
45 </th>
46 </tr>
47 13
48 <t r vali gn = "b ott om">
49 < th># of H um ps< /th>
50 < th>I n d i g e n o u s r e g i o n </ th>
51 < th>S pit s? </ th>
52 < th>P r o d u c e s W o o l ?< /t h>
53 </ tr >
54
55 < / t h e ad >
56
57 < t b o d y>
58
59 <t r>
60 < th>C a m e l s ( b a c t r i a n ) </ th>
61 < td>2 </t d>
62 < td>A f r i c a / A s i a </td >
63 < td>Y es< /t d>
64 < td>Y es< /t d>
table2.html
65 </ tr > (3 of 4)
66
67 <t r>
68 < th>L lam as </ th>
69 < td>1 </t d>
70 < td>A nde s Mo unt ains < / t d >
71 < td>Y es< /t d>
72 14 < td>Y es< /t d>
73 </tr>
74
75 </tbody>
76
77 </table>
78
79 </body>
80 </html>
15
Basic HTML Forms
` Element <form>
` Attribute method
` Specifies how the form’s data is sent to Web server
` method = “post”
Appends form data to the browser request
` 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 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- form.html -->
6 <!-- Form Design Example 1 -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Forms</title>
11 </head>
12
13 <body>
14
15 <h1>Feedback Form</h1>
16
17 <p>Please fill out this form to help form.html
18 us improve our site.</p>
19
(1 of 3)
20 <!-- this tag starts the form, gives the -->
21 <!-- method of sending information and the -->
22 <!-- location of form scripts -->
23 <form method = "post" action = "/cgi-bin/formmail">
24
17
25 <p>
26 <!-- hidden inputs contain non-visual -->
27 <!-- information -->
28 <input type = "hidden" name = "recipient"
29 value = "deitel@deitel.com" />
30 <input type = "hidden" name = "subject"
31 value = "Feedback Form" />
32 <input type = "hidden" name = "redirect"
33 value = "main.html" />
34 </p>
35
36 <!-- <input type = "text"> inserts a text box -->
37 <p><label>Name:
38 <input name = "name" type = "text" size = "25"
39 maxlength = "30" />
40 </label></p>
41
42 <p> form.html
43 <!-- input types "submit" and "reset" insert -->
44 <!-- buttons for submitting and clearing the (2 of 3)
-->
45 <!-- form's contents -->
46 <input type = "submit" value =
47 "Submit Your Entries" />
48 <input type = "reset" value =
49 "Clear Your Entries" />
50 </p>
18
51
52 </form>
53
54 </body>
55 </html>
19
More Complex HTML Forms
` Element <textarea>
` Inserts a multiline text box (text area)
` Attribute rows
` Specifies the number of rows
` 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 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- form2.html -->
6 <!-- Form Design Example 2 -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Forms</title>
11 </head>
12
13 <body>
14
15 <h1>Feedback Form</h1> form2.html
16
17 <p>Please fill out this form to help
(1 of 4)
18 us improve our site.</p>
19
20 <form method = "post" action = "/cgi-bin/formmail">
21
21
22 <p>
23 <input type = "hidden" name = "recipient"
24 value = "deitel@deitel.com" />
25 <input type = "hidden" name = "subject"
26 value = "Feedback Form" />
27 <input type = "hidden" name = "redirect"
28 value = "main.html" />
29 </p>
30
31 <p><label>Name:
32 <input name = "name" type = "text" size = "25" />
33 </label></p>
34
35 <!-- <textarea> creates a multiline textbox --> form2.html
<p><label>Comments:<br />
36
(2 of 4)
37 <textarea name = "comments" rows = "4" cols = "36">
38 Enter your comments here.
39 </textarea>
40 </label></p>
41
22
42 <!-- <input type = "password"> inserts a -->
43 <!-- textbox whose display is masked with -->
44 <!-- asterisk characters -->
45 <p><label>E-mail Address:
46 <input name = "email" type = "password"
47 size = "25" />
48 </label></p>
49
50 <p>
51 <strong>Things you liked:</strong><br />
52
53 <label>Site design
54 <input name = "thingsliked" type = "checkbox"
55 value = "Design" /></label>
56
57 <label>Links
58 <input name = "thingsliked" type = "checkbox"
59 value = "Links" /></label> form2.html
60
61 <label>Ease of use
(3 of 4)
62 <input name = "thingsliked" type = "checkbox"
63 value = "Ease" /></label>
64
65 <label>Images
66 <input name = "thingsliked" type = "checkbox"
67 value = "Images" /></label>
23
68
69 <label>Source code
70 <input name = "thingsliked" type = "checkbox"
71 value = "Code" /></label>
72 </p>
73
74 <p>
75 <input type = "submit" value =
76 "Submit Your Entries" />
77 <input type = "reset" value =
78 "Clear Your Entries" />
79 </p> form2.html
80
(4 of 4)
81 </form>
82
83 </body>
84 </html>
24
25
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- form3.html -->
6 <!-- Form Design Example 3 -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Forms</title>
11 </head>
12
13 <body>
14
15 <h1>Feedback Form</h1>
16
<p>Please fill out this form to help
17
18 us improve our site.</p>
form3.html
19
20 <form method = "post" action = "/cgi-bin/formmail">
(1 of 6)
21
22 <p>
23 <input type = "hidden" name = "recipient"
24 value = "deitel@deitel.com" />
25 <input type = "hidden" name = "subject"
26
26 value = "Feedback Form" />
27 <input type = "hidden" name = "redirect"
28 value = "main.html" />
29 </p>
30
31 <p><label>Name:
32 <input name = "name" type = "text" size = "25" />
33 </label></p>
34
35 <p><label>Comments:<br />
36 <textarea name = "comments" rows = "4"
37 cols = "36"></textarea>
38 </label></p>
39
40 <p><label>E-mail Address:
41 <input name = "email" type = "password"
42 size = "25" /></label></p> form3.html
43
44 <p> (2 of 6)
45 <strong>Things you liked:</strong><br />
46
47 <label>Site design
48 <input name = "thingsliked" type = "checkbox"
49 value = "Design" /></label>
50
27
51 <l ab el>L ink s
52 < inpu t n ame = " thin gsli ked " ty pe = "c heck box "
53 va lue = " Lin ks" /></ lab el>
54
55 <l ab el>E ase of use
56 < inpu t n ame = " thin gsli ked " ty pe = "c heck box "
57 va lue = " Eas e" / ></l abe l>
58
59 <l ab el>I mag es
60 < inpu t n ame = " thin gsli ked " ty pe = "c heck box "
61 va lue = " Ima ges" />< /la bel>
62
63 <l ab el>S our ce c ode
64 < inpu t n ame = " thin gsli ked " ty pe = "c heck box "
65 va lue = " Cod e" / ></l abe l>
66
67
</p>
form3.html
68 <! -- <i nput ty pe = "r adio " /> cr eate s a rad io (3 of 6)
-->
69 <! -- bu tton . T he d iff eren ce b etw een rad io b utto ns -->
70 <! -- an d ch eck boxe s i s th at o nly one ra dio butt on -->
71 <! -- in a g rou p ca n b e se lect ed. -->
72 <p >
73 <s tr ong>How did yo u ge t to ou r si te? :</s tron g>< br / >
74
28
75 <label>Search engine
76 <input name = "howtosite" type = "radio"
77 value = "search engine" checked = "checked" />
78 </label>
79
80 <label>Links from another site
81 <input name = "howtosite" type = "radio"
82 value = "link" /></label>
83
84 <label>Deitel.com Web site
85 <input name = "howtosite" type = "radio"
86 value = "deitel.com" /></label>
87
88 <label>Reference in a book
89 <input name = "howtosite" type = "radio"
90 value = "book" /></label> form3.html
91
92 <label>Other
(4 of 6)
93 <input name = "howtosite" type = "radio"
94 value = "other" /></label>
95
96 </p>
97
29
98 <p >
99 <l ab el>R ate our si te:
100
101 <!- - t he < sel ect> tag pr esen ts a dr op-d own -->
102 <!- - l ist wit h ch oice s i ndic ate d by the -->
103 <!- - < opti on> tag s -->
104 <sel ect nam e = "ra ting ">
105 < opt ion sel ecte d = "se lect ed" >Ama zing </o ptio n>
106 < opt ion> 10< /opt ion>
107 < opt ion> 9</ opti on>
108 < opt ion> 8</ opti on>
109 < opt ion> 7</ opti on>
110 < opt ion> 6</ opti on>
111 < opt ion> 5</ opti on>
112 < opt ion> 4</ opti on>
113
114
< opt ion> 3</ opti on>
< opt ion> 2</ opti on>
form3.html
115 < opt ion> 1</ opti on> (5 of 6)
116 < opt ion> Awf ul</ opti on>
117 </se lec t>
118
119 </l abel >
120 </p >
121
30
122 <p>
123 <input type = "submit" value =
124 "Submit Your Entries" />
125 <input type = "reset" value = "Clear Your Entries" />
126 </p>
127
128 </form>
129
130 </body>
131 </html>
form3.html
(6 of 6)
31
Internal Linking
` Enables the user to jump between locations in the same
document
32
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- links.html -->
6 <!-- Internal Linking -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - List</title>
11 </head>
12
13 <body>
14
15 <!-- id attribute creates an internal hyperlink destination -->
16 <h1 id = "features">The Best Features of the Internet</h1>
17
18 <!-- an internal link's address is "#id" -->
links.html
19 (1 of 3)
<p><a href = "#bugs">Go to <em>Favorite Bugs</em></a></p>
20
21 <ul>
22 <li>You can meet people from countries
23 around the world.</li>
24
25 <li>You have access to new media as it becomes public:
33
26 <ul>
27 <li>New games</li>
28 <li>New applications
29 <ul>
30 <li>For Business</li>
31 <li>For Pleasure</li>
32 </ul>
33 </li>
34
35 <li>Around the clock news</li>
36 <li>Search Engines</li>
37 <li>Shopping</li>
38 <li>Programming
39 <ul>
40 <li>XHTML</li>
41 <li>Java</li>
42 <li>Dynamic HTML</li>
43
44
<li>Scripts</li>
<li>New languages</li>
links.html
45
46
</ul>
</li>
(2 of 3)
47 </ul>
48 </li>
49
50 <li>Links</li>
34
51 <li>Keeping in touch with old friends</li>
52 <li>It is the technology of the future!</li>
53 </ul>
54
55 <!-- id attribute creates an internal hyperlink destination -->
56 <h1 id = "bugs">My 3 Favorite Bugs</h1>
57
58 <p>
59
60 <!-- internal hyperlink to features -->
61 <a href = "#features">Go to <em>Favorite Features</em>
62 </a></p>
63
64 <ol>
65 <li>Fire Fly</li>
66 <li>Gal Ant</li>
67 <li>Roman Tic</li>
68 </ol>
69 links.html
</body>
70
71 </html>
(3 of 3)
35
36
Creating and Using Image Maps
` Designate certain areas of an image (called hotspots) as
links
` Element <map>
` Attribute id
Identifies the image map
` Element area
Defines hotspot
Attribute shape and coords
Specify the hotspot’s shape and coordinates
Rectangular ( shape = “rect” )
Polygon ( shape = “poly” )
Circle ( shape = “circle” )
37
1 <?xml version = "1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- picture.html -->
6 <!-- Creating and Using Image Maps -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Internet and WWW How to Program - Image Map
12 </title>
13 </head>
14
15 <body>
16
17 <p> picture.html
18
19 <!-- the <map> tag defines an image map --> (1 of 3)
20 <map id = "picture">
21
22 <!-- shape = "rect" indicates a rectangular -->
23 <!-- area, with coordinates for the upper-left -->
24 <!-- and lower-right corners -->
38
25 <area href = "form.html" shape = "rect"
26 coords = "2,123,54,143"
27 alt = "Go to the feedback form" />
28 <area href = "contact.html" shape = "rect"
29 coords = "126,122,198,143"
30 alt = "Go to the contact page" />
31 <area href = "main.html" shape = "rect"
32 coords = "3,7,61,25" alt = "Go to the homepage" />
33 <area href = "links.html" shape = "rect"
34 coords = "168,5,197,25"
35 alt = "Go to the links page" />
36
37 <!-- value "poly" creates a hotspot in the shape -->
38 <!-- of a polygon, defined by coords -->
39 <area shape = "poly" alt = "E-mail the Deitels"
40 coords = "162,25,154,39,158,54,169,51,183,39,161,26"
41
42
href = "mailto:deitel@deitel.com" />
picture.html
43 <!-- shape = "circle" indicates a circular --> (2 of 3)
44 <!-- area with the given center and radius -->
45 <area href = "mailto:deitel@deitel.com"
46 shape = "circle" coords = "100,36,33"
47 alt = "E-mail the Deitels" />
48 </map>
49
39
50 <!-- <img src =... usemap = "#id"> indicates that the -->
51 <!-- specified image map is used with this image -->
52 <img src = "deitel.gif" width = "200" height = "144"
53 alt = "Deitel logo" usemap = "#picture" />
54 </p>
55 </body>
56 </html>
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
` “description” ( name = “description” )
Provides a description of a site
` Attribute content
` Provides the information search engine use to catalog pages
41
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- main.html -->
6 <!-- <meta> tag -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Welcome</title>
11
12 <!-- <meta> tags provide search engines with -->
13 <!-- information used to catalog a site -->
14 <meta name = "keywords" content = "Web page, design,
15 XHTML, tutorial, personal, help, index, form,
16 contact, feedback, list, links, frame, deitel" />
17 main.html
18 <meta name = "description" content = "This Web site will
19 (1 of 2)
help you learn the basics of XHTML and Web page design
20 through the use of interactive examples and
21 instruction." />
22
23 </head>
24
42
25 <body>
26
27 <h1>Welcome to Our Web Site!</h1>
28
29 <p>We have designed this site to teach about the wonders
30 of <strong><em>XHTML</em></strong>. <em>XHTML</em> is
31 better equipped than <em>HTML</em> to represent complex
32 data on the Internet. <em>XHTML</em> takes advantage of
33 XML’s strict syntax to ensure well-formedness. Soon you
34 will know about many of the great new features of
35 <em>XHTML.</em></p>
36
37 <p>Have Fun With the Site!</p>
38
39 </body>
40 </html>
main.html
(2 of 2)
43
frameset Element
` Allow browser display more than one document
simultaneously
` Element frameset
` Attribute cols
Specifies the frameset’s 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 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
4
5 <!-- index.html -->
6 <!-- XHTML Frames I -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Main</title>
11 <meta name = "keywords" content = "Webpage, design,
12 XHTML, tutorial, personal, help, index, form,
13 contact, feedback, list, links, frame, deitel" />
14
15 <meta name = "description" content = "This Web site will
16 help you learn the basics of XHTML and Web page design
17 through the use of interactive examples
18 and instruction." />
19
index.html
20
21
</head>
(1 of 2)
22 <!-- the <frameset> tag sets the frame dimensions -->
23 <frameset cols = "110,*">
24
45
25 <!-- frame elements specify which pages -->
26 <!-- are loaded into a given frame -->
27 <frame name = "leftframe" src = "nav.html" />
28 <frame name = "main" src = "main.html" />
29
30 <noframes>
31 <body>
32 <p>This page uses frames, but your browser does not
33 support them.</p>
34
35 <p>Please, <a href = "nav.html">follow this link to
36 browse our site without frames</a>.</p>
37 </body>
38 </noframes>
39
40 </frameset>
41 </html>
index.html
(2 of 2)
46
47
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- nav.html -->
6 <!-- Using images as link anchors -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9
10 <head>
11 <title>Internet and WWW How to Program - Navigation Bar
12 </title>
13 </head>
14
15 <body>
16
17 <p>
18 <a href = "links.html" target = "main">
19 <img src = "buttons/links.jpg" width = "65"
nav.html
20
21
height = "50" alt = "Links Page" />
</a><br />
(1 of 2)
22
23 <a href = "list.html" target = "main">
24 <img src = "buttons/list.jpg" width = "65"
25 height = "50" alt = "List Example Page" />
48
26 </a><br />
27
28 <a href = "contact.html" target = "main">
29 <img src = "buttons/contact.jpg" width = "65"
30 height = "50" alt = "Contact Page" />
31 </a><br />
32
33 <a href = "header.html" target = "main">
34 <img src = "buttons/header.jpg" width = "65"
35 height = "50" alt = "Header Page" />
36 </a><br />
37
38 <a href = "table1.html" target = "main">
39 <img src = "buttons/table.jpg" width = "65"
40 height = "50" alt = "Table Page" />
41 </a><br />
42
43 <a href = "form.html" target = "main">
44 <img src = "buttons/form.jpg" width = "65" nav.html
height = "50" alt = "Feedback Form" />
45
46 </a><br />
(2 of 2)
47 </p>
48
49 </body>
50 </html>
49
Nested framesets
` framesets within framesets
50
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
4
5 <!-- index2.html -->
6 <!-- XHTML Frames II -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Main</title>
11
12 <meta name = "keywords" content = "Webpage, design,
13 XHTML, tutorial, personal, help, index, form,
14 contact, feedback, list, links, frame, deitel" />
15
16 <meta name = "description" content = "This Web site will
17 help you learn the basics of XHTML and Web page design
18 through the use of interactive examples
19 and instruction." />
index2.html
20
21 </head>
(1 of 2)
22
23 <frameset cols = "110,*">
24 <frame name = "leftframe" src = "nav.html" />
25
51
26 <!-- nested framesets are used to change the -->
27 <!-- formatting and layout of the frameset -->
28 <frameset rows = "175,*">
29 <frame name = "picture" src = "picture.html" />
30 <frame name = "main" src = "main.html" />
31 </frameset>
32
33 <noframes>
34 <body>
35 <p>This page uses frames, but your browser does not
36 support them.</p>
37
38 <p>Please, <a href = "nav.html">follow this link to
39 browse our site without frames</a>.</p>
40 </body>
41 </noframes>
42
43 </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 ?
Pramudith_Kandambi@MIT_IMdepartment
HTML page
<html>
<body>
My First Heading
My first paragraph.
</body>
</html>
Pramudith_Kandambi@MIT_IMdepartment
HTML
<html>
<body>
</body>
</html>
Pramudith_Kandambi@MIT_IMdepartment
HTML Headings
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
HTML Paragraphs
<p>This is a paragraph</p>
<p>This is another paragraph</p>
Pramudith_Kandambi@MIT_IMdepartment
HTML Links
<a> attribute
href - provide the link address
Pramudith_Kandambi@MIT_IMdepartment
HTML Links
<> attribute
Pramudith_Kandambi@MIT_IMdepartment
HTML image
<frameset >
<frame >
<frame >
</frameset>
<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>
Pramudith_Kandambi@MIT_IMdepartment
HTML
<table >
</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
Grouping
h1,h2,h3,h4,h5,h6 { color: green }
• Ex: HTML
• <p class="center"> This paragraph will be center-aligned. </p>
• <p class="right"> This paragraph will be right-aligned. </p>
9
24 <p style = "font-size: 20pt; color: #0000ff">
25 This text has the <em>font-size</em> and
Outline
26 <em>color</em> styles applied to it, making it
27 20pt. and blue.</p>
28
29 </body>
30 </html>
10
Embed an entire CSS document in an XHTML
document’s head section
◦ Multipurpose Internet Mail Extensions (MIME) type
Describes a file’s content
◦ Property background-color
Specifies the background color
◦ Property font-family
Specifies the name of the font to use
◦ Property font-size
Specifies a 14-point font
12
26
27 <body>
Outline
28
29 <!-- this class attribute applies the .special style -->
30 <h1 class = "special">Deitel & Associates, Inc.</h1>
31
32 <p>Deitel & Associates, Inc. is an internationally
33 recognized corporate training and publishing organization
34 specializing in programming languages, Internet/World
35 Wide Web technology and object technology education.
36 Deitel & Associates, Inc. is a member of the World Wide
37 Web Consortium. The company provides courses on Java,
38 C++, Visual Basic, C, Internet and World Wide Web
39 programming, and Object Technology.</p>
40
41 <h1>Clients</h1>
42 <p class = "special"> The company's clients include many
43 <em>Fortune 1000 companies</em>, government agencies,
44 branches of the military and business organizations.
45 Through its publishing partnership with Prentice Hall,
46 Deitel & Associates, Inc. publishes leading-edge
47 programming textbooks, professional books, interactive
48 CD-ROM-based multimedia Cyber Classrooms, satellite
49 courses and World Wide Web courses.</p>
50
13
51 </body>
52 </html>
Outline
14
Inheritance
◦ Descendant’s properties have greater specificity
than ancestor’s properties
16
25 ul ul { text-decoration: underline;
26 margin-left: 15px }
Outline
27
28 </style>
29 </head>
30
31 <body>
32
33 <h1>Shopping list for <em>Monday</em>:</h1>
34
35 <ul>
36 <li>Milk</li>
37 <li>Bread
38 <ul>
39 <li>White bread</li>
40 <li>Rye bread</li>
41 <li>Whole wheat bread</li>
42 </ul>
43 </li>
44 <li>Rice</li>
45 <li>Potatoes</li>
46 <li>Pizza <em>with mushrooms</em></li>
47 </ul>
48
17
49 <p><a class = "nodec" href = "http://www.food.com">
50 Go to the Grocery store</a></p>
Outline
51
52 </body>
53 </html>
18
External style sheets
◦ Can provide uniform look and feel to entire site
20
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- external.html -->
6 <!-- Linking external style sheets -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Linking External Style Sheets</title>
11 <link rel = "stylesheet" type = "text/css"
12 href = "styles.css" />
13 </head>
14
15 <body>
16
17 <h1>Shopping list for <em>Monday</em>:</h1>
18 <ul>
19 <li>Milk</li>
20 <li>Bread
21 <ul>
22 <li>White bread</li>
23 <li>Rye bread</li>
24 <li>Whole wheat bread</li>
25 </ul>
21
26 </li>
27 <li>Rice</li>
Outline
28 <li>Potatoes</li>
29 <li>Pizza <em>with mushrooms</em></li>
30 </ul>
31
32 <p>
33 <a href = "http://www.food.com">Go to the Grocery store</a>
34 </p>
35
36 </body>
37 </html>
22
Validates external CSS documents
Ensures that style sheets are syntactically
correct
27
© Dept. of Industrial Management-2008 28
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- positioning2.html -->
6 <!-- Relative positioning of elements -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Relative Positioning</title>
11
12 <style type = "text/css">
13
14 p { font-size: 1.3em;
15 font-family: verdana, arial, sans-serif }
16
17 span { color: red;
18 font-size: .6em;
19 height: 1em }
20
21 .super { position: relative;
22 top: -1ex }
23
24 .sub { position: relative;
25 bottom: -1ex }
26
29
27 .shiftleft { position: relative;
28 left: -1ex }
Outline
29
30 .shiftright { position: relative;
31 right: -1ex }
32
33 </style>
34 </head>
35
36 <body>
37
38 <p>The text at the end of this sentence
39 <span class = "super">is in superscript</span>.</p>
40
41 <p>The text at the end of this sentence
42 <span class = "sub">is in subscript</span>.</p>
43
44 <p>The text at the end of this sentence
45 <span class = "shiftleft">is shifted left</span>.</p>
46
47 <p>The text at the end of this sentence
48 <span class = "shiftright">is shifted right</span>.</p>
49
50 </body>
51 </html>
30
© Dept. of Industrial Management-2008 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
33
26 </style>
27 </head>
Outline
28
29 <body>
30
31 <p>
32 This example uses the background-image,
33 background-position and background-attachment
34 styles to place the <span class = "dark">Deitel
35 & Associates, Inc.</span> logo in the bottom,
36 right corner of the page. Notice how the logo
37 stays in the proper position when you resize the
38 browser window.
39 </p>
40
41 </body>
42 </html>
34
© Dept. of Industrial Management-2008 35
CSS rules can specify the actual dimensions
of each page element
37
26
27 <div style = "width: 80%; text-align: center">
Outline
28 Here is some CENTERED text that goes in a box
29 which is set to stretch across eighty percent of
30 the width of the screen.</div>
31
32 <div style = "width: 20%; height: 30%; overflow: scroll">
33 This box is only twenty percent of
34 the width and thirty percent of the height.
35 What do we do if it overflows? Set the
36 overflow property to scroll!</div>
37
38 </body>
39 </html>
38
Floating
◦ Move an element to one side of the screen
Box model
◦ Margins
margin-top, margin-right, margin-left, margin-bottom
◦ Padding
padding-top, padding-right, padding-left, and padding-bottom
◦ Border
border-width
thin, medium, thick
border-color
Sets the color
border-style
none, hidden, dotted, dashed, solid, double, groove, ridge,
inset and outset
40
25 <body>
26
Outline
27 <div style = "text-align: center">
28 Deitel & Associates, Inc.</div>
29
30 <div style = "float: right; margin: .5em;
31 text-align: right">
32 Corporate Training and Publishing</div>
33
34 <p>Deitel & Associates, Inc. is an internationally
35 recognized corporate training and publishing organization
36 specializing in programming languages, Internet/World
37 Wide Web technology and object technology education.
38 The company provides courses on Java, C++, Visual Basic, C,
39 Internet and World Wide Web programming, and Object Technology.</p>
40
41 <div style = "float: right; padding: .5em;
42 text-align: right">
43 Leading-Edge Programming Textbooks</div>
44
45 <p>The company's clients include many Fortune 1000
46 companies, government agencies, branches of the military
47 and business organizations.</p>
48
41
49 <p style = "clear: right">Through its publishing
50 partnership with Prentice Hall, Deitel & Associates,
Outline
51 Inc. publishes leading-edge programming textbooks,
52 professional books, interactive CD-ROM-based multimedia
53 Cyber Classrooms, satellite courses and World Wide Web
54 courses.</p>
55
56 </body>
57 </html>
42
Margin
Border
Content
Padding
44
26 .groove { border-style: groove }
27
Outline
28 .inset { border-style: inset }
29
30 .outset { border-style: outset }
31
32 .red { border-color: red }
33
34 .blue { border-color: blue }
35
36 </style>
37 </head>
38
39 <body>
40
41 <div class = "thick groove">This text has a border</div>
42 <div class = "medium groove">This text has a border</div>
43 <div class = "thin groove">This text has a border</div>
44
45 <p class = "thin red inset">A thin red line...</p>
46 <p class = "medium blue outset">
47 And a thicker blue line</p>
48
49 </body>
50 </html>
45
© Dept. of Industrial Management-2008 46
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- borders2.html -->
6 <!-- Various border-styles -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Borders</title>
11
12 <style type = "text/css">
13
14 body { background-color: #ccffcc }
15
16 div { text-align: center;
17 margin-bottom: .3em;
18 width: 50%;
19 position: relative;
20 left: 25%;
21 padding: .3em }
22 </style>
23 </head>
24
25 <body>
47
26
27 <div style = "border-style: solid">Solid border</div>
Outline
28 <div style = "border-style: double">Double border</div>
29 <div style = "border-style: groove">Groove border</div>
30 <div style = "border-style: ridge">Ridge border</div>
31 <div style = "border-style: inset">Inset border</div>
32 <div style = "border-style: outset">Outset border</div>
33
34 </body>
35 </html>
48
Format pages based on preferences
50
24
25 </body>
Outline
26 </html>
51
1 /* Fig. 6.17: userstyles.css */
2 /* A user stylesheet */
Outline
3
4 body { font-size: 20pt;
5 color: yellow;
6 background-color: #000080 }
52
User style sheet in Internet Explorer 6.
55
24
25 </body>
Outline
26 </html>
56
User style sheet applied with em measurement.
By Pramudith Kandambi
Outline
Introduction
Simple Program: Printing a Line of Text in a Web Page
Obtaining User Input with prompt Dialogs
Memory Concepts
Arithmetic
Decision Making: Equality and Relational Operators
Web Resources
2
In this lesson, you will be able to:
3
JavaScript was designed to add interactivity to HTML pages
4
JavaScript's official name is ECMAScript.
6
JavaScript gives HTML designers a programming tool –
◦ HTML authors are normally not programmers, but JavaScript is a
scripting language with a very simple syntax! Almost anyone can put
small "snippets" of code into their HTML pages
7
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
8
JavaScript is Case Sensitive
◦ <script> tag
Indicate that the text is part of a script
type attribute
Specifies the type of file and the scripting language use
writeln method
Write a line in the document
Escape character ( \ )
Indicates “special” character is used in the string
alert method
Dialog box
9
The HTML <script> tag is used to insert a JavaScript into an
HTML page.
<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function message()
{
alert(“Hello BIT !");
}
</script>
</head>
<body onload="message()">
</body>
</html>
Browsers that do not support JavaScript,
<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>
Example
<html>
<head>
<body>
</body>
</html>
Comments can be added to explain the
JavaScript, or to make the code more readable.
◦ Variable names are case sensitive (y and Y are two different variables)
◦ Variable names must begin with a letter or the underscore character
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 Horizontal tab. Move the screen cursor to the next tab stop.
\r 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.
Some common escape sequences.
18
A script can adapt the content based on input
from the user or other variables
19
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- welcome5.html -->
6 <!-- Using Prompt Boxes -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using Prompt and Alert Boxes</title>
11
12 <script type = "text/javascript">
13 <!--
14 var name; // string entered by the user
15
16 // read the name from the prompt box as a string
17 name = window.prompt( "Please enter your name", "GalAnt" );
18
19 document.writeln( "<h1>Hello, " + name +
20 ", welcome to JavaScript programming!</h1>" );
21 // -->
22 </script>
20
23
24 </head>
25
26 <body>
27 <p>Click Refresh (or Reload) to run this script again.</p>
28 </body>
29 </html>
21
When the user clicks OK, the
value typed by the user is
returned to the program as a
This is the string.
prompt
to the user.
22
Prompt user for two integers and calculate
the sum
NaN (not a number)
parseInt
◦ Converts its string argument to an integer
23
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Addition.html -->
6 <!-- Addition Program -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>An Addition Program</title>
11
12 <script type = "text/javascript">
13 <!--
14 var firstNumber, // first string entered by user
15 secondNumber, // second string entered by user
16 number1, // first number to add
17 number2, // second number to add
18 sum; // sum of number1 and number2
19
20 // read in first number from user as a string
21 firstNumber =
22 window.prompt( "Enter first integer", "0" );
23
24
24 // read in second number from user as a string
25 secondNumber =
26 window.prompt( "Enter second integer", "0" );
27
28 // convert numbers from strings to integers
29 number1 = parseInt( firstNumber );
30 number2 = parseInt( secondNumber );
31
32 // add the numbers
33 sum = number1 + number2;
34
35 // display the results
36 document.writeln( "<h1>The sum is " + sum + "</h1>" );
37 // -->
38 </script>
39
40 </head>
41 <body>
42 <p>Click Refresh (or Reload) to run the script again</p>
43 </body>
44 </html>
25
26
Variable names correspond to locations in the
computer’s memory
Every variable has a name, a type, and a value
Read value from a memory location
◦ nondestructive
27
number1 45
28
number1 45
number2 72
Memory locations after values for variables number1 and number2 have been input.
29
number1 45
number2 72
sum 117
30
Many scripts perform arithmetic calculations
◦ Expressions in JavaScript must be written in
straight-line form
31
Operator Description Example Result
33
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7;
2 * 5 is 10 (Leftmost multiplication)
Step 2. y = 10 * 5 + 3 * 5 + 7;
10 * 5 is 50 (Leftmost multiplication)
Step 3. y = 50 + 3 * 5 + 7;
3 * 5 is 15 (Multiplication before addition)
Step 4. y = 50 + 15 + 7;
50 + 15 is 65 (Leftmost addition)
Step 5. y = 65 + 7;
65 + 7 is 72 (Last addition)
35
Operator Example Same As Result
= x=y x=5
37
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- welcome6.html -->
6 <!-- Using Relational Operators -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using Relational Operators</title>
11
12 <script type = "text/javascript">
13 <!--
14 var name, // string entered by the user
15 now = new Date(), // current date and time
16 hour = now.getHours(); // current hour (0-23)
17
18 // read the name from the prompt box as a string
19 name = window.prompt( "Please enter your name", "GalAnt" );
20
21 // determine whether it is morning
22 if ( hour < 12 )
23 document.write( "<h1>Good Morning, " );
24
38
25 // determine whether the time is PM
26 if ( hour >= 12 )
27 {
28 // convert to a 12 hour cl ock
29 hour = hour - 12;
30
31 // determine whether it is before 6 PM
32 if ( hour < 6 )
33 document.write( "<h1>Go od Afternoon, " );
34
35 // determine whether it is after 6 PM
36 if ( hour >= 6 )
37 document.write( "<h1>Go od Evening, " );
38 }
39
40 do cument.writeln( name +
41 ", welcome to JavaScript p rogramming!</h1>" );
42 // -->
43 </scr ipt>
44
45 </head>
46
39
47 <body>
48 <p>Click Refresh (or Reload) to run this script again.</p>
49 </body>
50 </html>
40
Operator Description Example
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
{
code to be executed if condition is not true
}
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
{
code to be executed if condition is not true
}
<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.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
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.
48
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- SwitchTest.html -->
6 <!-- Using the switch statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Switching between XHTML List Formats</title>
11
12 <script type = "text/javascript">
13 <!--
14 var choice, // user’s choice
15 startTag, // starting list item tag
16 endTag, // ending list item tag
17 validInput = true, // indicates if input is valid
18 listType; // list type as a string
19
20 choice = window.prompt( "Select a list style:\n" +
21 "1 (bullet), 2 (numbered), 3 (lettered)", "1" );
22
49
23 switch ( choice ) {
24 case "1":
25 startTag = "<ul>";
26 endTag = "</ul>";
27 listType = "<h1>Bullet List</h1>";
28 break;
29 case "2":
30 startTag = "<ol>";
31 endTag = "</ol>";
32 listType = "<h1>Ordered List: Numbered</h1>";
33 break;
34 case "3":
35 startTag = "<ol type = \"A\">";
36 endTag = "</ol>";
37 listType = "<h1>Ordered List: Lettered</h1>";
38 break;
39 default:
40 validInput = false;
41 }
42
43 if ( validInput == true ) {
44 document.writeln( listType + startTag );
45
46 for ( var i = 1; i <= 3; ++i )
47 document.writeln( "<li>List item " + i + "</li>" );
50
48
49 document.writeln( endTag );
50 }
51 else
52 document.writeln( "Invalid choice: " + choice );
53 // -->
54 </script>
55
56 </head>
57 <body>
58 <p>Click Refresh (or Reload) to run the script again</p>
59 </body>
60 </html>
51
52
53
case a true
case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
54
Syntax
<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
document.writeln(
true "<p style=\"font-size: "
counter <= 7 ++counter
+ counter +
"ex\">XHTML font size " + Increment
counter + "ex</p>" ); the control
false variable.
Determine Body of loop
(this may be many
if final value
of control statements)
variable
has been
reached.
<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>
<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 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- WhileCounter.html -->
6 <!-- Counter-Controlled Repetition -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Counter-Controlled Repetition</title>
11
12 <script type = "text/javascript">
13 <!--
14 var counter = 1; // initialization
15
16 while ( counter <= 7 ) { // repetition condition
17 document.writeln( "<p style = \"font-size: " +
18 counter + "ex\">XHTML font size " + counter +
19 "ex</p>" );
20 ++counter; // increment
21 }
22 // -->
23 </script>
24
y Variant of the while loop. This loop will execute the block
of code ONCE, and then it will repeat the loop as long as
the specified condition is true.
Syntax
do
{
code to be executed
}
while (var<=endvalue);
<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>
true
condition
false
y break
Immediate exit from the structure
y
y Used to escape early from a loop
y Skip the remainder of a switch statement
y continue
y Skips the remaining statements in the body of the structure
y Proceeds with the next iteration of the loop
y The break statement will break the loop and continue executing the code that
follows after the loop (if any).
y Example
y
<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 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- BreakTest.html -->
6 <!-- Using the break statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Using the break Statement in a for Structure
12 </title>
13
14 <script type = "text/javascript">
15 <!--
16 for ( var count = 1; count <= 10; ++count ) {
17 if ( count == 5 )
18 break; // break loop only if count == 5
19
20 document.writeln( "Count is: " + count + "<br />" );
21 }
22
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
}
</script>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 29
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- ContinueTest.html -->
6 <!-- Using the break statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Using the continue Statement in a for Structure
12 </title>
13
14 <script type = "text/javascript">
15 <!--
16 for ( var count = 1; count <= 10; ++count ) {
17 if ( count == 5 )
18 continue; // skip remaining code in loop
19 // only if count == 5
20
21 document.writeln( "Count is: " + count + "<br />" );
22 }
23
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
JavaScript Objects
Introduction
Define your own objects and own variable types.
An object is just a special kind of data.
Properties and methods.
© Pramudith_Kandambi_MIT_BIT_2009 3
Properties
Properties are the values associated with an object.
length property of the String object
<script type="text/javascript">
</script>
To return the number of characters in a string:
© Pramudith_Kandambi_MIT_BIT_2009 4
Methods
Actions that can be performed on objects.
ToUpperCase() method of the String object
<script type="text/javascript">
© Pramudith_Kandambi_MIT_BIT_2009 5
String Object
Property Description FF IE
constructor A reference to the function that created the object 1 4
length Returns the number of characters in a string 1 3
prototype Allows you to add properties and methods to the object 1 4
Method Description FF IE
anchor() Creates an HTML anchor 1 3
big() Displays a string in a big font 1 3
blink() Displays a blinking string 1
bold() Displays a string in bold 1 3
charAt() Returns the character at a specified position 1 3
charCodeAt() Returns the Unicode of the character at a specified position 1 4
concat() Joins two or more strings 1 4
fixed() Displays a string as teletype text 1 3
fontcolor() Displays a string in a specified color 1 3
fontsize() Displays a string in a specified size 1 3
© Pramudith_Kandambi_MIT_BIT_2009 6
String Object Cont…
fromCharCode() Takes the specified Unicode values and returns a string 14
indexOf() Returns the position of the first occurrence of a specified string value in a 13
string
italics() Displays a string in italic 13
lastIndexOf() Returns the position of the last occurrence of a specified string value, 13
searching backwards from the specified position in a string
link() Displays a string as a hyperlink 13
match() Searches for a specified value in a string 14
replace() Replaces some characters with some other characters in a string 14
search() Searches a string for a specified value 14
slice() Extracts a part of a string and returns the extracted part in a new string 14
small() Displays a string in a small font 13
split() Splits a string into an array of strings 14
strike() Displays a string with a strikethrough 13
sub() Displays a string as subscript 13
substr() Extracts a specified number of characters in a string, from a start index 14
substring() Extracts the characters in a string between two specified indices 13
sup() Displays a string as superscript 13
toLowerCase() Displays a string in lowercase letters 13
toUpperCase() Displays a string in uppercase letters 13
toSource() Represents the source code of an object 1-
valueOf() Returns the primitive value of a String object 14
© Pramudith_Kandambi_MIT_BIT_2009 7
Example –object Property
<html>
<body>
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
</body>
</html>
© Pramudith_Kandambi_MIT_BIT_2009 8
Methods generate XHTML
tags
Methods that generate
XHTML tags
anchor( name ) Wraps the source string in an anchor element
(<a></a>) with name as the anchor name.
blink() Wraps the source string in a <blink></blink>
element.
fixed() Wraps the source string in a <tt></tt>
element.
link( url ) Wraps the source string in an anchor element
(<a></a>) with url as the hyperlink location.
strike() Wraps the source string in a
<strike></strike> element.
sub() Wraps the source string in a <sub></sub>
element.
sup() Wraps the source string in a <sup></sup>
element.
String object methods.
© Pramudith_Kandambi_MIT_BIT_2009 9
Example –object method
<html>
<body>
<script type="text/javascript">
© Pramudith_Kandambi_MIT_BIT_2009 10
Example –object method
Cont…
document.write("<p>Strike: " + txt.strike() + "</p>");
</script>
</body>
</html>
© Pramudith_Kandambi_MIT_BIT_2009 11
Example –object method
<html>
<body>
<script type="text/javascript">
var str="Hello world!";
document.write(str.match("world") + "<br />");
document.write(str.match("World") + "<br />");
document.write(str.match("worlld") + "<br />");
document.write(str.match("world!"));
</script>
</body>
</html>
© Pramudith_Kandambi_MIT_BIT_2009 12
Searching Methods Try Your
Self
© Pramudith_Kandambi_MIT_BIT_2009 13
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- SearchingStrings.html -->
6 <!-- Searching Strings -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Searching Strings with indexOf and lastIndexOf
12 </title>
13
14 <script type = "text/javascript">
15 <!--
16 var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm";
17
18 function buttonPressed()
19 {
20 searchForm.first.value =
21 letters.indexOf( searchForm.inputVal.value );
22 searchForm.last.value =
23 letters.lastIndexOf( searchForm.inputVal.value );
24 searchForm.first12.value =
25 letters.indexOf( searchForm.inputVal.value, 12 );
26 s e a r ch F o r m. l a st 1 2 . va l u e =
27 l e tt e r s. l a st I n d ex O f (
28 s e a rc h F or m . i np u t V al . v al u e , 1 2 ) ;
29 }
30 // - - >
31 < /s cr ip t >
32
33 </ he ad >
34 <b od y>
35 < fo rm n a m e = " s ea r c hF o r m " a c t io n = " " >
36 <h 1> T h e s t r i ng t o s e a rc h is : < b r / >
37 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 >
38 <p >E n t e r s u b st r i ng t o s e a r ch f or
39 <i np u t na m e = " i np u t V al " t yp e = " t ex t " / >
40 <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 "
41 o nc l i ck = " b u t to n P re s s e d( ) " / > < b r / > < /p >
42
43 <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
44 <i np u t na m e = " f ir s t " t y p e = " te x t " s i z e = " 5" / >
45 <b r / > L a st o cc u r re n c e l o c a te d at i nd e x
46 <i np u t n am e = " l as t " ty p e = " t ex t " s i z e = " 5 " / >
47 <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
48 <i np u t n am e = " f ir s t 1 2" t y pe = " t e xt " s i ze = " 5 " / >
49 <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
50 <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 </form>
52 </body>
53 </html>
© Pramudith_Kandambi_MIT_BIT_2009 17
Splitting and Substrings Try your
Self
Tokenization
The process of breaking a string into tokens
Tokens
Individual words
Separated by delimiters
© Pramudith_Kandambi_MIT_BIT_2009 18
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- SplitAndSubString.html -->
6 <!-- String Method split and substring -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>String Method split and substring</title>
11
12 <script type = "text/javascript">
13 <!--
14 function splitButtonPressed()
15 {
16 var strings = myForm.inputVal.value.split( " " );
17 myForm.output.value = strings.join( "\n" );
18
19 myForm.outputSubstring.value =
20 myForm.inputVal.value.substring( 0, 10 );
21 }
22 // -->
23 </script>
24 </head>
25
26 <body>
27 <form name = "myForm" action = "">
28 <p>Enter a sentence to split into words<br />
29 <input name = "inputVal" type = "text" size = "40" />
30 <input name = "splitButton" type = "button" value =
31 "Split" onclick = "splitButtonPressed()" /></p>
32
33 <p>The sentence split into words is<br />
34 <textarea name = "output" rows = "8" cols = "34">
35 </textarea></p>
36
37 <p>The first 10 characters of the input string are
38 <input name = "outputSubstring" type = "text"
39 size = "15" /></p>
40 </form>
41 </body>
42 </html>
© Pramudith_Kandambi_MIT_BIT_2009 21
Math Object
© Pramudith_Kandambi_MIT_BIT_2009 22
Math Object
Method Description Example
abs( x ) absolute value of x 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 min( 2.3, 12.7 ) is 2.3
and y min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to power y pow( 2.0, 7.0 ) is 128.0
(xy) pow( 9.0, .5 ) is 3.0
round( x ) rounds x to the round( 9.75 ) is 10
closest integer round( 9.25 ) is 9
sin( x ) trigonometric sine of sin( 0.0 ) is 0.0
x (x in radians)
sqrt( x ) square root of x 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 Description Value
Math.E Base of a natural Approximately 2.718.
logarithm (e).
Math.LN2 Natural logarithm of 2. Approximately 0.693.
Math.LN10 Natural logarithm of 10. Approximately 2.302.
Math.LOG2E Base 2 logarithm of e. Approximately 1.442.
Math.LOG10E Base 10 logarithm of e. Approximately 0.434.
Math.PI —the ratio of a circle’s Approximately
circumference to its 3.141592653589793.
diameter.
Math.SQRT1_2 Square root of 0.5. Approximately 0.707.
Math.SQRT2 Square root of 2.0. Approximately 1.414.
Properties of the Math object.
© Pramudith_Kandambi_MIT_BIT_2009 25
Method Description
getDate() Returns a number from 1 to 31 representing the day of the month in local time or
getUTCDate() UTC, respectively.
getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the
getUTCDay() week in local time or UTC, respectively.
getFullYear() Returns the year as a four-digit number in local time or UTC, respectively.
getUTCFullYear()
getHours() Returns a number from 0 to 23 representing hours since midnight in local time or
getUTCHours() UTC, respectively.
getMilliseconds() Returns a number from 0 to 999 representing the number of milliseconds in local
getUTCMilliSeconds() 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 UTC—previously 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
setFullYear( y, m, d ) Sets the year in local time or UTC, respectively. The second and third
setUTCFullYear( y, m, d ) arguments representing the month and the date are optional. If an
optional argument is not specified, the current value in the Date object
is used.
setHours( h, m, s, ms ) Sets the hour in local time or UTC, respectively. The second, third and
setUTCHours( h, m, s, ms ) 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.
setSeconds( s, ms ) Sets the second in local time or UTC, respectively. The second
setUTCSeconds( s, ms ) argument representing the milliseconds is optional. If this argument is
not specified, the current millisecond value in the Date object is used.
© Pramudith_Kandambi_MIT_BIT_2009 27
Methods of the Date object.
Method Description
setTime( ms ) Sets the time based on its argument—the number of elapsed
milliseconds since January 1, 1970.
toLocaleString() Returns a string representation of the date and time in a form
specific to the computer’s 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.
toUTCString() Returns a string representation of the date and time in the
form: 19 Sep 2001 15:47:22 UTC
toString() 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).
valueOf() The time in number of milliseconds since midnight, January
1, 1970.
Methods of the Date object.
© Pramudith_Kandambi_MIT_BIT_2009 28
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- DateTime.html -->
6 <!-- Date and Time Methods -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Date and Time Methods</title>
11
12 <script type = "text/javascript">
13 <!--
14 var current = new Date();
15
16 document.writeln(
17 "<h1>String representations and valueOf</h1>" );
18 document.writeln( "toString: " + current.toString() +
19 "<br />toLocaleString: " + current.toLocaleString() +
20 "<br />toUTCString: " + current.toUTCString() +
21 "<br />valueOf: " + current.valueOf() );
22
23 document.writeln(
24 "<h1>Get methods for local time zone</h1>" );
25 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 ( ) +
26 " < b r /> g e tD a y : " + c u r r en t . ge t D ay ( ) +
27 " < b r /> g e tM o n th : " + c ur r e n t. g e tM o n t h( ) +
28 " < 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 ( ) +
29 " < b r /> g e tT i m e: " + c u rr e n t .g e t Ti m e ( ) +
30 " < b r / > g e tH o u rs : " + c ur r e n t. g e tH o u r s( ) +
31 " < b r /> g e tM i n ut e s : " + c u r r en t . ge t M i nu t e s( ) +
32 " < b r /> g e tS e c on d s : " + c u r r en t . ge t S e co n d s( ) +
33 " < b r /> g e tM i l li s e c on d s : " +
34 c u r r e nt . g et M i ll i s e co n d s () +
35 " < b r /> g e tT i m ez o n e Of f s e t: " +
36 c u r r en t . g et T i me z o n eO f f se t ( ) ) ;
37
38 do cu m e n t .w r i te l n (
39 " < 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 > " ) ;
40 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 );
41 do cu m e n t. w r i te l n ( " D a te : " + a no t h er D a t e ) ;
42
43 do cu m e n t. w r i te l n (
44 " < 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 > " ) ;
45 an ot h e r Da t e . se t D at e ( 31 ) ;
46 an ot h e r Da t e . se t M on t h ( 1 1 ) ;
47 an ot h e r Da t e . se t F ul l Y e ar ( 2 00 1 );
48 an ot h e r Da t e . se t H ou r s ( 2 3 ) ;
49 an ot h e r Da t e . se t M in u t e s( 5 9 ) ;
50 anotherDate.setSeconds( 59 );
51 document.writeln( "Modified date: " + anotherDate );
52 // -->
53 </script>
54
55 </head><body></body>
56 </html>
Boolean and Number Objects
Method Description
toString() Returns the string “true” if the value of the Boolean object is
true; otherwise, returns the string “false.”
valueOf() Returns the value true if the Boolean object is true; otherwise,
returns false.
Boolean object methods.
© Pramudith_Kandambi_MIT_BIT_2009 32
Method or Property Description
toString( radix ) Returns the string representation of the number. The optional radix
argument (a number from 2 to 36) specifies the number’s 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 program—approximately 1.79E+308
Number.MIN_VALUE This property represents the smallest value that can be stored in a
JavaScript program—approximately
2.22E–308
Number.NaN This property represents not a number—a 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 Description
write( string ) 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 user’s 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
© Pramudith_Kandambi_MIT_BIT_2009 35
Method or Property Description
open( url, name, options ) 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 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- window.html -->
6 <!-- Using the Window Object -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the Window Object</title>
11
12 <script type = "text/javascript">
13 <!--
14 var childWindow; // variable to control the child window
15
16 function createChildWindow()
17 {
18 // these variables all contain either "yes" or "no"
19 // to enable or disable a feature in the child window
20 var toolBar // specify if toolbar will appear in child window
21 var menuBar; // specify if menubar will appear in child window
22 var location; // specify if address bar will appear in child window
23 var scrollBars; // specify if scrollbars will appear in child window
24 var status; // specify if status bar will appear in child window
25 var resizable; // specify if the child window will be resizable
26
27 / / 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
28 i f ( t oo l B a rC h e ck Bo x. c h e ck e d )
29 t o o lB ar = " y es " ;
30 e l se
31 t o o lB ar = " n o" ;
32
33 / / 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
34 i f ( m en u B a rC h e ck Bo x. c h e ck e d )
35 m e n uB ar = " y es " ;
36 e l se
37 m e n uB ar = " n o" ;
38
39 / / 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
40 i f ( l oc a t i on C h ec kB ox . c h ec k e d )
41 l o c at io n = " ye s" ;
42 e l se
43 l o c at io n = " no ";
44
45 / / 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
46 i f ( s cr o l l Ba r s Ch ec kB o x . ch e c ke d )
47 s c r ol lB a rs = " ye s" ;
48 e l se
49 s c r ol lB a rs = " no ";
50
51 // determi ne w hether the Sta tus Bar checkbox is checked
52 if ( statusCheckBox.chec ked )
53 status = "yes";
54 else
55 status = "n o";
56
57 // determi ne w hether the Res izab le checkbox is che cked
58 if ( resizableCheckBox.c heck ed )
59 resizab le = "yes";
60 else
61 resizab le = "no";
62
63 // display win dow with s elec ted features
64 childWindo w = window.ope n( " ", " ", "resizable = " + resizable +
65 ", tool bar = " + tool Bar + ", menubar = " + menuBar +
66 ", stat us = " + statu s + ", l ocation = " + location +
67 ", scro llba rs = " + s crol lBar s );
68
69 // disable but tons
70 closeButto n.di sabled = f alse ;
71 modifyButt on.d isabled = fals e;
72 getURLButt on.d isabled = fals e;
73 setURLButt on.d isabled = fals e;
74 } // end function createChi ldWi ndow
75
76 // insert text from the textbox into the child window
77 function modifyChildWindow()
78 {
79 if ( childWindow.closed )
80 alert( "You attempted to interact with a closed window" );
81 else
82 childWindow.document.write( textForChild.value );
83 } // end function modifyChildWindow
84
85 // close the child window
86 function closeChildWindow()
87 {
88 if ( childWindow.closed )
89 alert( "You attempted to interact with a closed window" );
90 else
91 childWindow.close();
92
93 closeButton.disabled = true;
94 modifyButton.disabled = true;
95 getURLButton.disabled = true;
96 setURLButton.disabled = true;
97 } // end function closeChildWindow
98
99 // copy the U RL o f the chil d wi ndow into the parent window’s myChildURL
100 function getChildWindowURL()
101 {
102 if ( childWindow .closed )
103 alert( "You attempted to intera ct w ith a closed windo w" );
104 else
105 myChildURL.value = childWindow. loca tion;
106 } // end function getChildWindowURL
107
108 // set the URL of the child window to the URL
109 // in the parent wi ndow ’s myChildURL
110 function setChildWindowURL()
111 {
112 if ( childWindow .closed )
113 alert( "You attempted to intera ct w ith a closed windo w" );
114 else
115 childWindow.location = myChildU RL.v alue;
116 } // end function setChildWindowURL
117 //-->
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 <input id = "too lBarCheckBox" type = "checkbox" valu e = ""
1 26 che cke d = "checked" />
1 27 <la bel >To ol B ar</label>
1 28 <input id = "men uBarCheckBox" type = "checkbox" valu e = ""
1 29 che cke d = "checked" />
1 30 <la bel >Me nu B ar</label>
1 31 <input id = "loc ationCheckBox" typ e = "checkbox" val ue = ""
1 32 che cke d = "checked" />
1 33 <la bel >Ad dres s Bar</label>< br/>
1 34 <input id = "scr ollBarsCheckBo x" t ype = "checkbox" v alu e = ""
1 35 che cke d = "checked" />
1 36 <la bel >Sc roll Bars</label>
1 37 <input id = "sta tusCheckBox" t ype = " checkbox" value = ""
1 38 che cke d = "checked" />
1 39 <la bel >St atus Bar</label>
1 40 <input id = "res izableCheckBox " ty pe = "checkbox" va lue = ""
1 41 che cke d = "checked" />
1 42 <la bel >Re siza ble</label><br /></ p>
1 43
1 44 <p>Please en ter the text that you wou ld like to display
1 45 in the ch ild win dow<br/>
1 46 <input id = "tex tForChild" typ e = "te xt"
1 47 val ue = " <h1> Hello, I am a chi ld window</h1> <br \>" />
148 <input id = "createButton" type = "button"
149 value = "Create Child Window" onclick = "createChildWindow()" />
150 <input id= "modifyButton" type = "button" value = "Modify Child Window"
151 onclick = "modifyChildWindow()" disabled = "disabled"/>
152 <input id = "closeButton" type = "button" value = "Close Child Window"
153 onclick = "closeChildWindow()" disabled = "disabled"/></p>
154
155 <p>The other window's URL is: <br/>
156 <input id = "myChildURL" type = "text" value = "./"/>
157 <input id = "setURLButton" type = "button" value = "Set Child URL"
158 onclick = "setChildWindowURL()" disabled = "disabled"/>
159 <input id = "getURLButton" type = "button" value = "Get URL From Child"
160 onclick = "getChildWindowURL()" disabled = "disabled"/></p>
161
162 </body>
163 </html>
© 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
2
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.
3
` An array is a special variable, which can hold
more than one value, at a time.
c[ 2 ] 0
c[ 3 ] 72
c[ 4 ] 1543
c[ 5 ] -89
c[ 6 ] 0
c[ 7 ] 62
c[ 8 ] -3
c[ 9 ] 1
Position number (index
or subscript) of the c[ 10 ] 6453
element within c
c[ 11 ] 78
array
A 12-element array.
5
` The following code creates an Array object
called myCars:
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";
` 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
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">
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";
</body>
</html>
<html>
<body>
<script type="text/javascript">
</body>
</html>
` Arrays
◦ Data structures of related items
x Also called Collections
◦ Dynamic
15
` Arrays in JavaScript
◦ Each element referenced by a number
x Start at “zeroth element”
x Subscript or index
◦ Accessing a specific element
x Name of array
x Brackets
x Number of element
◦ Arrays know their length
x length property
16
` Arrays in memory
◦ Objects
◦ Operator new
x Allocates memory for objects
x Dynamic memory allocation operator
var c;
c = new Array( 12 );
17
` Arrays grow dynamically
◦ Allocate more space as items are added
` Must initialize array elements
◦ Default value is undefined
◦ for loops convenient
◦ Referring to uninitialized elements or elements
outside array bounds is an error
18
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- InitArray.html -->
6 <!-- Initializing an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Initializing an Array</title>
11
12 <script type = "text/javascript"> Array n1 has five elements.
13 <!--
14 // this function is called when the <body> element's
15 // onload event occurs Array n2 is an empty array.
16 function initializeArrays()
17 {
18 var n1 = new Array( 5 ); // allocate 5-element Array
19 var n2 = new Array(); // allocate empty Array
The for loop initializes the elements in n1
20
21 // assign values to each element of
to their subscript numbers (0 to 4).
Array n1
22 for ( var i = 0; i < n1.length; ++i )
23 n1[ i ] = i;
19
24
25 // create and initialize five-elements in Array n2
26 for ( i = 0; i < 5; ++i )
27 n2[ i ] = i; The for loop adds Each
five elements
function to theand
Array n2
displays
28 initialize each element to itsofsubscript
contents number (0 to
its respective
29 outputArray( "Array n1 4).n1 );
contains", Array in an XHTML table.
30 outputArray( "Array n2 contains", n2 );
31 }
32
33 // output "header" followed by a two-column table
34 // containing subscripts and elements of "theArray"
35 function outputArray( header, theArray )
36 {
37 document.writeln( "<h2>" + header + "</h2>" );
38 document.writeln( "<table border = \"1\" width =" +
The second time
first time function
function ouputArray
ouputArray is is
39 "\"100%\">" );
40
called, variable header gets the value of
41 “Array n2 "<thead><th and
n1 contains”
document.writeln( widthvariable
= \"100\"" +
42 theArray
"align gets the value of n2
n1.+
= \"left\">Subscript</th>"
43 "<th align = \"left\">Value</th></thead><tbody>" );
20
44
45 for ( var i = 0; i < theArray.length; i++ )
46 document.writeln( "<tr><td>" + i + "</td><td>" +
47 theArray[ i ] + "</td></tr>" );
48
49 document.writeln( "</tbody></table>" );
50 }
51 // -->
52 </script>
53
54 </head><body onload = "initializeArrays()"></body>
55 </html>
21
Initializing the elements of an array.
22
` Possible to declare and initialize in one step
◦ Specify list of values
x Initializer list
var n = [ 10, 20, 30, 40, 50 ];
var n = new Array( 10, 20, 30, 40, 50 );
◦ Also possible to only initialize some values
x Leave uninitialized elements blank
x Uninitialized elements default to “undefined”
var n = [ 10, 20, , 40, 50 ];
23
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- InitArray2.html -->
6 <!-- Initializing an Array with a Declaration -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Initializing an Array with a Declaration</title>
11
12 <script type = "text/javascript">
Array integers1 is initialized using an initializer list.
13 <!--
14 function start()
15 { Two values are not supplied for
16 // Initializer list specifies number of elements
integers2 and will be displayed as
, which
17 // value for each element.
undefined.
18 var colors = new Array( "cyan", "magenta",
19 "yellow", "black" );
20 var integers1 = [ 2, 4, 6, 8 ];
21 var integers2 = [ 2, , , 8 ];
22
23 outputArray( "Array colors contains", colors );
24 outputArray( "Array integers1 contains", integers1 );
25 outputArray( "Array integers2 contains", integers2 );
26 }
24
27
28 // output "header" followed by a two-column table
29 // containing subscripts and elements of "theArray"
30 function outputArray( header, theArray )
31 {
32 document.writeln( "<h2>" + header + "</h2>" );
33 document.writeln( "<table border = \"1\"" +
34 "width = \"100%\">" );
35 document.writeln( "<thead><th width = \"100\" " +
36 "align = \"left\">Subscript</th>" +
37 "<th align = \"left\">Value</th></thead><tbody>" );
38
39 for ( var i = 0; i < theArray.length; i++ )
40 document.writeln( "<tr><td>" + i + "</td><td>" +
41 theArray[ i ] + "</td></tr>" );
42
43 document.writeln( "</tbody></table>" );
44 }
45 // -->
46 </script>
47
48 </head><body onload = "start()"></body>
49 </html>
25
Initializing the elements of an array.
26
` for…in statement
◦ Perform an action for each element in an array
◦ Iterates over array elements
x Assigns each element to specified variable one at a
time
◦ Ignores non-existent elements
27
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- SumArray.html -->
6 <!-- Summing Elements of an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Sum the Elements of an Array</title>
11
12 <script type = "text/javascript">
13 <!--
14 function start()
The for loop sums the values contained in the
15 { 10-element integer array called theArray.
16 var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
17 var total1 = 0, total2 = 0;
18
19 for ( var i = 0; i < theArray.length; i++ )
20 total1 += theArray[ i ];
21
22 document.writeln( "Total using subscripts: " + total1 );
23
28
24 for ( var element in theArray )
25 total2 += theArray[ element ];
26
Variable element is assigned a
27 document.writeln( "<br />Total using for...in: " +
subscript in the range of 0 up to, but
28 total2 );
29 }
not including, theArray.length.
30 // -->
31 </script>
32
33 </head><body onload = "start()"></body>
34 </html>
29
Calculating the sum of the elements of an array.
30
` Arrays can provide shorter and cleaner
substitute for switch statements
◦ Each element represents one case
31
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- RollDie.html -->
6 <!-- Roll a Six-Sided Die 6000 Times -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Roll a Six-Sided Die 6000 Times</title>
11
12 <script type = "text/javascript">
13 <!-- Referencing Array frequency replaces the switch
14 var face, frequency = [ , statement
0, 0, 0, 0, used in Chapter 10’s example.
0, 0 ];
15
16 // summarize results
17 for ( var roll = 1; roll <= 6000; ++roll ) {
18 face = Math.floor( 1 + Math.random() * 6 );
19 ++frequency[ face ];
20 }
21
32
22 document.writeln( "<table border = \"1\"" +
23 "width = \"100%\">" );
24 document.writeln( "<thead><th width = \"100\"" +
25 " align = \"left\">Face<th align = \"left\">" +
26 "Frequency</th></thead></tbody>" );
27
28 for ( face = 1; face < frequency.length; ++face )
29 document.writeln( "<tr><td>" + face + "</td><td>" +
30 frequency[ face ] + "</td></tr>" );
31
32 document.writeln( "</tbody></table>" );
33 // -->
34 </script>
35
36 </head>
37 <body>
38 <p>Click Refresh (or Reload) to run the script again</p>
39 </body>
40 </html>
33
Dice-rolling program using arrays instead of a switch.
34
` Cleaner approach than previous version
◦ Specify any file name rather than integers 1-7
◦ Result of Math.random call is index into array of
image file names
35
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- RandomPicture2.html -->
6 <!-- Randomly displays one of 7 images -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Random Image Generator</title>
11
12 <script type = "text/javascript">
13 <!--
14 var pictures =
15 [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ];
36
16
17 document.write ( "<img src = \"" +
18 pictures[ Math.floor( Math.random() * 7 ) ] +
19 ".gif\" width = \"105\" height = \"100\" />" );
20 // -->
21 </script>
22
23 </head>
24
25 <body>
26 <p>Click Refresh (or Reload) to run the script again</p>
27 </body>
28 </html>
37
Random image generation using arrays.
38
` Two ways to pass parameters
◦ Pass-by-value
x Pass copy of original value
x Default for numbers and booleans
x Original variable is unchanged
◦ Pass-by-reference
x How objects are passed, like arrays
x Pass location in memory of value
x Allows direct access to original value
x Improves performance
39
` Name of array is argument
◦ Not necessary to also pass size of array
x Arrays know their size
◦ Passed by reference
x Individual elements are passed by value if numbers or
booleans
` Array.join
◦ Creates string containing all array elements
◦ Specify separator
40
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- PassArray.html -->
6 <!-- Passing Arrays -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Passing Arrays and Individual Array
11 Elements to Functions</title>
12
13 <script type = "text/javascript">
14 <!--
15 function start() The first call to function outputArray displays
16 { the contents of the Array a before it is modified.
17 var a = [ 1, 2, 3, 4, 5 ];
18
19 document.writeln( "<h2>Effects of passing entire " +
20 "array call-by-reference</h2>" );
21 outputArray( Function modifyArray multiplies each element by
22 "The values of the original2.array are: ", a );
23
24 modifyArray( a ); // array a passed call-by-reference
25
41
26 outputArray(
27 "The values of the modified array are: ", a );
28
29 Again, function
document.writeln( "<h2>Effects of passing outputArray
array " + is called to
30 show that
"element call-by-value</h2>" + the contents of Array a have been
31 modified.
"a[3] before modifyElement: " + a[ 3 ] );
32
33 modifyElement( a[ 3 ] ); Function modifyElement multiplies
34 the contents of a[ 3 ] by 2.
35 document.writeln(
36 The value of a[ 3 ] is output to show its
"<br />a[3] after modifyElement: " + a[ 3 ] );
37 } contents before it is modified.
38
39 // outputs "header" followed by the contents of "theArray"
40 function outputArray( header, theArray )
41 {
42 document.writeln(
43 header + theArray.join( " " ) + "<br />" );
44 }
45
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 // function that modifies the elements of an array
47 function modifyArray( theArray )
48 {
49 for ( var j in theArray )
50 theArray[ j ] *= 2;
51 }
52
53 // function that attempts to modify the value passed
54 function modifyElement( e ) Multiply each element in theArray by 2.
55 {
56 e *= 2;
57 document.writeln( "<br />value in modifyElement: " + e );
58 }
59 // -->
60 </script>
61
62 </head><body onload = "start()"></body>
63 </html>
43
Passing arrays and individual array elements to functions.
44
` Sorting
◦ Important computing task
` Array.sort
◦ Defaults to string comparison
◦ Optional comparator function
x Return negative if first argument less than second
x Return zero if arguments equal
x Return positive if first argument greater than second
45
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- sort.html -->
6 <!-- Sorting an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Sorting an Array with Array Method sort</title>
11
12 <script type = "text/javascript">
13 <!--
Method sort takes as its optional argument the
14 function start() name of a function that compares two arguments
15 { and returns a value of –1, 0 or 1.
16 var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];
17
18 document.writeln( "<h1>Sorting an Array</h1>" );
19 outputArray( "Data items in original order: ", a );
20 a.sort( compareIntegers ); // sort the array
21 outputArray( "Data items in ascending order: ", a );
22 }
46
23
24 // outputs "header" followed by the contents of "theArray"
25 function outputArray( header, theArray )
26 {
27 document.writeln( "<p>" + header +
28 theArray.join( " " ) + "</p>" );
29 }
30
31 // comparison function for use with sort
32 function compareIntegers( value1, value2 )
33 {
34 return parseInt( value1 ) - parseInt( value2 );
35 } Function compareIntegers calculates the
36 // -->
difference between the integer values of its
37 </script>
arguments.
38
39 </head><body onload = "start()"></body>
40 </html>
47
Fig. 11.9 Sorting an array with sort.
48
` Searching
◦ Look for matching key value
` Linear search
◦ Iterate through each element until match found
◦ Inefficient
x Worst case scenario, must test entire array
` Binary search
◦ Requires sorted data
◦ Cuts search range in half each iteration
◦ Efficient
x Only look at small fraction of elements
49
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- LinearSearch.html -->
6 <!-- Linear Search of an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head> Array a is initiated with 100 elements.
10 <title>Linear Search of an Array</title>
11
12 <script type = "text/javascript">
13 <!--
14 var a = new Array( 100 ); Array
// create ais populated with the even integers 0 to
an Array
15 198.
16 // fill Array with even integer values from 0 to 198
17 for ( var i = 0; i < a.length; ++i )
18 a[ i ] = 2 * i;
19
50
20 // function called when "Search" button is pressed
21 function buttonPressed()
22 {
23 var searchKey = searchForm.inputVal.value;
24
25 // Array a is passed to linearSearch even though it
26 Get value of search key from the input
// is a global variable. Normally an array will
27 // be passed to a method for field in the XHTML form.
searching.
28 var element = linearSearch( a, parseInt( searchKey ) );
29
30 if ( element != -1 ) Calling function linearSearch and passing
31 searchForm.result.value = it the Array a and the value of variable
32 "Found value in element " + element;
searchKey as an integer.
33 else
34 searchForm.result.value = "Value not found";
35 }
36
51
37 // Search "theArray" for the specified "key" value
38 function linearSearch( theArray, key )
39 {
40 for ( var n = 0; n < theArray.length; ++n )
41 if ( theArray[ n ] == key )
42 return n;
43
Variable theArray gets the value
44 return -1;
45 }
of Array a and variable key gets
Function linearSearch compares
46 // --> the value of variable searchKey.
each each element with a search key.
47 </script>
48
49 </head>
50
51 <body>
52 <form name = "searchForm" action = "">
53 <p>Enter integer search key<br />
54 <input name = "inputVal" type = "text" />
55 <input name = "search" type = "button" value = "Search"
56 onclick = "buttonPressed()" /><br /></p>
57
58 <p>Result<br />
59 <input name = "result" type = "text" size = "30" /></p>
60 </form>
61 </body>
62 </html>
52
Linear search of an array.
53
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- BinarySearch.html -->
6 <!-- Binary search -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Binary Search</title>
11 Array ais initialized with 15
12 <script type = "text/javascript"> elements.
13 <!--
14 var a = new Array( 15 );
15
16 for ( var i = 0; i < a.length; ++i )
17 a[ i ] = 2 * i;
18
54
19 // function called when "Search" button is pressed
20 function buttonPressed()
21 {
22 var searchKey = searchForm.inputVal.value;
23
24 searchForm.result.value =
25 "Portions of array searched\n";
26 Function binarySearch receives two
27 // Array a is passed to binarySearch arguments: the Array a and the search key,
even though it
28 // is a global variable. This is donesearchKey
because .
29 // normally an array is passed to a method
30 // for searching.
31 var element =
32 binarySearch( a, parseInt( searchKey ) );
33
34 if ( element != -1 )
35 searchForm.result.value +=
36 "\nFound value in element " + element;
37 else
38 searchForm.result.value += "\nValue not found";
39 }
40
55
41 // Binary search
42 function binarySearch( theArray, key )
43 {
44 var low = 0; // low subscript
45 var high = theArray.length - 1; // high subscript
46 var middle; // middle subscript
47
48 while ( low <= high ) {
49 middle = ( low + high ) / 2;
50
51 // The following line is used to display the
52 // part of theArray currently being manipulated
If the key matches the middle element of a
53 // during each iteration of the binary
54 // search loop.
subarray, the subscript of the current element
55 buildOutput( theArray, low, is less
If middle,
key is returned.
high than
); the middle element, the
56 high subscript is set to middle – 1.
57 if ( key == theArray[ middle ] ) // match
58 return middle;
59 else if ( key < theArray[ middle ] )
60 If is greater then the middle elements,
key low end of array
high = middle - 1; // search
61 else the high subscript is set to middle + 1.
62 low = middle + 1; // search high end of array
63 }
56
64
65 return -1; // searchKey not found
66 }
67
68 // Build one row of output showing the current
69 // part of the array being processed.
70 function buildOutput( theArray, low, mid, high )
71 {
72 for ( var i = 0; i < theArray.length; i++ ) {
73 Function buildOutput creates the markup
if ( i < low || i > high )
74 searchForm.result.value += " the";results of the search.
that displays
75 // mark middle element in output
76 else if ( i == mid )
77 searchForm.result.value += theArray[ i ] +
78 ( theArray[ i ] < 10 ? "* " : "* " );
79 else
80 searchForm.result.value += theArray[ i ] +
81 ( theArray[ i ] < 10 ? " " : " " );
82 }
83
84 searchForm.result.value += "\n";
85 }
86 // -->
87 </script>
88 </head>
89
57
90 <body>
91 <form name = "searchForm" action = "">
92 <p>Enter integer search key<br />
93 <input name = "inputVal" type = "text" />
94 <input name = "search" type = "button" value =
95 "Search" onclick = "buttonPressed()" /><br /></p>
96 <p>Result<br />
97 <textarea name = "result" rows = "7" cols = "60">
98 </textarea></p>
99 </form>
100 </body>
101 </html>
58
Binary search of an array.
59
` Two-dimensional arrays analogous to tables
◦ Rows and columns
x Specify row first, then column
◦ Two subscripts
60
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Array name
61
` Declaring and initializing multidimensional
arrays
◦ 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
` Also possible to use new operator
◦ 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 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- InitArray3.html -->
6 <!-- Initializing Multidimensional Arrays -->
7
8 Array array1
<html xmlns = "http://www.w3.org/1999/xhtml"> provides six initializers
9 <head>
in two rows.
10 <title>Initializing Multidimensional Arrays</title>
11
12 <script type = "text/javascript">
Array array2 provides six initializers in
13 <!--
three rows.
14 function start()
15 {
16 var array1 = [ [ 1, 2, 3 ], // first row
17 [ 4, 5, 6 ] ]; // second row
18 var array2 = [ [ 1, 2 ], // first row
19
Function outputArray
[ 3 ],
displays each array’s
// second row
20 [ elements in a //
4, 5, 6 ] ]; Web page.
third row
21
22 outputArray( "Values in array1 by row", array1 );
23 outputArray( "Values in array2 by row", array2 );
24 }
64
25
26 function outputArray( header, theArray )
27 {
28 document.writeln( "<h2>" + header + "</h2><tt>" );
29
30 for ( var i in theArray ) {
31
32 for ( var j in theArray[ i ] )
33 document.write( theArray[ i ][ j ] + " " );
34
35 document.writeln( "<br />" );
36 }
37 Referencing the
38 document.writeln( "</tt>" ); multidimensional array theArray.
39 }
40 // -->
41 </script>
42
43 </head><body onload = "start()"></body>
44 </html>
65
Initializing multidimensional arrays.
66
` Radio buttons
◦ Represented as an array
x Name of radio buttons is name of array
x One element per button
◦ checked property is true when selected
` XHTML Forms
◦ Contain controls, including radio buttons
◦ action property specifies what happens when
submitted
x Can call JavaScript code
67
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- quiz.html -->
6 <!-- Online Quiz -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Online Quiz</title>
11
12 <script type = "text/JavaScript">
13
14 function checkAnswers()
15 {
16 // determine whether the answer is correct
17 if ( myQuiz.radiobutton[ 1 ].checked )
18 document.write( "Congratulations, your answer is correct" );
19 else // if the answer is incorrect
20 document.write( "Your answer is incorrect. Please try again" );
21 } Determining the value of
22 property checked.
23 </script>
24
25 </head>
68
26
27 <body>
28 <form id = "myQuiz" action = "JavaScript:checkAnswers()">
29 <p>Select the name of the tip that goes with the image shown:<br />
30 <img src="EPT.gif" width="108" height="100" alt="mystery tip"/>
31 <br />
Call the checkAnswers function
32
33 <input type = "radio"
when the form is submitted.
name = "radiobutton" value = "CPE" />
34 <label>Common Programming Error</label>
35
36 <input type = "radio" name = "radiobutton" value = "EPT" />
37 <label>Error-Prevention Tip</label>
38
39 <input type = "radio" name = "radiobutton" value = "PERF" />
40 <label>Performance Tip</label>
41
42 <input type = "radio" name = "radiobutton" value = "PORT" />
43 <label>Portability Tip</label><br />
44
45 <input type = "submit" name = "submit" value = "Submit" />
46 <input type = "reset" name = "reset" value = "Reset" />
47 </p>
48 </form>
49 </body>
50 </html>
69
Online quiz graded with JavaScript.
70
By Pramudith Kandambi
` Detect the visitor's browser, and then serve
up the appropriate information.
` 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
` Password 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
` Date 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
` 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:
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'>
<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.
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
PHP is a server-side scripting language.
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
PHP + MySQL
◦ PHP combined with MySQL are cross-platform (you can develop in
Windows and serve on a Unix platform)
Why PHP?
◦ PHP runs on different platforms (Windows, Linux, Unix, etc.)
◦ PHP is compatible with almost all servers used today (Apache, IIS, etc.)
◦ PHP is FREE to download from the official PHP resource: www.php.net
◦ PHP 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.
<?php
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
Variables are used for storing a values
◦ text strings, numbers or arrays.
$txt="Hello World";
echo $txt;
?>
String variables are used for values that contains
characters.
<?php
$txt="Hello World";
echo $txt;
?>
There is only one string operator in PHP.
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
<?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.
<?php
echo strpos("Hello world!","world");
?>
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
?>
</body>
</html>
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:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</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
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
?>
An associative array, each ID key is associated with a value.
Example 1
In this example we use an array to assign ages to the different
persons:
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";
The ID keys can be used in a script:
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
?>
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.
Example
$families = array ( "Griffin"=>array ( "Peter", "Lois","Megan"),
“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 while loop executes a block of code while
a condition is true.
Syntax
while (condition)
{
code to be executed;
}
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:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 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 is 2
The number is 3
The number is 4
The number is 5
The number is 6 The for loop and the foreach loop will be explained in the next
chapter.
The for loop is used when you know in
advance how many times the script should
run.
Syntax
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The foreach loop is used to loop through arrays.
Syntax
Output:
one
two
three
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)
A simple function that writes my name when it is called:
<html>
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes
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.
The following function has two parameters:
<html>
<body>
<?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("Ståle","?");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Ståle Refsnes?
To let a function return a value, use the return statement.
Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Output:
1 + 16 = 17
The most important thing to notice when
dealing with HTML forms.
</body>
</html>
Output
Welcome John!
You are 28 years old.
Variable name Description
$_SERVER Data about the currently running server.
$_ENV Data about the client’s environment.
$_GET Data posted to the server by the get method.
$_POST Data posted to the server by the post method.
$_COOKIE Data contained in cookies on the client’s computer.
$GLOBALS Array containing all global variables.
Some useful global arrays.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 <!-- env.php -->
5 <!-- Program to display environment variables -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Environment Variables</title>
10 </head>
11
12 <body>
13 <table border = "0" cellpadding = "2" cellspacing = "0"
14 width = "100%">
15 <?php
16
17 // print the key and value for each element
18 // in the $_ENV array
19 foreach ( $_ENV as $key => $value )
20 print( "<tr><td bgcolor = \"#11bbff\">
21 <strong>$key</strong></td>
22 <td>$value</td></tr>" );
23 ?>
24 </table>
25 </body>
26 </html>
The built-in $_GET function.
Used to collect values from a form sent with
method="get".
</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"
http://www.w3schools.com/welcome.php
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
client’s 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
it’s free!
Familiarity
Many of the language’s 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 case-
insensitive.
<?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 )
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;
Arithmetic Operators
$a + $b
$a - $b
$a * $b
$a / $b Division
$a % $b Modulus Remainder of $a / $b
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
Output is ……abcdefghijk
Logical Operators
// ...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!";
Processing Form Data
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
</head><body>
<p>form data processing</p>
<p> </p>
<form name="form1" method="post" action="form2.php" >
<p>name
<input type="text" name="name" value="">
</p> <p>age
<input type="text" name="age">
</p> <p>
<input type="submit" name="Submit" value="Submit">
</p>
</form><p> </p></body></html>
<?
$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 file’s 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. It’s 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 “amara’s 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)) :
<?
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
user’s 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>
<Body>
This is my page<br>
Below you see an applet<br>
<br>
<Applet
Code=“HelloWorld.class" width=200 Height=100>
</Applet>
</Body>
</Html>
Attribute -Explanation -Example
Code - Name of class file --- Code="myapplet.class“
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 alt="Menu Applet”
Align=
Left
Justifies the applet
according to the
Align=Right
Right,Top,Texttop text and images
Middle,Absmiddle surrounding it.
Baseline,Bottom
Absbottom
timestamp Optional. Specifies a timestamp. Default is the current date and time
Here are some characters that can be used:
◦ d - Represents the day of the month (01 to 31)
◦ m - Represents a month (01 to 12)
◦ Y - Represents a year (in four digits)
<?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.
◦ mktime(hour,minute,second,month,day,year,is_dst)
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
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"); ?>
Now, let's run the same example with the require() function.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
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
Interacting with databases
◦ SQL
Structured Query Language
Used to manipulate databases
◦ Several useful functions
mysql_connect
mysql_select_db
mysql_query
mysql_error
mysql_fetch_row
mysql_close
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.
mysql_connect(servername,username,password);
Parameter Description
servername Optional. Specifies the server to connect to. Default value is "localhost:3306"
username Optional. Specifies the username to log in with. Default value is the name of
the user that owns the server process
password 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
$con=mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
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);
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.
22
How to Create a Cookie?
◦ The setcookie() function is used to set a cookie.
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).
<?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);
?>
Gathering data to be written as a cookie.
27
1 <?php
2 // Fig. 26.21: cookies.php
3 // Program to write a cookie to a client's machine
4
5 extract( $_POST );
6 // write each form field’s value to a cookie and set the
7 // cookie’s expiration date
8 setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 );
9 setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 );
10 setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );
11 ?> Function setcookie takes the name of
12 the cookie to be set as the first
13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
argument, followed by the value to be
14 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
15
stored in the cookie. The optional third
16 <html xmlns = "http://www.w3.org/1999/xhtml">
argument specifies the expiration date of
17 <head> the cookie.
18 <title>Cookie Saved</title>
19 </head>
20
21 <body style = "font-family: arial, sans-serif">
22 <p>The cookie has been set with the following data:</p>
23
28
24 <!-- print each form field’s value -->
25 <br /><span style = "color: blue">Name:</span>
Each form field’s value is printed to
26 <?php print( $NAME ) ?><br />
confirm the data that has been set as a
27
28 <span style = "color: blue">Height:</span>
cookie with the user.
29 <?php print( $HEIGHT ) ?><br />
30
31 <span style = "color: blue">Favorite Color:</span>
32
33 <span style = "color: <?php print( "$COLOR\">$COLOR" ) ?>
34 </span><br />
35 <p>Click <a href = "readCookies.php">here</a>
36 to read the saved cookie.</p>
37 </body>
38 </html> Hyperlink to readCookies.php.
29
Writing a cookie to the client.
30
Reading cookies
◦ $_COOKIE environment variable
Array
◦ foreach loop to access each element
Split into key and value
31
Cookie storage
◦ Internet Explorer
Stores cookies in Cookies directory
Text file
32
Cookies directory before a cookie is written.
33
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 <!-- readCookies.php -->
5 <!-- Program to read cookies from the client's computer -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head><title>Read Cookies</title></head>
9
10 <body style = "font-family: arial, sans-serif">
11
12 <p>
13 <strong>
14 The following data is saved in a cookie on your
15 computer.
16 </strong>
17 </p>
18
34
19 <table border = "5" cellspacing = "0" cellpadding = "10">
20 <?php
The foreach PHPloop iterates
creates through
array the which
$_COOKIE
21
$_COOKIE array andall
contains prints the values
cookie name and valueby
indexed
22 // iterate through array $_COOKIE and print
23 // name and valueofofeach
each cookie
their in
cookie an XHTML table.
names.
24 foreach ( $_COOKIE as $key => $value )
25 print( "<tr>
26 <td bgcolor=\"#F0E68C\">$key</td>
27 <td bgcolor=\"#FFA500\">$value</td>
28 </tr>" );
29 ?>
30
31 </table>
32 </body>
33 </html>
35
Displaying the cookie’s content.
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.
<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
2
` In this lesson, you will learn:
◦ To understand a Web server’s functionality.
◦ To introduce Microsoft Internet Information Services
(IIS) and Apache Web server.
◦ To learn how to request documents from a Web
server.
3
` Web server
◦ Responds to client requests by providing resources
` URI (Uniform Resource Identifier)
` Web server and client communicate with
platform-independent Hypertext Transfer
Protocol (HTTP)
4
IIS 5.0 IIS 6.0 Apache Web server
Company Microsoft Microsoft Apache Software
Corporation Corporation Foundation
Version 5.0 6.0 2.0.47
Released 2/17/00 3/28/03 7/10/03
Platforms Windows 2000, Windows Server 2003 Windows NT/2000/XP,
Windows XP Mac OS X, Linux and
other UNIX-based
platforms,
experimentally supports
Windows 95/98
Brief The most popular The newest release of Currently the most
description Web server for IIS from Microsoft. popular Web server.
Windows 2000.
Price Included with Included with Freeware.
Windows 2000 Windows Server 2003
and Windows XP.
Web servers discussed in this chapter.
5
` Request methods
◦ get
◦ post
◦ Retrieve and send client form data to Web server
◦ Post data to a server-side form handler
6
` Multi-tier application (n-tier application)
◦ Information tier (data or bottom tier)
x Maintains data for the application
x Stores data in a relational database management
system (RDBMS)
◦ Middle tier
x Implements business logic and presentation logic
x Control interactions between application clients and
application data
◦ Client tier (top tier)
x Application’s user interface
x Users interact directly with the application through the
client tier
7
` Client-side scripts
◦ Validate user input
x Reduce requests needed to be passed to server
x Access browser
x 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
8
` Request documents from Web servers
◦ Host names
◦ Local Web servers
x Access through machine name or localhost
◦ Remote Web servers
x Access through machine name
◦ Domain name or Internet Protocol (IP) address
x Domain name server (DNS)
x Computer that maintains a database of host names and
their corresponding IP address
9
` An enterprise-level Web server that is
included with Windows
10
` FTP Site
◦ Used for transferring large files across the Internet
` HTTP Site
◦ Used most frequently to request documents from
Web servers
` SMTP Virtual Server
◦ Sends and receives electronic mail
` Web Site Content Directory
◦ Directory containing the documents that clients will
view
11
Internet Information Services window of Internet Services Manager.
12
Virtual Directory Creation Wizard welcome dialog.
13
Virtual Directory Alias dialog of the Virtual Directory Creation Wizard.
14
Web Site Content Directory dialog of the Virtual Directory Creation Wizard.
15
Access Permissions dialog of the Virtual Directory Creation Wizard.
16
Internet Information (IIS) Services Manager window.
17
Virtual Directory Creation Wizard welcome dialog.
18
Virtual Directory Alias dialog of the Virtual Directory Creation Wizard.
19
Web Site Content Directory dialog of the Virtual Directory Creation Wizard.
20
Access Permissions dialog of the Virtual Directory Creation Wizard.
21
` Currently the most popular Web server
` Stability
` Efficiency
` Portability
` Open-source
22
Apache Web server starting. (Courtesy of The Apache Software Foundation.)
23
` Requesting five different documents
◦ XHTML
◦ ASP.NET
◦ Perl
◦ PHP
◦ Python
24
` Request XHTML documents from IIS 6.0 or
Apache
◦ Launch Internet Explorer
◦ Enter XHTML document’s location in Address field
25
Requesting test.html from IIS 5.
26
` Request ASP.NET document from IIS 5 or 6
◦ Launch Internet Explorer
◦ Enter ASP.NET document’s location in Address field
` Apache support ASP Classic but doesn’t
support ASP.NET
27
Requesting test.aspx from IIS 5.
28
` Request Perl document from IIS 5 or 6
◦ Launch Internet Explorer
◦ Enter the Perl document’s location in the Address
field
` Request Perl document on Apache Web server
◦ Put all Perl documents in cgi-bin directory
◦ Launch Internet Explorer
◦ Enter Perl document’s location in Address field
29
Requesting test.pl from IIS 5.
30
Requesting test.pl from Apache.
31
` Request PHP documents from IIS 5 and 6
◦ Launch Internet Explorer
◦ Enter PHP document’s location in the Address field
` Request PHP documents from Apache
◦ Save PHP documents in the htdocs directory
◦ Launch Internet Explorer
◦ Enter PHP document’s location in Address field
32
Requesting test.php from IIS 5.
33
Requesting test.php from Apache.
34
` Request Python documents from IIS 5 and 6
◦ Launch Internet Explorer
◦ Enter Python document’s location in the Address
field
` Request Python documents from Apache Web
server
◦ Put Python documents in cgi-bin directory
◦ Launch Internet Explorer
◦ Enter Python document’s location in Address field
35
Requesting test.py from IIS.
36
Requesting test.py from Apache.
37
` www.microsoft.com/msdownload/ntoptionpack/askwiz.asp
` www.w3.org/Protocols
` www.apache.org
` httpd.apache.org
` httpd.apache.org/docs-2.0
` www.apacheweek.com
` linuxtoday.com/stories/18780.html
` www.iisanswers.com
` www.iisadministrator.com
38