introduction to web programming - mycigroup.com · chapter 1: introduction to web programming ......

105
Introduction to Web Programming: Design Notes My CI Group Holger Findling

Upload: dangkhanh

Post on 09-Jun-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Introduction to Web Programming: Design Notes

M y C I G r o u p

Holger Findling

Page 2: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Introduction to Web Programming:

Design Notes

© 2010. My CI Group. All rights reserved.

Page 3: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts
Page 4: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Table of Contents Chapter 1: Introduction to Web Programming .......................................................................... 1

Internet Standards ................................................................................................................ 2 Overview ................................................................................................................................ 3 Web Design Styles ................................................................................................................. 4 Web Site Performance ........................................................................................................... 5 Site Score ............................................................................................................................... 6

Overall Site Score............................................................................................................... 6 Get In Google ..................................................................................................................... 6 Link Building ..................................................................................................................... 6 Meta Tags .......................................................................................................................... 6 Social Networking...............................................................................................................7 Broken Links.......................................................................................................................7

Site Score Example .................................................................................................................7 Required Software and Tools ................................................................................................ 9

Web Server ........................................................................................................................ 9 MySQL ............................................................................................................................... 9 PHP .................................................................................................................................... 9 Web Development Software .............................................................................................. 9

Software Downloads and Installation ................................................................................... 9

Verification .......................................................................................................................10

Chapter 2: HTML and XHTML ............................................................................................... 11

Structure of an HTML document ......................................................................................... 11

Formatted Text ................................................................................................................. 14 Acronym, Abbreviation, and Bold Text ............................................................................ 15 Headers ............................................................................................................................. 16 Unordered List ................................................................................................................. 17 Ordered List ...................................................................................................................... 18 Definition List ................................................................................................................... 19 Images ............................................................................................................................. 20 Document Links .............................................................................................................. 22

Exercise 2.1 .......................................................................................................................... 23

Chapter 3: Cascading Style Sheet ........................................................................................... 25

Style Declarations................................................................................................................ 25 Style Rules ........................................................................................................................... 26

Comments ........................................................................................................................ 26 Styling the body ............................................................................................................... 26 Class and ID Selectors ..................................................................................................... 26

CSS Page Layout .................................................................................................................. 28 Positioning .......................................................................................................................... 28

Static Positioning ............................................................................................................. 28 Relative Positioning ......................................................................................................... 29 Absolute Positioning ........................................................................................................ 29 Fixed Positioning ............................................................................................................. 29

Page 5: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Exercise 3.1 .......................................................................................................................... 29

style.css ............................................................................................................................ 29 Index.html ........................................................................................................................ 31

Exercise 3.2 ......................................................................................................................... 33

Style.css ........................................................................................................................... 34 Index.html ....................................................................................................................... 37

CSS Validation ..................................................................................................................... 39

Chapter 4: Web Page Design .................................................................................................. 40

Monitor Sizes and Resolutions ........................................................................................... 40 Web Site Architecture ......................................................................................................... 40

Define Goals .................................................................................................................... 40 Define Audience .............................................................................................................. 40 Create and Organize Content .......................................................................................... 40 Formulate Visual Presentation Concepts ........................................................................ 40 Develop Site Map and Navigation ................................................................................... 40 Design and Produce Visual Forms ................................................................................... 41 Designing Layout Grid System ......................................................................................... 41

Composition ........................................................................................................................ 42

Chapter 5: Forms .................................................................................................................... 44

Forms ............................................................................................................................... 45 Fieldset ............................................................................................................................ 45 Legend ............................................................................................................................. 45

Exercise 5.1 .......................................................................................................................... 46

Cascading Style Sheet ...................................................................................................... 46 XHTML ............................................................................................................................ 48 Input Text ........................................................................................................................ 50 Password ........................................................................................................................... 51 Textarea ............................................................................................................................ 51

Exercise 5.2 ......................................................................................................................... 52

Chapter 6: Server Side Programming ..................................................................................... 55

PHP Basics .......................................................................................................................... 55

Scalar and Compound Data Types .................................................................................. 56 Comments, Variables, and Operators ............................................................................. 56 Strings ............................................................................................................................... 57 Predefined Variables ....................................................................................................... 58 Arrays .............................................................................................................................. 58 If statements .................................................................................................................... 60 Switch statement .............................................................................................................. 61 While Loop ...................................................................................................................... 62 For Loop .......................................................................................................................... 63

Processing Forms ................................................................................................................ 63

Processing Text Input ...................................................................................................... 64 Processing Control Elements .......................................................................................... 65

PHP Templates and Controllers.......................................................................................... 68

Page 6: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Chapter 7: MySQL Database ................................................................................................... 70

Database Schema ................................................................................................................ 70 PHP Functions for Interfacing with MySQL ........................................................................ 71 Database Connection ........................................................................................................... 71 Creating a dynamic pull-down menu .................................................................................. 72 Inserting Data into the Database ........................................................................................ 76

Chapter 8: Client Side Programming ..................................................................................... 78

JavaScript ............................................................................................................................ 78 JavaScript Basics ................................................................................................................. 78

Variables, Operators, and Comments ............................................................................. 79 Arrays ............................................................................................................................... 81 If statements ..................................................................................................................... 81 Switch construct .............................................................................................................. 82 While Loop ...................................................................................................................... 82 For Loop .......................................................................................................................... 82 Functions ......................................................................................................................... 83

Date/ Time .......................................................................................................................... 83

Date and Time Example .................................................................................................. 84

Processing Images ............................................................................................................... 87 Dialog Windows .................................................................................................................. 88

Alert Dialog ...................................................................................................................... 88 Confirm Dialog ................................................................................................................ 89 Prompt Dialog ................................................................................................................. 90

Processing Navigation Bar Images...................................................................................... 92

Chapter 9: Document Object Model and Dynamic HTML ..................................................... 94

Exercise 9.1 .......................................................................................................................... 95

References ............................................................................................................................... 98 Index ....................................................................................................................................... 99

Page 7: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Chapter 1: Introduction to Web Programming The Internet is a global network that connects IP networks. The Internet evolved from the ARPANET, a U.S. Department of Defense Advanced Research Projects Agency (DARPA). ARPANET transitioned to the Internet in the late 1980s as NFSnet, the U.S. National Science Foundation’s network of Universities and supercomputing centers. The Web consists of the following components: Clients – Web browsers that enable users to access the Web. Servers – Running programs that serve information to the Web. Documents – Web pages, coded in HTML that supply information on the Web. Protocols – The Hypertext Transfer Protocol (HTTP) that Web clients and servers use to communicate to one another and the TCP/IP (Transmission Control Protocol/ Internet Protocol) on which HTTP depends. The domain name system (DNS) provides a distributed database service that supports dynamic update and retrieval of information contained in the name space. The Web browsers use DNS to obtain address information for a target host before making contact with the server. The DNS organizes the Internet name space into a large tree.

ROOT

COM ORG NET GOV EDU

W3C SCS UCF USF

Figure #1. Web Organization

Page 8: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

1: I

ntr

od

uct

ion

to

Web

Pro

gra

mm

ing

2

Internet Standards World Wide Web (WWW) Consortium (W3C) is a non-profit organization responsible for developing open web standards. The W3C XHTML2 Working Group was chartered in March 2007 until December 2010 to develop techniques using RelaxNG and extending XHTML 2.0. XHTML 2.0 is a markup language intended for rich, portable web-based applications. It is an XHTML Host Language as defined in Modularization of XHTML. It is made up of a set of XHTML Modules that together describe the elements and attributes of the language, and their content model. While the ancestry of XHTML 2.0 comes from HTML 4, XHTML 1.0, and XHTML 1.1, it is not intended to be 100% backwards compatible with its earlier versions. There are three types of XHTML documents which are XHTML 1.0 Strict, Transitional, and Framset.

XHTML 1.0 Strict - Use Strict when you want really clean structural mark-up, free of any markup associated with layout. Use this together with W3C's Cascading Style Sheet (CSS) language to get the font, color, and layout effects.

XHTML 1.0 Transitional – Use when writing Web pages for the general public. The idea is to take advantage of XHTML features including style sheets but nonetheless to make small adjustments to markup for the benefit of those viewing pages with older browsers which can't understand style sheets. These include using the body element with bgcolor, text and link attributes.

XHTML 1.0 Frameset - Use when you want to use Frames to partition the browser window into two or more frames.

For detailed description of the markup language see http://www.w3.org/MarkUp/.

Page 9: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

1: I

ntr

od

uct

ion

to

Web

Pro

gra

mm

ing

3

Overview Refer to Figure #1.2 for the following discussion. The user interacts with the Internet using a web browser and requests a document. The web browser establishes communication with the appropriate server and requests the document. The Apache server verifies if the requested document contains a PHP script. If the document contains PHP script, then the PHP interpreter has to create the HTML document before it is returned to the web browser. The document returned to the browser may only contain (X) HTML code. The PHP server may have to connect to the MySQL server to obtain data from the relational database. The PHP language includes a library with a rich set of built-in database functions. Once the document is constructed the Apache server returns the HTML document to the web browser. The web browser may execute Java Scripts to animate data or to provide an interactive environment to the user.

Relational Database

MySQL Server

PHP Server

Apache Server

Scripting Languages

Internet Browser

UsersUser browses the Internet

and requests a document

The Internet browser requests the

the document from the Apache

server

The Apache server uses the PHP server

to build the HTML Document

The PHP Server establishes connection with the

database using MySQL server. It obtains the

information from the database to create the document.

MySQL server provides the interface

between PHP and the relational database

JavaScript and DOM provides for dynamic Web

programming. It allows the user to manipulate

data on the client side.

Client Side

Server Side

Figure #1.2 Overview

Page 10: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

1: I

ntr

od

uct

ion

to

Web

Pro

gra

mm

ing

4

Web Design Styles

Page 11: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

1: I

ntr

od

uct

ion

to

Web

Pro

gra

mm

ing

5

Web Site Performance

Table #1.1 Statistics

Figure #1.3 Statistics

MonthUnique

visitors

Number

of visitsPages Hits

Bandwidth

(MB)

Jan-10 6 42 204 3397 9.17

Feb-10 45 194 1393 6488 117.5

Mar-10 71 356 1162 6591 89.59

Apr-10 167 492 1317 6695 171.85

May-10 68 408 1686 11509 143.71

Jun-10 70 352 1086 8109 100.53

Jul-10 128 275 853 6006 121.37

Aug-10 237 372 968 5728 124.66

Sep-10 244 367 973 4964 241.68

Oct-10 348 517 1575 6167 441.3

Nov-10 299 405 1164 6345 240.41

Dec-10 349 533 2345 10781 223.07

0

2000

4000

6000

8000

10000

12000

14000

Unique visitors

Number of visits

Pages

Hits

Bandwidth (MB)

Page 12: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

1: I

ntr

od

uct

ion

to

Web

Pro

gra

mm

ing

6

Reported

period Month Dec 2010

First visit NA

Last visit 31 Dec 2010 - 11:43

Unique visitors Number of visits Pages Hits Bandwidth

Viewed traffic *

349

533 (1.52 visits/visitor)

2347 (4.4 Pages/Visit)

10806 (20.27 Hits/Visit)

223.37 MB (429.13 KB/Visit)

Not viewed traffic *

1429 2669 136.06 MB

Figure #1.4 Monthly Status

Site Score

Overall Site Score The overall site score is ranked on a scale of 0 to 100. The ranking determines how well the web pages comply with Google’s guidelines. A higher ranking provides for greater traffic. 1 to 49 Poor 50 to 79 Average 80 to 90 Good 90 to 100 Excellent

Get In Google Site pages must be listed with Google to allow the search engine to rank the pages. The greater ranking increases the chance of people finding the web site. Frequent re-submission helps maintain the page rankings.

Link Building The ranking of a Web Site is increased with the number of back-links. There are many opportunities to create back-links; however not all of the back-links will significantly increase traffic and boost search rank. A free text link can be established using Attracta Directory, which lists the Web Site’s business information. After approval by Attracta staff, the web site business listing and description will appear in the Attracta Directory with a link to the website.

Meta Tags The Title and Meta description tags of web pages are displayed in Google's search results. Clear and well-written titles and descriptions that conform to length standards, is an essential part of getting customers to visit your site over your competitors.

Page 13: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

1: I

ntr

od

uct

ion

to

Web

Pro

gra

mm

ing

7

Good title tags have between 10 and 69 characters, while good description tags have between 50 and 156 characters.

Social Networking Use the power of Social networking to promote your site! Twitter and Facebook are considered top social networking sites.

Broken Links A broken link is the easiest way to lose visitors. Broken and invalid links reduces the search ranking. Typical error codes are: 403 Forbidden 404 Not Found 500 Internal Server Error SEO Badge Adding the SEO Badge to the Web site provides:

Better navigation for your visitors through a text based site map

Google powered site-wide search box

Rank building, two-way link between your site and Attracta.com

Better listings in search engines that don't support XML Sitemaps

Higher Google rank for sites with good navigation

Site Score Example

Figure #1.5 Overall Site Score

Overall Site Score

Overall Site Score61

Get In Google67

Link Building0

Meta Tags92

Social Networking0

Broken Links100

SEO Badge100

Top Local

Targeted Traffic

Page 14: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

1: I

ntr

od

uct

ion

to

Web

Pro

gra

mm

ing

8

Figure #1.6 Overall Site Score Analysis

Symbol Category Score

Get In Google 67

A 35 page XML Sitemap was created and last submitted on: 2010-11-13. Google first

crawled site on: 2010-09-06. Sitemap read by search engines 145 times. No pages

remain to be added to Sitemap.

Link Building 0

Site listed in the Attracta Customer Directory on Not Yet. Good description text: No.

>1 categories listed: No. Logo added: No.

Meta Tags 92

During the last analysis of your site 3 pages had problems. There are a total of 1 title

tag problems and 3 meta description problem.

Social Networking 0

Use the power of Social Networking to promote your site!

Twitter linked: No. Facebook linked: No.

Broken Links 100

There were 0 broken links found during the last analysis of your site on 2010-11-13.

SEO Badge 100

Badge with HTML site map and Google site-search installed on 2010-12-10 . Badge

viewed 51 times. Last viewed on 2010-12-31 .

Page 15: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

1: I

ntr

od

uct

ion

to

Web

Pro

gra

mm

ing

9

Required Software and Tools

Web Server A Web Server provides user requested documents to a web browser, such as Internet Explorer or Firefox. Typical web server software used today is Apache and Internet Information Services (IIS).

MySQL MySQL is a relational database management system (RDBMS).

PHP PHP is a server-side scripting language that provides an interface to the MySQL server.

Web Development Software There are many web development software tools available, including Apple iWeb, Adobe Dreamweaver CS5, Adobe Fireworks CS4, Microsoft Front Page, and MS Visual Web Developer. Of course it is not necessary to use any of these tools; a simple text editor is all that is required to develop html, PHP and Java scripts.

Software Downloads and Installation The following tools are required for the Web Programming course.

Microsoft Visual Web Developer 2010 Express Edition for Windows 7

Microsoft Visual Web Developer 2008 Express Edition for Windows XP

Apache 2.2 or newer version

PHP/5.3.2 or newer version

MySQL Workbench 5.2 OSS or newer version

Visit http://www.microsoft.com/express/Web/ and download the MS Visual Web Developer software. Visit http://www.wampserver.com/en/download.php and download the WampServer, which includes:

Apache 2.2

PHP 5.3.3

MySQL 5.5

PhpMyadmin

Page 16: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

1: I

ntr

od

uct

ion

to

Web

Pro

gra

mm

ing

10

Verification Display the hidden icons on the taskbar and select “Running all Apache services” by right clicking on the icon. Select Open Apache Monitor. When the Apache Monitor window is open verify that “Apache/2.2.14 (Win32) PHP/5.3.2” is displayed at the bottom of the window. This message implies that the Apache Server and PHP are running.

Page 17: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

11

Chapter 2: HTML and XHTML

Structure of an HTML document The HTML document is comprised of 3 components

1. HTML Version information 2. Header Section 3. Body

Note: We will ignore the preferred length of title and description in the following examples. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <!-- Row 1 --> <div> <br/> <p> Welcome. </p> <br/> <p> This is my first Web Site. </p> </div> </body> </html>

Page 18: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

12

Comments are implemented between the tags <!-- Comments -->

div <div> … </div> The division block denotes a generic division within a document. The element is used to add a customizable block to the document. Using <div> provides important structure to the webpage. p <p> … </p> Denotes a paragraph. It is typically nested inside a division. h1, h2, h3, h4, h5, h6 <h1> … </h1> There are 6 different size headers available. A header should not be nested inside a paragraph tag <p>.

br </br> Insert a line break into the document. It should not be nested inside a paragraph tag <p>.

strong <strong> … </strong> The text will be displayed in bold font. Designers should use <strong> instead of <b> since web audio readers interpret the tag <strong> by speaking the text a little louder. b <b> … </b> The encapsulated text is displayed in bold type fond. It is not supported by html 5.0 abbr <abbr> … </abbr> Denotes abbreviation.

Page 19: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

13

acronym <acronym> … </acronym> Denotes an acronym.

Page 20: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

14

Formatted Text <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <!-- Formated Text --> <div> <h4> Robert Frost: The Man and His Work - 1923 </h4> <p> "My definition of poetry (<em><small> if I were forced to give one </small></em>) would be this: words that become deeds." </p> <p> "All <em><strong> poetry </strong></em> is a reproduction of the tones of actual speech." </p> </div> </body> </html>

Output:

Robert Frost: The Man and His Work - 1923

"My definition of poetry ( if I were forced to give one ) would be this: words that become deeds."

"All poetry is a reproduction of the tones of actual

Page 21: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

15

Acronym, Abbreviation, and Bold Text <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <!-- Row 1 --> <div> <br/> <p> Welcome. </p> <br/> <p> How to create an acronym. The acronym for World Wide Web is: <acronym title="World Wide Web">WWW</acronym>. </p> <p> How to abbreviate text. World Wide Web is abbreviated: <abbr title="World Wide Web">WWW</abbr>. </p> <p> It is possible to display bold type text. <strong> "World Wide Web"</strong>. </p> <p> We can nest elements. World Wide Web is abbreviated: <abbr title="World Wide Web"><b>WWW</b></abbr>. </p> </div> </body> </html>

Output:

Welcome.

How to create an acronym. The acronym for World Wide Web is: WWW. How to abbreviate text. World Wide Web is abbreviated: WWW. It is possible to display bold type text. "World Wide Web". We can nest elements. World Wide Web is abbreviated: WWW.

Page 22: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

16

Headers <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <!-- Row 1 --> <div> <p> <br/> Welcome. </p> <p> The following example displays different size headers. <br /> <h1>Header 1</h1> <h2>Header 2</h2> <h3>Header 3</h3> <h4>Header 4</h4> <h5>Header 5</h5> <h6>Header 6</h6> </p> </div> </body> </html>

Output:

Welcome. The following example displays different size headers.

Header 1 Header 2 Header 3

Header 4

Header 5

Header 6

Page 23: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

17

Unordered List

<ul> <li> … </li> <li> … </li> </ul> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <!-- Row 1 --> <div> <p> <h3>Introduction to Web Programming</h3> <h4>References</h4> <ul> <li>An Introduction to Web Design + Programming</li> <li>Web Design in a Nut Shell</li> <li>Building your own Web Site the Right Way using HTML & CSS</li> <li>Fancy Form Design</li> </ul> </p> </div> </body> </html>

Output: Introduction to Web Programming

References

An Introduction to Web Design + Programming Web Design in a Nut Shell Building your own Web Site the Right Way using HTML & CSS Fancy Form Design

Page 24: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

18

Ordered List <ol> <li> … </li> <li> … </li> </ol> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <!-- Row 1 --> <div> <p> <h3>Introduction to Web Programming</h3> <h4>References</h4> <ol> <li>An Introduction to Web Design + Programming</li> <li>Web Design in a Nut Shell</li> <li>Building your own Web Site the Right Way using HTML & CSS</li> <li>Fancy Form Design</li> </ol> </p> </div> </body> </html>

Output: Introduction to Web Programming

References

1. An Introduction to Web Design + Programming 2. Web Design in a Nut Shell 3. Building your own Web Site the Right Way using HTML & CSS 4. Fancy Form Design

Page 25: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

19

Definition List dl <dl> … </dl> Defines a definition list, which includes terms <dt> and definitions <dd> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <!-- An example of definition list --> <div> <dl> <dt><strong>An Introduction to Web Design + Programming</strong></dt> <dd>A textbook for web programming ... </dd> <dt><strong>Web Design in a Nut Shell</strong></dt> <dd>A reference book for web design ... </dd> </dl> </div> </body> </html>

Output: An Introduction to Web Design + Programming

A textbook for web programming ... Web Design in a Nut Shell

A reference book for web design ...

Page 26: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

2

0

Images

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <!-- Working with Images --> <div> <h4> Welcome to Riverside </h4> <br /> <p> <img src = "Images/Riverside.JPG" alt = "Riverside" /> </p> </div> </body> </html>

Output: Welcome to Riverside

Page 27: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

21

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <!-- Working with Images --> <div style = "width: 550px"> <h4> Welcome to Riverside </h4> <p> <img src = "Images/Riverside.JPG" alt = "Riverside" width="330" height="220" style="float: left; margin-right: 1em; margin-bottom: 8px; margin-top: 8px"/> <br /><br /><br /><br /><br /><br /><br /> The river moves lazily towards Riverport. As the evening sets in people settle outside to observe life on the river. </p> </div> </body> </html>

Output:

Page 28: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

22

Document Links <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Web Site 1</title> <meta name="description" content="Example of a simple Web Page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <div> <h4> Recommended Book List</h4> <ul> <li> <a href="Documents/Book1.pdf" type="pdf"> Book 1 (pdf)</a> </li> <li> <a href="Documents/Book2.pdf" type="pdf"> Book 2 (pdf)</a> </li> </ul> </div> </body> </html>

Output:

Recommended Book List

Book 1 (pdf) Book 2 (pdf)

Page 29: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

23

Exercise 2.1 Design a simple Web Site which is comprised of three web pages. Navigation between the individual pages should be established using an unordered list. Page #1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Exercise 2.1</title> <meta name="description" content="Design a Web Site that is comprised of three web pages. Provide for navigation between any page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body style="width:500px"> <div> <br /> <h2> Exercise 2.1</h2> </div> <div> <h4> Site Navigation</h4> <ul> <li> <a href="page2.html"> Page 2 </a> </li> <li> <a href="page3.html"> Page 3 </a> </li> </ul> </div> </body> </html>

Page #2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Exercise 2.1</title> <meta name="description" content="Design a Web Site that is comprised of three web pages. Provide for navigation between any page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body style="width:500px">

Page 30: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

2:

HT

ML

an

d X

HT

ML

24

<div> <br /> <h2> Page 2</h2> </div> <div> <h4> Site Navigation</h4> <ul> <li> <a href="index.html"> Home </a> </li> <li> <a href="page3.html"> Page 3 </a> </li> </ul> </div> </body> </html>

Page #3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Exercise 2.1</title> <meta name="description" content="Design a Web Site that is comprised of three web pages. Provide for navigation between any page." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body style="width:500"> <div> <br /> <h2> Page 3</h2> </div> <div> <h4> Site Navigation</h4> <ul> <li> <a href="index.html"> Home </a> </li> <li> <a href="page2.html"> Page 2 </a> </li> </ul> </div> </body> </html>

Page 31: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

25

Chapter 3: Cascading Style Sheet A Web page has two important aspects: document structure and presentation style. The cascading style sheet (CSS) is a language that specifies the presentation style. It contains one or more style rules which are applied to the html code. CSS is the recommended language by W3C and supported by most major browsers. CSS replaced the former architectural style of Web design; tables should not be used to create the structural layout of a web page. The cascading style sheet is a text file and uses the .css suffix. Reference to a style sheet must be provided in the header section of the html code. <head> <title>Style Sheets</title> <meta name="description" content="Example of a simple Web Page using a style sheet." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <link href="style.css" rel="stylesheet" type="text/css" /> </head>

Style Declarations

Style sheets are comprised of rules which describe how a page element should be displayed.

The XHTML markup forms the structural layer upon which the presentation layer is applied.

Style sheets may not include any html code. A clear division is enforced between the XHTML

markup and the cascading style sheets.

The structure of a style rule is comprised of a selector, declarations, properties and

associated values.

Selector { Declaration: value ; Property : Value }

Page 32: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

26

Style Rules

Comments Comments are incorporated using the /* comments */ convention.

Styling the body The body of the document can be styled and should define the overall presentation of the

page. The physical size and positioning information is can also be provided to the web

browser.

In this example body is also referred to the selector and properties of the selector are declared inside the { }. The property font-family has three fonts assigned, Georgia, Verdana, followed by all sans-serif. The web browser will try and apply the first value, and if it is not available apply the second value; and so on. If none of the specified fonts are available the web browser will use its default font.

body { font-family: Georgia, Verdana, sans-serif; background-color: #aaccaa; position: absolute; width: 1000px; left: 50%; margin-left: -500px; }

Class and ID Selectors

The web developer can define Class and ID selectors. These types of selectors are

independent of document elements.

As an example the <div> tag is styled using the class .style11. .style11 is a user defined class which defines the size of a region and declares the background color.

<div class="style11"> ... </div>

Page 33: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

27

.style11 { position: absolute; top: 0px; padding-top: 5px; width: 780px; height: 120px; background-color:#10aa10; }

Elements of a class can be further styled using the dot (.) operator. For example the first letter in a paragraph can be altered to make it more aesthetically visible by setting the font-size to 200%. The web browser interprets the rule and increases the size of the first letter to double the size of the other characters. p.drop:first-letter { font-size: 200%; font-weight: bold; float: left; margin-right: 3px; margin-bottom: -6px; }

:first-letter is called a pseudo-element. A pseudo class works as if a class was applied to a group of elements. It allows the developer to define an action, such as rollover. In the example below the font for a link and its desired behavior is defined for mouse-over. Care must be taking to maintain the order of the individual pseudo-classes. a { font-weight: normal; } a:link { color: black; } a:visited { color: black; text-decoration: none; } a:hover { color: white; background-color: #000000; text-decoration: none; } a:active { color: white; background-color: #7070aa; }

Page 34: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

2

8

CSS Page Layout Before detailing a web page an overall physical layout of the web page is required. Consider the following layout of a 1000 x 630 pixel large web page. The page is padded on the top of the screen with 5 pixels to provide for a small buffer space. The page is divided into 3 horizontal sections, where the center is the largest component. The top section is reserved for a title section and perhaps a logo. The center section is further divided into three sections, which can be used for a menu, content section, and maybe an advertisement section on the far right. The bottom section can be used for displaying credentials.

Figure 3.1

Positioning There are four types of positioning.

Static

Relative

Absolute

Fixed

Inherited

Static Positioning This is the normal positioning scheme in which element boxes are rendered in order as they appear in the document flow.

Page 35: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

29

Relative Positioning Relative positioning moves the element box, but its original space in the document flow is preserved.

Absolute Positioning Absolutely positioned objects are completely removed from the document flow and are positioned relative to their containing block. Because they are removed from the document flow, they no longer influence the layout of surrounding elements, and the space they once occupied is closed up. Absolutely positioned elements always take on block behaviors.

Fixed Positioning Fixed poisoning is like absolute positioning, but instead of a containing element, it is positioned relative to the viewport.

Exercise 3.1 Implement the physical layout defined in Figure 1. The overall style of the body should be defined first in the style sheet, and then is followed by the physical page layout. This can be accomplished by using Selectors.

style.css body { font-family: Georgia, Verdana, Sans-Serif; background-color: #aaccaa; position: absolute; width: 1000px; left: 50%; margin-left: -500px; }

Defining the top row: .style11 { position: absolute; top: 0px; padding-top: 5px; width: 780px; height: 120px; background-color:#10aa10; }

Page 36: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

3

0

.style12 { position: absolute; top: 0px; padding-top: 5px; left: 780px; width: 220px; height: 120px; background-color:#10bb10; }

Defining the center section: .style21 { position:absolute; top: 125px; width: 170px; height: 480px; background-color:#107710; } .style22 { position: absolute; top: 125px; left: 170px; width: 610px; height: 480px; background-color:#108810; } .style23 { position: absolute; top: 125px; left: 780px; width: 220px; height: 480px; background-color:#109910; }

Defining the bottom section: .style31 { position: absolute; top: 605px; width: 1000px; height: 25px; background-color:#106610; }

Page 37: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

31

Defining the header styles: h4 { text-align: left; padding-left: 20px; font-family: Georgia; font-size: 12px; } h5 { text-align: left; padding-left: 20px; font-family: Georgia; font-size: 10px; }

Defining text styles: .text31 { text-align: center; padding-left: 20px; font-family: Georgia; font-size: 10px; }

Index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml> <head> <title>Style Sheets</title> <meta name="description" content="Example of a simple Web Page using a style sheet." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <!-- Row 1 Column 1 --> <div class="style11"> <h4> Row 1 Column 1</h4> </div> <!-- Row 1 Column 2 --> <div class="style12"> <h4> Row 1 Column 2</h4> </div>

Page 38: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

32

<!-- Row 2 Column 1 --> <div class="style21"> <h4> Row 2 Column 1</h4> </div> <!-- Row 2 Column 2 --> <div class="style22"> <h4> Row 2 Column 2</h4> </div> <!-- Row 2 Column 3 --> <div class="style23"> <h4> Row 2 Column 3</h4> </div> <!-- Row 3 Column 1 --> <div class="style31"> <p class="text31"> Row 3 Column 1</p> </div> </body> </html>

Page 39: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

33

Exercise 3.2 Design a Webpage that has a title, navigation bar and a vertically divided content area. The

styling of the page shall be defined using a cascading style sheet.

The physical layout of the web page is shown below.

The top of the page is padded by 5 pixels and each content area is padded left and right by 20

pixels.

The navigation bar area is displayed horizontally and its size is 1000 x 45 pixels.

780 x 85

Padding

220 x 85

460 x 550

1000 x 45

460 x 550

Physical Layout

Page 40: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

34

Style.css /* Body */ body { font-family: Georgia, Verdana, Arial, Sans-Serif; background-color: #404040; position: absolute; width: 1000px; left: 50%; margin-left: -500px; } /* Top Row */ .style11 { position: absolute; top: 0px; padding-top: 5px; width: 780px; height: 85px; background-color: #606090; } .style12 { position: absolute; top: 0px; padding-top: 5px; left: 780px; width: 220px; height: 85px; background: #606090 url(Images/logo.jpg) no-repeat top; } /* Menu Section */ div.navigationStyle { position:absolute; top: 90px; width: 1000px; height: 45px; background-color:#7070aa; } div.navigationStyle > span.self { font-weight: bold; color: #000000; padding: 3px; } a { font-weight: normal; } a:link { color: black; } a:visited { color: black; text-decoration: none; }

Page 41: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

35

a:hover { color: white; background-color: #000000; text-decoration: none; } a:active { color: white; background-color: #7070aa; } /* Middle section */ .style31 { position:absolute; top: 135px; width: 460px; height: 550px; background-color: #bbbbbb; padding-left: 20px; padding-right: 20px; } .style31 img { border: 7px solid #606090; } .style32 { position: absolute; top: 135px; left: 500px; width: 460px; height: 550px; background-color: #bbbbbb; padding-left: 20px; padding-right: 20px; } .style32 img { border: 7px solid #606090; } /* Title */ .title { text-align: center; padding-left: 20px; font-family: Georgia; font-size: 24px; font-weight: bold; } p { text-align: left; padding-left: 5px; font-family: Georgia; font-size: 12px; }

Page 42: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

36

p.drop:first-letter { font-size: 200%; font-weight: bold; float: left; margin-right: 3px; margin-bottom: -6px; } h4 { text-align: left; padding-left: 20px; font-family: Georgia; font-size: 12px; } h5 { text-align: left; padding-left: 20px; font-family: Georgia; font-size: 10px; } li { text-align: left; padding-left: 10px; padding-top: 5px; font-family: Tahoma; font-size: 13px; } div { SCROLLBAR-ARROW-COLOR:#716142; SCROLLBAR-FACE-COLOR:#FCF8F0; SCROLLBAR-TRACK-COLOR:#FCF8F0; SCROLLBAR-HIGHLIGHT-COLOR:#716142; SCROLLBAR-SHADOW-COLOR:#716142; SCROLLBAR-3DLIGHT-COLOR:#FCF8F0; SCROLLBAR-DARKSHADOW-COLOR:#FCF8F0; } div.g { SCROLLBAR-ARROW-COLOR:#6B593B; SCROLLBAR-FACE-COLOR:#E3DACB; SCROLLBAR-TRACK-COLOR:#E3DACB; SCROLLBAR-HIGHLIGHT-COLOR:#6B593B; SCROLLBAR-SHADOW-COLOR:#6B593B; SCROLLBAR-3DLIGHT-COLOR:#E3DACB; SCROLLBAR-DARKSHADOW-COLOR:#E3DACB; }

Page 43: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

37

Index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml> <head> <title>Exercise 3.2</title> <meta name="description" content="Example of a simple Web Page using a style sheet." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <!-- Title --> <div class="style11"> <p class="title"> Welcome to my Website </p> </div> <!-- Logo --> <div class="style12" > </div> <!-- Navigation Row 2 --> <div class="navigationStyle"> <br /> <span class="self">Navigation</span>| <a href="index.html" > Home</a>| <a href="page2.html" > Page 2</a>| <a href="aboutUS.html" > About US</a>| </div> <!-- Row 3 Small Space --> <div class="style31"> <br /> <h3> Riverside </h3> <p class="drop" > Paragraphs can be styled such that the first letter has a drop cap effect. The first letter is bold and 200 percent the size of all other letters. </p> <p class="drop"> The river moves lazily towards Riverport. The old styled building and waterwheel offers a warm welcome to travelers on the river. <img src = "Images/Riverside.JPG" alt = "Riverside" width="330" height="220" style="float: left; margin-right: 1em; margin-bottom: 8px; margin-top: 8px"/> As the evening sets in people settle outside to observe life on the river. From the distance one could hear a horse and carriage approaching without hurry steadily moving.

Page 44: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

3

8

</p> </div> <div class="style32"> <br /> <h3> My Journey </h3> <p class="drop" > This paragraph is styled such that the first letter has a drop cap effect. The first letter is bold and is 200 percent the size of all other letters. </p> <p> <img src = "Images/Carriage.JPG" alt = "Carriage" width="220" height="330" style="float: left; margin-right: 1em; margin-bottom: 8px; margin-top: 8px"/> </p> <p class="drop" > Inventing a new job is better than finding a new job. </p> </div> </body> </html>

Page 45: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

3:

Ca

sca

din

g S

tyle

Sh

eet

39

CSS Validation XHTML and CSS validation verifies your implementation for errors and compliance with W3C standards. Many validation services are available on the Internet and the service is provided free by W3C. Most Web developing tools also have such capability built-in. For XHTML and CSS validation visit the W3C sites. http://validator.w3.org/ http://jigsaw.w3.org/css-validator/

Page 46: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

4:

Web

Pa

ge

Des

ign

4

0

Chapter 4: Web Page Design

Monitor Sizes and Resolutions

Web Site Architecture

Define Goals What is the mission or purpose of the organization? What are the short term and long term goals of the web site? Who are the intended audiences? Does the site provide a well-defined service or sell a specific product?

Define Audience Who are the intended users? How will users interact with the web site? Who is the competition?

Create and Organize Content Which pages are static and which pages are dynamic? What will be the function of the pages? What transactions will the user perform? Should copyright notices or privacy statements be displayed? Are logon pages required?

Formulate Visual Presentation Concepts Define the concept. Draw or sketch the pages. Capture to phrases to the pages.

Develop Site Map and Navigation Create a page hierarchy. Determine the links between the pages. Create cross-links between pages. Ensure every page can be reached, no dead ends.

Page 47: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

4:

Web

Pa

ge

Des

ign

41

For large web sites create a top navigation schema and include it on every page. Determine section titles and use the title as a link.

Design and Produce Visual Forms The visual form defines how the web site looks. It refers to the visual layout, graphics, colors, charts and images.

Designing Layout Grid System Create an organizational framework. The framework establishes the divisions and groupings of the page.

Page 48: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

4:

Web

Pa

ge

Des

ign

42

Composition

Composition is the selection and arrangement of subjects within the viewing area of a web

page. When placing an object in the center of the screen it projects a static appearance and

becomes uninteresting. Static appearances are not ideal for advertising a product or services.

An easy way to improve a composition is to use the rule of thirds.

Figure 4.1 shows an image of size 4000 x 3000. It is divided by two vertical and two horizontal lines such that the image is divided into thirds. Placing the object of interest at one of the line intersections generates a dynamic visual interest. The intersecting points are ideal spots to position point of interest. Aligning point of interests along any of the lines also improves a composition. Consider placing the horizontal menu bar at the top horizontal line.

Figure 4.1 The Rule of Thirds The Golden Rule is an alternative method used to create an interesting composition, see Figure 4.2. The main point of interest of your web page should reside at either intersection of the three lines. Avoid placing the main point of interest at the center of he screen.

Page 49: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

4:

Web

Pa

ge

Des

ign

43

Figure 4.2 The Golden Mean

Page 50: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

44

Chapter 5: Forms Forms provide the mechanism for users to interact with a web site. In most cases Forms are used to collect information which is stored in the site database. Shopping carts are a typical example. No data is processed by Forms; instead information is send to the server where the data is processed by a scripting language, such as PHP. Elements available when designing forms include:

form The body that establishes the form

fieldset Grouping of elements, controls, and labels

legend The caption assigned to the fieldset

input Creates a variety of controls:

o Single-line text entry o Password entry o Hidden controls o Checkboxes o Radio Buttons o Submit Button o Reset Button o File upload o Custom buttons, including images

label Information attached to an input

textarea Multiline text area

button Generic input button

select Multiple choice menu or list

option an option within a select control

Page 51: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

45

Forms The form element is used to designate an area within a division section as a form. The form can contain any web content, text, images, tables, etc. Its main function is to be a container for control elements and data collection. <form action=”index.php” method=”get”> … </form> <form action=”/bin/myScript.javascript” method=”get”> … </form>

The action defines either the page or a script that processes the data. The method defines the mechanism to transmit the data to the server. The choices are get and post. The get mechanism is used for short messages and small forms, and the post mechanism should be used for large messages and large forms. Post provides for better site security; however it does not encrypt messages.

Fieldset Fieldset provides for grouping controls and text areas. It must be used within a form tag and can be nested. A physical layout and organization of data should be designed first before implementing forms and Fieldset.

Legend Legends are optional and can be used with Fieldset. Considerations should be given when using legends to ensure that screen readers for the hearing impaired do not repeat the legends in an awkward redundant way. A screen reader reads the legend, label, and field as a tuple. <legend> Personal Information </legend>

Page 52: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

46

Exercise 5.1 Exercise 5.1 creates a web page layout using a form and two fieldset. Each fieldset includes a legend.

Cascading Style Sheet /* Body */

body {

font-family: Georgia, Verdana, Arial, Sans-Serif;

background-color: #202020;

position: absolute;

width: 1000px;

left: 50%;

margin-left: -500px;

}

/* Title Section */

.titleSection {

position: absolute;

top: 0px;

padding-top: 5px;

width: 780px;

height: 85px;

background-color: #606090;

}

.title {

text-align: center;

padding-left: 20px;

font-family: Georgia;

font-size: 24px;

font-weight: bold;

}

/* Logo Section */

.logoSection {

position: absolute;

top: 0px;

padding-top: 5px;

left: 780px;

width: 220px;

height: 85px;

background: #606090 url(Images/logo.jpg) no-repeat top;

}

/* Menu Section */

div.navigationSection {

position:absolute;

top: 90px;

width: 1000px;

height: 45px;

background-color:#7070aa;

}

Page 53: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

47

div.navigationStyle > span.self {

font-weight: bold;

}

/* Content Section */

.contentSection {

position:absolute;

top: 135px;

width: 960px;

height: 550px;

background-color: #404040;

padding-left: 20px;

padding-right: 20px;

}

form {

width: 680px;

height : 255px;

background-color:#707070;

}

/* Personal Information */

fieldset.piStyle {

position:absolute;

top:60px;

left:25px;

width: 300px;

height: 220px;

border-style:inset;

float: left;

}

/* Contact Information */

fieldset.ciStyle {

position:absolute;

top:60px;

left:360px;

width: 300px;

height: 220px;

border-style:inset;

}

legend

{

font-family: Georgia;

font-size: 14px;

}

p {

text-align: left;

padding-left: 5px;

font-family: Georgia;

font-size: 12px;

}

Page 54: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

4

8

p.drop:first-letter {

font-size: 200%;

font-weight: bold;

float: left;

margin-right: 3px;

margin-bottom: -6px;

}

/* Mouse Behavior */

a {

font-weight: normal;

}

a:link {

color: black;

}

a:visited {

color: black;

text-decoration: none;

}

a:hover {

color: white;

background-color: #000000;

text-decoration: none;

}

a:active {

color: white;

background-color: #7070aa;

}

XHTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 2.0 Transitional//EN"

"http://www.w3.org/TR/xhtml2/DTD/xhtml2-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Exercise 3.1</title>

<meta name="description" content="Example of a Web Page using a

form." />

<meta name="keywords" content="Computer Science, Web Programming" />

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

<link href="style.css" rel="stylesheet" type="text/css" />

</head>

<body>

<!-- Title Section -->

<div class="titleSection">

<p class="title"> Welcome to my Website </p>

</div>

<!-- Logo Section -->

<div class="logoSection" >

</div>

Page 55: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

49

<!-- Navigation Section -->

<div class="navigationSection">

<br />

&nbsp &nbsp

<span class="self"><strong> Navigation</strong></span>: |

<a href="index.html" > Home</a>|

<a href="aboutUS.html" > About US</a>|

</div>

<!-- Content Section -->

<div class="contentSection">

<br /><br /><br />

<form method="get" action="index.html">

<fieldset class="piStyle">

<legend> Personal Information </legend>

</fieldset>

<fieldset class="ciStyle">

<legend> Contact Information </legend>

</fieldset>

</form>

</div>

</body>

</html>

Figure 5.1 Forms with nested fieldset

Page 56: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

5

0

Input Text <form method="get" action="index.html"> <fieldset class="piStyle"> <legend> Personal Information </legend> <p><label for="FirstName"> First Name: </label> <input type="text" name="FirstName" size="20" maxlength="50" value="Enter ... " /> </p> <p><label for="LastName"> Last Name: </label> <input type="text" name="LastName" size="20" maxlength="50" value="Enter ... " /> </p> </fieldset> <fieldset class="ciStyle"> <legend> Contact Information </legend> <p><label for="EmailAddress"> Email Address: </label> <input type="text" name="EmailAddress:" size="20" maxlength="50" value=" " /> </p> </fieldset> <br/> <input type="submit" value="Submit" style="position:absolute; float:left; top:270px; "/> <input type="reset" value="Reset" style="position:absolute; left:90px; top:270px; "/> </form>

Page 57: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

51

Figure 5.2 Text Fields

Password <p><label for="Password"> Password ..... </label> <input type="password" name="Password" size="20" maxlength="50" value="" /> </p>

Textarea <p><label for="Comments"> Comments: </label> <br /> <textarea rows="7" cols="30" id="desc">Please enter your comments here. </textarea> </p>

Page 58: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

52

Figure 5.3 Text Area

Exercise 5.2 Exercise 5.2 uses the same Cascading Style Sheet as Exercise 5.1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Exercise 5.2</title> <meta name="description" content="Example of a simple Web Page using a style sheet." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <!-- Title Section --> <div class="titleSection"> <p class="title"> Welcome to Web Programming </p> </div>

Page 59: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

53

<!-- Logo Section --> <div class="logoSection" > </div> <!-- Navigation Section --> <div class="navigationSection"> <br /> <span> Navigation</span>: | <a href="index.html" > Home</a>| <a href="aboutUS.html" > About US</a>| </div> <!-- Content Section --> <div class="contentSection"> <br/> <br/> <br/> <form method="get" action="index.html"> <fieldset class="piStyle"> <legend> Student </legend> <p><label for="FirstName"> First Name .. </label> <input type="text" name="FirstName" size="20" maxlength="50" value="" /> </p> <p><label for="LastName"> Last Name ... </label> <input type="text" name="LastName" size="20" maxlength="50" value="" /> </p><br/> <p><select id="statename" name="statename" size="1"> <option value="MC"> Main Campus </option> <option value="MGC"> Melborne Graduate Center </option> <option value="OGC"> Orlando Graduate Center </option> <option value="KGC"> Cape Kennedy Graduate Center </option> </select></p> </fieldset> <fieldset class="ciStyle"> <legend> MS Program </legend> <p> <input id="Radio1" type="radio" name="MS" checked="checked"/> <label for="Radio1"> CS </label> <input id="Radio2" type="radio" name="MS" /> <label for="Radio2"> CIS </label> <input id="Radio3" type="radio" name="MS" /> <label for="Radio3"> CSE </label> </p><br/> <p><strong>Courses</strong></p> <p> <input id="Checkbox1" type="checkbox" name="Courses" /> <label for ="Checkbox1"> Analysis of Algorithms </label><br /> <input id="Checkbox2" type="checkbox" name="Courses" /> <label for ="Checkbox2"> Web Programming </label><br /> <input id="Checkbox3" type="checkbox" name="Courses" /> <label for ="Checkbox3"> Compiler Theory and Design </label><br /> <input id="Checkbox4" type="checkbox" name="Courses" /> <label for ="Checkbox4"> CapStone Project </label> </p>

Page 60: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

5:

Fo

rms

54

</fieldset> <br/> <input type="submit" value="Submit" style="position:absolute; float:left; top:270px; "/> <input type="reset" value="Reset" style="position:absolute; left:90px; top:270px; "/> </form> </div> </body> </html>

Figure 5.4 Control Elements

Page 61: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

55

Chapter 6: Server Side Programming The Personal Home Page (PHP) is a general-purpose scripting language originally created by Rasmus Lerdorf in 1995. The scripting language since has been renamed to PHP: Hypertext Preprocessor. PHP was designed for Web development to produce dynamic Web pages. The code is executed on the server side, producing HTML code which is then downloaded to the client side. Server side scripting languages include

PHP

Java Script

Perl

ASP

PHP Basics PHP code can be placed directly in line with HTML code. The PHP code must be converted to HTML code by the server prior to sending the page to the web browser. PHP code is placed between the tags <?php statements; ?>. <body> <div> <p> This is HTML code </p> <?php echo “This is PHP code”; ?> </div> </body> Typically PHP statements are terminated by a semicolon. In the code snippet above the echo command is used to display information on the page. When using the echo command a new line can be started using \n directive. The directive is equivalent to using the tag <br/> in HTML. The echo command can also be used to insert HTML tags. This is a powerful feature since it provides for a mechanism to include HTML code directly in a PHP file. <?php echo “<div> \n”; echo “ <p> \n”; echo “ My Text \n”; echo “ </p> \n”; echo “ </div> \n”; ?>

Page 62: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

56

Scalar and Compound Data Types PHP uses four scalar data types:

Boolean:

TRUE = 1, FALSE = 0

Integer: 32 it signed number

Float: up to 14 digit precision

String

PHP uses two compound types:

Array: Map of data

Object: Instance of a class

Comments, Variables, and Operators A comment in PHP is implemented using // Comment line /* Multiple comment lines */ A variable is defined using $ symbol. In the example below, $x, $y and $sum are user defined variables. Their data types are not pre-declared. $x = 4; $y = 10; $sum = $x + $y;

Page 63: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

57

In PHP there is no division operator for integer numbers. Instead the integer numbers are automatically converted to type float. In the example below the variable $sum would be of type float and assigned the value 0.5. $x = 1; $y = 2; $sum = $x / $y; It is possible to type cast a variable. $sum becomes an integer type and the assigned value is 0. PHP rounds all floats down to type integer. $x = 1; $y = 2; $sum = (int) ($x / $y); To properly round a floating point value use the function round (). In this example $sum is assigned the value 1. $x = 1; $y = 2; $sum = round ($x / $y);

Strings A string can be created using single or double quotes. The differences between single quotes and double quotes are that single quotes do not provide for escape characters, such as \n or \t. Double quoted strings allow for escape characters and nested strings. $buf = ‘Hello World’; $buffer = “The typical introduction of a PHP program $buf \n”; Numbers stored in a string can be assigned to variables and the conversion is automatic. However, properly storing a number to a string requires using the function strval (). $value = 10; $buffer = strval ($value); $number = (int) buffer; The string content can be assigned to other strings, and strings can also be concatenated. The . operator is used to concatenate two strings. The example below results in Agent Smith. $title = “Agent”; $Name = “Smith”; $buffer = $title . “ “ . $Name;

Page 64: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

58

The content of a string can be reversed using the function strrev (). In the example below, $buf contains the string Agent John Smith. $buffer contains the string htimS nhoJ tnegA. $Title = “Agent”; $FirstName = “John”; $LastName = “Smith”; $buf = $Title . “ “ . $Firstame . “ “ . $LastName; $buffer = strrev($buf); The content of a string can be changed to either upper or lower case letters by using functions strtolower () strtoupper (). $buf = “HTML tags require lower case letters”; $buffer = strtoupper ($buf); The $buffer contains the string HTML TAGS REQUIRE LOWER CASE LETTERS. $buffer = strtolowerr ($buf); The $buffer contains the string html tags require lower case letters.

Predefined Variables Predefined variables use the prefix $_ and are global variables that can be used anywhere in a PHP script. Examples of predefined variables of type Array are $_GET $_POST $_SERVER $_FILES $_ENV $_COOKIE These predefined variables are further discussed in the section Processing Forms.

Arrays A simple array of integers is created using the statement $fibNumbers = array(1, 1, 2, 3, 5, 8, 13, 21);

Page 65: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

59

Observe the array is an object and the brackets ( ) are used in the creation of the array instead of []. The array elements are accessed using an array index. Like most programming languages the index count starts with index 0 instead of 1. In the example below, $value is assigned the number 5. $value = $fibNumbers[4]; The smallest and largest value can be found in an array using functions min() and max(), respectively. $minNum = min($fibNumbers); $maxNum = max($fibNumbers ); An array can be sorted in ascending and descending order using functions assort () and arsort (), respectively. asort ($fibNumbers); arsort($fibNumbers); An array can also be used as a map. In the example below, the array is comprised of three elements, $FirstName, $Lastname, and $Title. This allows each element to be accessed by its name instead of an index. Notice the assignment operator => is used. $student = array(“FirstName” => “John”, “LastName” => “Smith”, “Title” => “Agent”); $buffer = $student[Title] . “ “ . $student[‘FirstName’] . “ “ . $student[‘LastName’]. The output produces Agent John Smith. In a previous example we used the function strrev () to reverse the content of a string. It is also possible to reverse the order of the words in a string with the help of using an array. The function explode () extracts the words separated by a space ‘ ‘ and copies them into the array $WordArray. Function array_reverse() reverses the array content. The array content can be captured back to a string by calling function implode (). $buf = “Agent John Smith”; $WordArray = explode (‘ ‘, $buf); $ WordArray = array_reverse($WordArray); $buffer = implode (‘ ‘, $WordArray); The content of $buffer is Smith John Agent. The code snippet above can be simplified as shown below; however, we do not recommend this practice since troubleshooting PHP code is very difficult. One loses all visibility when imbedding function calls as a parameter to a function call.

Page 66: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

6

0

$buf = “Agent John Smith”; $buffer = implode (‘ ‘, array_reverse (explode (‘ ‘, $buf));

If statements The conditional if statement has the same construct as the C++, C#, or Java programming languages. if (condition) { statement; } elseif (condition) { statement; } else { statement; } Example: $buffer = strval (5); $x = $buffer; if ($x >= 0) { print (“$x is a positive number); } Example: $buffer = strval (5); $x = $buffer; if ($x >= 0) { print (“$x is a positive number); } else { print (“$x is a negative number); } Example: $buffer = strval (5); $x = $buffer; if ($x >= 0) { print (“The absolute value is $x); }

Page 67: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

61

elseif ($x < 0) { $x = $x * -1; print (“The absolute value is $x); } else { print (“$x is not a number); }

Switch statement The switch statement is an alternative to the if, if-else conditional statement. Computer hardware is designed to favor the switch statement and typically is more efficient in performance. The individual case statements must include the break statement; otherwise the case statements are executed in order until a break is encountered. The default case is optional, but it is good coding practice to include the default case with a comment stating that it is intentionally left blank. switch ($choice) { case 1: statement; statement; break; case 2: statement; statement; break; default: statement; break; }

Page 68: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

62

While Loop The while statement allows PHP to execute a set of statements repeatedly. The syntax requires an expression, when evaluated true, enables the loop to be executed. while (expression) { statement; } An alternative construct for the while loop is shown below. while (condition): statement; statement; endwhile The combination of a while loop and a switch statement provides for the implementation of a deterministic finite automata (DFA), also known as a state machine. Example: Implementation of a state machine The state machine increments $num from 0 to 10, and then decrements $num back to 0. Once $num is equal zero $state is set to zero and the while loop exits. $num = 0; $state = 1; while ($state > 0) { switch ($state) { case 1: $num = $num + 1; if ($num > 9) { $state = 2; } break; case 2: $num = $num - 1; if ($num == 0) { $state = 0; } break; default: // Not used break; } }

Page 69: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

63

For Loop The for statement is an alternative to the while statement. The for statement should be used instead of a while statement when the number of executing the loop is known. Three components are required to enable the for loop successfully, a counter variable initialization, a conditional statement, and incrementing the counter variable. Typically the counter variable is used to determine how often the loop has executed, and the conditional statement determines when to exit the loop. for ($i = 0; $i > 0; $i++) { statement; statement; } An alternative construct for the for loop is available. for ($i = 0; $i > 0; $i++) : statement; statement; endfor;

Processing Forms PHP provides for a seamless integration with forms. In the example below the form is comprised of two input text fields, FirstName and LastName respectively. The user enters the name into the text fields and selects the Submit button. When the form is submitted $_POST[‘FirstName’] and $_POST[‘LastName’] contains the user input. <form method="post" action="index.php"> <p><label for="FirstName"> First Name: </label> <input type="text" name="FirstName" size="20" maxlength="50" value="Enter ... " /> </p> <p><label for="LastName"> Last Name: </label> <input type="text" name="LastName" size="20" maxlength="50" value="Enter ... " /> </p> <input type="submit" value="Submit" style="position:absolute; float:left; top:270px; "/> </form>

Page 70: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

64

Processing Text Input The PHP code snippet below displays the content entered by the user. <?php echo 'My name is ' . $_POST['FirstName'] . " " . $_POST['LastName']; ?>

If the PHP script is used to process multiple pages where the method may vary, then a simple conditional statement can resolve the issue. <?php if ($_SERVER['REQUEST_METHOD'] == 'GET') { echo 'My name is ' . $_GET['FirstName'] . " " . $_GET['LastName']; } else { echo 'My name is ' . $_POST['FirstName'] . " " . $_POST['LastName']; } ?>

It is possible that the user selected the Submit button without entering any text, or deliberately omitted information. The function strlen() can verify if data was entered. <?php if ($_SERVER['REQUEST_METHOD'] == 'GET') { if (!strlen($_GET['FirstName']) || !strlen($_GET['LastName'])) { echo ' Please enter the requested information!'; } else { echo 'My name is ' . $_GET['FirstName'] . " " . $_GET['LastName']; } } ?>

A strict form validation can be implemented by adding a check to determine if a variable is set. If a variable is assigned a value then it is set, otherwise it is unset. The function isset() returns true if the variable is set, otherwise it returns false. <?php if ($_SERVER['REQUEST_METHOD'] == 'GET') { if (! isset($_GET['FirstName']) || ! strlen($_GET['FirstName'])) { echo ' Please enter the First Name!'; } elseif (! isset($_GET['LastName']) || ! strlen($_GET['LastName'])) { echo ' Please enter the Last Name!'; }

Page 71: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

65

else { echo 'My name is ' . $_GET['FirstName'] . " " . $_GET['LastName']; } } ?>

User provided information can be displayed in the text fields by placing the PHP code directly into the HTML statements. <input type="text" name="FirstName" size="20" maxlength="50" value= <?php if (!strlen($_GET['FirstName'])){ print '"" /> '; } else { print ' "' . $_GET['FirstName'] .'" /> '; } ?>

Processing Control Elements Pulldown Menu <?php $choices = array ('0' => 'Select', '1' => 'Main Campus', '2' => 'Melborne Graduate Center', '3' => 'Orlando Graduate Center', '4' => 'Cape Kennedy Graduate Center'); print '<select id="statename" name="statename" size="1"> \n'; print '<option value="0"> Select ... </option> \n'; print '<option value="1"> Main Campus </option> \n'; print '<option value="2"> Melborne Graduate Center </option> \n'; print '<option value="3"> Orlando Graduate Center </option> \n'; print '<option value="4"> Cape Kennedy Graduate Center </option> \n'; print '</select>'; ?>

Verify that the user selected a choice. The user choice can be displayed or further processed. <?php if (0 != $_GET[statename]) { print '<p>'; echo $choices[$_GET[statename]]; print '</p>'; } ?>

Page 72: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

66

Radio Button <p> <input id="1" type="radio" name="MS" value="CS" checked="checked" /> CS <input id="2" type="radio" name="MS" value="CIS" /> CIS <input id="3" type="radio" name="MS" value="CSE" /> CSE </p><br/> <?php if (isset($_GET['Submit'])) { $mdata = $_GET['MS']; print $mdata; } ?>

In the code above the state of the radio buttons are not maintained. When the user selects the Submit button the state is set back to the CS choice. Form widgets require that the PHP script manages the state of the buttons. <?php $radiodata = "no"; if (isset($_GET['Submit'])) { $radiodata = $_GET['MS']; } if ($radiodata == "CS") { print '<input id="radio1" type="radio" name="MS" value="CS" checked="checked" /> CS'; } else { print '<input id="radio1" type="radio" name="MS" value="CS" /> CS'; } if ($radiodata == "CIS") { print '<input id="radio2" type="radio" name="MS" value="CIS" checked="checked" /> CIS'; } else { print '<input id="radio2" type="radio" name="MS" value="CIS" /> CIS'; } if ($radiodata == "CSE") { print '<input id="radio3" type="radio" name="MS" value="CSE" checked="checked" /> CSE'; } else { print '<input id="radio3" type="radio" name="MS" value="CSE" /> CSE'; } ?>

Page 73: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

67

Check Boxes

<p> <input id="1" type="checkbox" name="Course1" value="AA" /> <label for ="1"> Analysis of Algorithms </label><br/> <input id="2" type="checkbox" name="Course2" value="WP" /> <label for ="2"> Web Programming </label><br/> <input id="3" type="checkbox" name="Course3" value="CT"/> <label for ="3"> Compiler Theory and Design </label><br/> <input id="4" type="checkbox" name="Course4" value="CP" /> <label for ="4"> CapStone Project </label> </p>

if ($_GET['Course1'] == 'AA') { echo " "; print $_GET['Course1'] ; } if ($_GET['Course2'] == 'WP') { echo " "; print $_GET['Course2'] ; } if ($_GET['Course3'] == 'CT') { echo " "; print $_GET['Course3'] ; } if ($_GET['Course4'] == 'CP') { echo " "; print $_GET['Course4'] ; }

Page 74: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

6

8

PHP Templates and Controllers PHP code can be captured to file instead of using it in line, and then include it in the html file. Such a file is referred to a PHP template which can be referenced in numerous html and PHP files. It provides for a level of data abstraction and greatly simplifies the design. If every web page uses the same title and navigation section, then that code could be captured to a PHP file. An advantage is that a code change can be made in a single file instead of multiple pages. The code snippet below can be simplified by including a php template containing the same content. <body> <!-- Title Section --> <div class="titleSection"> <p class="title"> Welcome to Web Programming </p> </div> <!-- Logo Section --> <div class="logoSection" > </div> <!-- Navigation Section --> <div class="navigationSection"> <br /> <span> Navigation</span>: | <a href="index.html" > Home</a>| <a href="aboutUS.html" > About US</a>| </div> <!-- Content Section --> <div class="contentSection"> <br/>

The html code including the PHP template is given below. <body> <!-- Title Section --> <?php include('index.php'); ?> <!-- Content Section --> <div class="contentSection"> <br/>

Page 75: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

6:

Ser

ve

r S

ide

Pro

gra

mm

ing

69

File index.php <?php print ' <div class="titleSection"> <p class="title"> Welcome to Web Programming </p> </div> <!-- Logo Section --> <div class="logoSection" > </div> <!-- Navigation Section --> <div class="navigationSection"> <br /> <span> Navigation</span>: | <a href="index.html" > Home</a>| <a href="aboutUS.html" > About US</a>| </div> '; ?>

A PHP template can use numerous include statements and determine which content to display to the user. Selecting a PHP template versus another can be accomplished based on user input and conditional statements. Such a PHP script is called a Controller. if ($_GET['Course3'] == 'CT') { include(‘cis.php’); } else { include(‘cse.php’); }

Page 76: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

7:

MyS

QL

Da

tab

ase

70

Chapter 7: MySQL Database The PHP programming language provides for an extensive database support. It can interface with at least 20 different types of database, including MySQL, Oracle, Sybase, and Microsoft SQL Server. The relationship between the servers is shown in Figure 7.1. The Web Client requests a page from the Apache server. The PHP server cooperates with the Apache server to convert the PHP code into html. Any information required from the database is retrieved using the MySQL server and is further processed by the PHP server. The Apache server returns the page to the Web Client.

Web Client PHP Server MySQLApache

Server

Request

a Page

PHP

ScriptSQL

Statement

DataHTML Data

Figure 7.1 Relationship between servers.

Database Schema The following database schema is used for the given examples below. Database name: forum Table: member Attributes: FirstName LastName Email Comments ID (Primary Key) Table: forums Attributes: forum_id (Primary Key) forum_name

Page 77: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

7:

MyS

QL

Da

tab

ase

71

PHP Functions for Interfacing with MySQL Visit www.php.net for a detailed description of database related functions. mysqli_connect (host, username, password, database, port, socket) Establishes a connection to MySQL server and returns a reference required for additional calls to the database. mysqli_error ($link) Returns the text of the error message. mysqli_fetch_array (result, type) Fetches the next row of data from the result array. mysqli_query ($link, query, mode) Executes a SQL query amd returns the results. mysqli_select_db ($link, database) Selects the database for the specified $link returned by mysqli_connect(). mysqli_set_charset ($link, charset) Sets the default character set.

Database Connection The following PHP code connects to the MySQL database. The DEFINE statements provide for defining the four attributes required to connect to the database.

DEFINE ('DB_USER', 'root');

DEFINE ('DB_PASSWORD', 'P#@22d');

DEFINE ('DB_HOST', '127.0.0.1');

DEFINE ('DB_NAME', 'forum');

Page 78: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

7:

My

SQ

L D

ata

ba

se

72

If the connection to the database fails, a detailed error is returned. This error should be recorded to file and not displayed to the user. The variable $dbc becomes the reference to the database. When the connection is established the ISO-8859-1 character encoding is used by default. To use a more extensive character encoding we must set the encoding to utf8. <?php // Establishes the database connection DEFINE ('DB_USER', 'root'); DEFINE ('DB_PASSWORD', 'P#@22d'); DEFINE ('DB_HOST', '127.0.0.1'); DEFINE ('DB_NAME', 'Forum'); $dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (!$dbc) echo ‘Unable to connect to DB.’; else echo ‘Connected to DB.’; // set the character encoding mysqli_set_charset($dbc, ‘utf8’); ?>

Creating a dynamic pull-down menu

Suppose we need to dynamically create a pull down menu and the menu options are stored in the database table ‘forums’. Storing the menu options in the database allows the users to add new categories to the forum. The database can automatically sort the options in ascending order, which is a benefit of using a database.

Table forums

Page 79: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

7:

MyS

QL

Da

tab

ase

73

The SQL query to extract data from the forums table is Select forum_id, forum_name FROM forums ORDER BY forum_name ASC

In this example the first option of the pull-down menu is set to ‘Select …’ which is not stored in the database table. print '<select id="forid" name="forid" size="1"> \n';

print '<option value="0"> Select ... </option> ';

When the Submit button is pushed and the user did not select an option from the pull-down menu, then ‘Select …’ is forwarded by default to the PHP server. We use this item to protect the database from bots trying to paste their advertisement messages into our database. If the option ‘Select …’ is send to the PHP server the information is discarded. The SQL statement is stored to variable $query. $query = "SELECT forum_id, forum_name

FROM forums

ORDER BY forum_name ASC";

Page 80: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

7:

MyS

QL

Da

tab

ase

74

The array $result is comprised of 6 rows of data which is returned from the SQL query. Each row must be extracted separately from the array using the function $menu_row = mysqli_fetch_array(). $menu_row [0] contains the forum_id and $menu_row [1] contains the forum_name. Both items are required to create the option item for the pull-down menu. At the end of the transaction the data must be removed from the arrays, otherwise the new data will be appended into the array. Function mysqli_free_result($result) and function unset($menu_row) accomplishes this task. Example Code: <body>

<!-- Row 1 Column 1 -->

<div class="style11">

<img class="logo" src="images/logo.jpg" alt="Logo" />

</div>

<!-- Row 1 Column 2 -->

<div class="style12">

<img src="images/logo1.jpg"

alt="Logo"

width="215px" height="115px" />

</div>

<!-- Row 2 Column 1 -->

<div class="style21">

</div>

<?php include('DBConnection.php');?>

<!-- Row 2 Column 2 -->

<div class="style22a">

<p class="space20" style= "font-size: 18px;">

<br/> Forums ... <br/><br/>

</p>

<?php include('PullDownMenu.php');?>

</div>

<!-- Row 2 Column 3 -->

<div class="style23a">

<br />

<form action="Forums.html.php" method="post">

<fieldset>

<legend><span>Credentials: </span></legend>

<div><label for = "firstname">First Name: </label>

<input type= "text" name= "firstname" id="firstname" />

</div>

<div><label for = "lastname">Last Name: </label>

Page 81: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

7:

MyS

QL

Da

tab

ase

75

<input type= "text" name= "lastname" id="lastname" />

</div>

<div><label for = "email">Your email: </label>

<input type= "text" name= "email" id="email" />

</div>

<div><label for = "id">User ID: </label>

<input type= "text" name= "id" id="id" />

</div>

</fieldset>

<br />

<fieldset>

<legend><span>Your Comments: </span></legend>

<div>

<textarea name= "comment" id="comment" cols="42" rows = "10">

</textarea>

</div>

</fieldset>

<br />

<div> <input type= "submit" name= "submit" id="submit" value="Submit"

/>

</div>

</form>

</div>

</body>

<?php //mysqli_connect.php

// Script establishes the database connection

DEFINE ('DB_USER', 'root');

DEFINE ('DB_PASSWORD', 'Phd12345');

DEFINE ('DB_HOST', '127.0.0.1');

DEFINE ('DB_NAME', 'forum');

$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

// set the character encoding

mysqli_set_charset($dbc, ‘utf8’);

?>

<?php

print '<p class="space0"> <strong> Choose a Forum: </strong> </p>

<form action="index.php" method="get"> ';

// Display the Pull down menu

print '<select id="forid" name="forid" size="1"> \n';

print '<option value="0"> Select ... </option> ';

// Get the options from the database

$query = "SELECT forum_id, forum_name FROM forums ORDER BY forum_name

ASC";

$result = mysqli_query($dbc, $query);

Page 82: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

7:

MyS

QL

Da

tab

ase

76

if (mysqli_num_rows($result) > 0) {

while ($menu_row = mysqli_fetch_array($result, MYSQLI_NUM))

{

echo "<option value=\"$menu_row[0]\">$menu_row[1]</option> ";

}

}

print '</select>';

print '</form>';

mysqli_free_result($result);

unset($menu_row);

?>

Inserting Data into the Database

To insert data into the database we create a DBInsert.php file and include it in the html code. The action in the form tag passes the script and the method to the server, once the submit button is pressed. The variable $_POST is an array that contains the information from the form. <form action="Forums.html.php" method="post">

DBInsert.php <?php $query = "INSERT INTO member SET FirstName = '" . $_POST['firstname'] . "', LastName = '" . $_POST['lastname'] . "', Email = '" . $_POST['email'] . "', Comments = '" . $_POST['comment'] . "', ID = 3"; $result = mysqli_query($dbc, $query); ?> <div class="style23a">

<br />

<?php include('DBInsert.php');?>

<form action="Forums.html.php" method="post">

<fieldset>

<legend><span>Credentials: </span></legend>

<div><label for = "firstname">First Name: </label>

<input type= "text" name= "firstname" id="firstname" />

</div>

<div><label for = "lastname">Last Name: </label>

<input type= "text" name= "lastname" id="lastname" />

</div>

Page 83: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

7:

MyS

QL

Da

tab

ase

77

<div><label for = "email">Your email: </label>

<input type= "text" name= "email" id="email" />

</div>

<div><label for = "id">User ID: </label>

<input type= "text" name= "id" id="id" />

</div>

</fieldset>

<br/>

<fieldset>

<legend><span>Your Comments: </span></legend>

<div><textarea name= "comment" id="comment" cols="42" rows = "10">

</textarea>

</div>

</fieldset>

<br />

<div> <input type= "submit" name= "submit" value="Submit" /> </di

</form>

</div>

Page 84: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

78

Chapter 8: Client Side Programming Client side programming is used to

Improve navigation

Provide special effects

Validate user data

Provide dynamic content

JavaScript is the client side scripting language of choice and it is executed on the client side instead of the server side like PHP.

JavaScript The JavaScript programming language was originally called LiveScript, however the name was changed prior to its release. The JavaScript programming language and the Java programming language are not related, and other than the name they share no similarity. JavaScript is a loosely typed programming language that is interpreted instead of compiled. The JavaScript language resembles C++ and Java, with programming constructs such as the if statement, while loop, and standard operators. Object Oriented inheritance is different from the C++ or Java programming language.

JavaScript Basics JavaScript code can be placed in-line with HTML code. Use the <script> </script> tags to include the code. It is processed by the web browser instead of the server. <body> <div> <p> This is HTML code </p> <script language=”JavaScript”> document.write(“<p>This text is inserted using JavaScript</p>”); </script> </div> </body> JavaScript statements are typically terminated with a semicolon; however it is not a requirement when each statement is listed on a separate line.

Page 85: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

79

The document.write command is used to display data on the page. The script tag supports referencing a JavaScript file. The JavaScript file uses the .js extension. The closing </script> tag is required when using the src attribute. <script src=”./JavaScripts/myAlgorithm.js”></script> JavaScript functions can be included in the <head> section. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>SocietyComputationalScience - Home </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="description" content="algorithm design" /> <meta name="keywords" content="algorithm, software design, Imager" /> <link href="style.css" type="text/css" rel="stylesheet" /> <script language="JavaScript" type="text/JavaScript"> <!-- function myFunction() { JavaScript statements; } function mySecondFunction() { JavaScript statements; }

//--> </script> </head>

Variables, Operators, and Comments JavaScript supports the comment style of the C++ programming language. // This is a single comment line /* This is a multiple line comment section Additional comments */

Page 86: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

8

0

An identifier is used to name variables. Variables can start with a $ symbol like PHP variables, but an underscore or a letter can also be used. Variables can be declared locally using var $myVariable. The variable can be initialized at the same time of instantiation. When a variable is used without a prior declaration then the variable is treated as a global variable. var $sumOfSquares = 0; var $x = 10; var $y = 10; var $hypothesis = 0; $sumOfSquares = ($x * $x) + ($y * $y); $hypothesis = Math.sqrt( $sumOfSquares ); A number can be stored to a string by concatenating the number with an empty string. var $sum = 100; var $buf = $sum + “”; The String() function can also be used to explicitly convert a number to a string. var $buf = String ($sum ); The toString function is another mechanism to convert a number to a string. var $buf = $sum.toString(); A number stored to a string can be converted directly to a number by subtracting 0. var $sum = $buf – 0; A more explicit method is to call the function Number(). var $sum = Number($buf);

Page 87: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

81

Arrays A simple array of integers can be created with the statement var ar = [1, 1, 2, 3, 5, 8, 13, 21]; The array elements are accessed using an array index. Like most programming languages the index count starts with index 0. In this example $value is assigned the number 5. var $value = ar[4]; Creating an empty array using the new operator. var ar = new Array(); Creating an array of size 10. var ar = new Array( 10 ); The function Array.join() copies the content of an array to a string. The array values are separated by a comma. var ar = [1, 1, 2, 3, 5, 8, 13, 21]; var buf = ar.join(); document.write(buf); The output displays 1,1,2,3,5,8,13,21

If statements if (expression) { statement; } elseif (expression) { statement; } else { statement; } var $x = 5; var $ans = 0; if ($x >= 0) { $ans = $x; } else {

Page 88: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

8

2

$ans = $x * -1; }

Switch construct switch (expression) { case 1: statement; statement; break; case 2: statement; statement; break; default: statement; break; }

While Loop while (expression) { statement; } The following example calculates n! using a while statement. var $n = 10; var $cnt = 1; var $ans = 1; while ($cnt <= $n) { $ans = $ans * $cnt; $cnt++; } document.write($ans);

For Loop for ( initialize; test; increment) { statement; statement;

Page 89: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

8

3

} The following example displays the first 10 integers using a for loop. var i = 0; var n = 10; for (i = 0; i < n; i++) { document.write( i ); }

Functions function functionName ( arg1, arg2, …, argn) { statements; } The following function calcuates the factorial. function factorial(n) { if ( n <= 1) { return 1; } return n * factorial( n -1); }

Date/ Time The function displayDate() displays the date and time. The date and time is obtained by creating a date object var d = new Date();.

The method document.getElementById("dd").innerHTML = d finally displays the content of the object to the html element “dd”. <p id=”dd’> Display date and time here </p> function displayDate() {

Page 90: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

8

4

var d = new Date(); document.getElementById("dd").innerHTML = d; }

The Date and Time Example below shows the HTML/ JavaScript implementation. The function displayDate() resides in the <head><script> section ready to be called. The setInterval function provides for the animation of date and time. This timer calls displayDate() every 1000 milliseconds, which results in a text update every second. Call clearInterval(dd) to stop the timer. <p id="dd"> <script language="javascript" type="text/javascript"> setInterval("displayDate()", 1000); </script> </p>

Date and Time Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Exercise 8.1</title> <meta name="description" content="A Web Page using JavaScript." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <link href="style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> function displayDateTime(buf) { // Displays the date and time var d = new Date(); document.getElementById(buf).innerHTML = d; } function displayDate(buf1) { // Displays the date var d = new Date(); var month_names = new Array(); month_names[0] = "Jan"; month_names[1] = "Feb"; month_names[2] = "Mar"; month_names[3] = "Apr"; month_names[4] = "May"; month_names[5] = "Jun"; month_names[6] = "Jul"; month_names[7] = "Aug"; month_names[8] = "Sep";

Page 91: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

85

month_names[9] = "Oct"; month_names[10] = "Nov"; month_names[11] = "Dec"; var day_names = new Array(); day_names[0] = "Sun"; day_names[1] = "Mon"; day_names[2] = "Tue"; day_names[3] = "Wed"; day_names[4] = "Thu"; day_names[5] = "Fri"; day_names[6] = "Sat"; document.getElementById(buf1).innerHTML = day_names[d.getDay()] + " " + month_names[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear(); } function displayTime(buf2) { // Displays time in the format 00:00:00 var d = new Date(); if (d.getHours() < 10) { hr = "0" + d.getHours() + ":"; } else { hr = d.getHours() + ":"; } if (d.getMinutes() < 10) { min = "0" + d.getMinutes() + ":"; } else { min = d.getMinutes() + ":"; } if (d.getSeconds() < 10) { sec = "0" + d.getSeconds() + ":"; } else { sec = d.getSeconds(); } var timeBuf = "" + hr + min + sec; document.getElementById(buf2).innerHTML = timeBuf; } function elapsedTime(t1, t2) { // Calculates elapsed time in milliseconds return (t2.getTime() - t1.getTime()); } </script> </head> <body> <!-- Title Section --> <div class="titleSection">

Page 92: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

8

6

<p class="title"> Welcome to Web Programming </p> </div> <!-- Logo Section --> <div class="logoSection" > </div> <!-- Navigation Section --> <div class="navigationSection"> <br /> <span> Navigation</span>: | <a href="index.html" > Home</a>| <a href="aboutUS.html" > About Us</a>| </div> <!-- Content Section --> <div class="contentSection"> <p id="dt"> <script language="javascript" type="text/javascript"> setInterval("displayDateTime('dt')", 1000); </script> </p> <p id="d"> <script language="javascript" type="text/javascript"> displayDate('d'); </script> </p> <p id="t"> <script language="javascript" type="text/javascript"> setInterval("displayTime('t')", 1000); </script> </p> </div> </body> </html>

Page 93: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

87

Processing Images <p> <img src="" id="pp" alt="image" /> <script language="javascript" type="text/javascript"> toggle = 0; function loadImage() { switch (toggle) { case 0: var pic = "Images/Ball_1.JPG"; toggle = 1; break; case 1: var pic = "Images/Ball_2.JPG"; toggle = 2; break; case 2: var pic = "Images/Ball_3.JPG"; toggle = 3; break; case 3:

Page 94: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

8

8

var pic = "Images/Ball_4.JPG"; toggle = 4; break; case 4: var pic = "Images/Ball_5.JPG"; toggle = 5; break; case 5: var pic = "Images/Ball_6.JPG"; toggle = 0; break; } document.getElementById("pp").src = pic; } setInterval("loadImage()", 500); </script> </p>

Dialog Windows Three types of dialogs can be displayed to the user. The user is required to perform an action by either entering a message or selecting the OK or Cancel button. The dialog methods block until the user responds.

alert()

confirm()

prompt()

Alert Dialog The alert dialog can be invoked by clicking a button and invoking the associated event handler. <p> <button onclick="alert('Garfield says hello!');"> Click here </button> </p>

Page 95: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

8

9

Confirm Dialog In the example below, the event handler for the button “Confirm Animation” calls the JavaScript function confirmTimerFunction(). The confirmTimerFunction() creates the confirm dialog. When the user selects the Ok button a periodic timer is activated. myTimer is a reference that can be used to turn the timer off, using clearInterval(myTimer). Turning the timer off halts executing loadImage() which provided for the animation. <p> <button onclick="confirmTimerFunction();"> Confirm Animation </button> </p>

function confirmTimerFunction() { var buf = 'Do you want the animation to continue? \n\n' + 'Select Ok to continue or Cancel to stop'; if (!confirm(buf)) { clearInterval(myTimer); return; } toggle = 0; myTimer = setInterval("loadImage()", 300); return; }

Page 96: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

9

0

Prompt Dialog

Using a Prompt Dialog is shown in the example below. The event handler for the button User

Prompt calls the javascript function userPromptFunction(). The userPromptFunction()

creates the Prompt Dialog prompting the user for his/her name. Once the user has entered

the name and selected Ok, the dialog box closes. When the user selects the Get Message

button the Alert Dialog displays the message “name, Garfield says Hello! “

<p> <button onclick="alertFunction();"> Get Message </button> </p> <p> <button onclick="userPromptFunction();"> User Prompt </button> </p>

Page 97: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

91

function userPromptFunction() { var buf = 'Enter the name:'; message = ""; message = prompt(buf, message); return; }

function alertFunction() { var buf = message + ", Garfield says Hello!"; alert(buf); return; }

Page 98: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

92

Processing Navigation Bar Images <script language="JavaScript" type="text/JavaScript"> <!-- function MM_swapImgRestore() { //v3.0 var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc; } function MM_preloadImages() { //v3.0 var d = document; if (d.images) { if (!d.MM_p) d.MM_p = new Array(); var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++) if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; } } } function MM_findObj(n, d) { //v4.01 var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) { d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p); } if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n]; for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document); if (!x && d.getElementById) x = d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3) if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src;

Page 99: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

8:

Cli

en

t S

ide

Pro

gra

mm

ing

93

x.src = a[i + 2]; } } //--> </script>

Page 100: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

9:

Do

cum

en

t O

bje

ct M

od

el

an

d D

yn

am

ic H

TM

L

94

Chapter 9: Document Object Model and Dynamic HTML Dynamic HTML (DHTML) refers to the technique of making Web pages dynamic by client-side scripting to manipulate the document content and presentation. Standardization efforts at W3C made it possible to write standard-based DHTML that works on most compliant browsers. DHTM involves three aspects:

1. JavaScript – for cross-browser scripting 2. Cascading Style Sheets (CSS) – for style and presentation control 3. Document Object Model (DOM) – for a uniform programming interface to access

and manipulate the Web page as a document

W3C established the Document Object Model (DOM) as a standards application programming interface (API). Scripts access the API to manipulate the HTML document. The DOM objects are organized into a tree structure. Each Web page has a document node at the root of the tree.

Figure 9.1 Client-Side object hierarchy

Page 101: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

9:

Do

cum

en

t O

bje

ct M

od

el

an

d D

yn

am

ic H

TM

L

95

Exercise 9.1 Exercise 9.1 shows that we can modify the document using the DOM API and JavaScript. In the example the list items of an unordered list are reordered in ascending order. The list elements of the unordered list are copied to a new array NewListArray. The membership function Sort() is called on the NewListArray. A comparator function is used to perform the sort. After the array is sorted the elements are reinserted into the original list. The existing duplicate members are automatically removed from the list as they are re-inserted into the list. Figure 9.1 and Figure 9.2 shows the UL before and after the sort, respectively. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Exercise 9.1</title> <meta name="description" content="A Web Page using JavaScript." /> <meta name="keywords" content="Computer Science, Web Programming" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <link href="style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="JavaScripts/navigation.js"></script> </head> <body> <!-- Title Section --> <div class="titleSection"> <p class="title"> Welcome to Web Programming </p> </div> <!-- Logo Section --> <div class="logoSection" > </div> <!-- Navigation Section --> <div class="navigationSection"> <br /> &nbsp &nbsp &nbsp <a href="index.html" > Home</a>| <a href="aboutUs.html" > About Us</a>| </div> <!-- Date Section --> <div class="dateSection"> <p id="D1" style= "text-align:right"> <script language="javascript" type="text/javascript"> displayDate('D1'); </script> &nbsp &nbsp &nbsp </p>

Page 102: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

9:

Do

cum

en

t O

bje

ct M

od

el

an

d D

yn

am

ic H

TM

L

96

</div> <!-- Content Section --> <div class="contentSection"> <script language="javascript" type="text/javascript"> function sortMyList(e) { if (typeof e == "string") { e = document.getElementById(e); } var NewListArray = []; for (var x = e.firstChild; x != null; x = x.nextSibling) { if (x.nodeType == 1) { NewListArray.push(x); } } NewListArray.sort( function (n, m) { var s = n.firstChild.data; var t = m.firstChild.data; if (s < t) { return -1; } else if (s > t) { return 1; } else { return 0; } } ); For (var i = 0; i < NewListArray.length; i++) { e.appendChild(NewListArray[i]); } } </script> <ul id="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> </ul> <button onclick ="sortMyList('list')">Sort List</button> </div> </body> </html>

Page 103: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Ch

ap

ter

9:

Do

cum

en

t O

bje

ct M

od

el

an

d D

yn

am

ic H

TM

L

97

Figure 9.1

Figure 9.2

Page 104: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

Re

fere

nce

s

9

8

References An Introduction to Web Design + Programming Paul S. Wang, Sanda S. Katila Thomson, Course Technology ISBN-13: 978-0-534-39528-5 ISBN-10: 0-534-39528-7 Web Design in a Nutshell Jennifer Niederst Robbins O’Reily ISBN-13: 978-0-596-00987-8 ISBN-10: 0-596-00987-9 Just Enough WEB Programming with XHTML, PHP, and MySQL Guy W. Lecky Thomson, Course Technology eISBN-10: 1-59863-684-7 PHP Cookbook Adam Trachtenberg, David Sklar O’Reily Build your own Database Driven Web Site using PHP & MySQL Kevin Yank Sitepoint ISBN: 978-0-9805768-1-8 JaavaScript, The Definitive Guide David Flanangan O’Reily

Page 105: Introduction to Web Programming - mycigroup.com · Chapter 1: Introduction to Web Programming ... Link Building ... Formulate Visual Presentation Concepts

In

de

x

99

Index

A Apache Server, 2

C Controller, 14

E

F

P