Vous êtes sur la page 1sur 71

PROGRAMMING THE WEB (10CSL78) LAB MANUAL

For

viI SEMESTER

MAHARAJA INSTITUTE OF TECHNOLOGY, MYSORE Department Of Computer Science & Engineering


MIT-Mysore

PROGRAMMING THE WEB

[2013]

INDEX
Sl No TITLE
Develop and demonstrate a XHTML file that includes JavaScript script for the following problems: a) Input: a number n obtained using prompt Output: The first n Fibonacci numbers. b) Input: A number n obtained using prompt Output: Numbers 1 to n and their squares, using alert. Develop and demonstrate, using JavaScript, a XHTML file that collects the USN(the valid format is: A digit from 1 to 4 followed by two upper case characters followed by three digits; no embedded Spaces allowed) of the user. Event handler must be included for the form element that collects this information to validate the input. Messages in the alert window must be produced when errors are detected. Modify the above program to get the current semester also(number between 1 and 8). Develop and demonstrate using JavaScript script, a XHTML document that contains three short paragraphs Of text, stacked on top of each other, with only enough of each showing so that the mouse cursor can be placed over some part of them. When the cursor is placed over the exposed part of any paragraph, it should rise to the top to become completely visible. Modify the above document so that when a paragraph is moved from the top stacking position, it returns to its original position rather than to the bottom.

1.

2.

3.

a) Design an XML document to store information about a student in an engineering college


4. affiliated to VTU. The information must include USN, Name, College, branch, Year of Joining, and email id. Make up sample data for 3 students. Create a css style sheet and use it to display the document. b) Create an XSLT stylesheet for one student element of the above document and use it to create a display of that element.

a) Write a Perl program to display various server information like Server Name, Server
5. Software, Protocol, CGI Revision, etc. b) Write a Perl program to accept a UNIX command from an HTML form and to display the output of the command executed.

a) Write a Perl program to accept the user name and to display a greeting message randomly
6. chosen from a list of 4 greeting messages. b) Write a Perl program to keep track of the number of Visitors visiting the Web page and to display this count of visitors, with proper headings. Write a Perl program to display a digital clock which displays the current time of the server. Write a Perl program to insert name and age information entered by the user into a table created using MySQL and to display the current contents of this table.

7.

8.

DEPT OF CSE

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

9.

Write a PHP program to store current date-time in a COOKIE and display the Last visited on date-time on the web page upon reopening of the same page. Write a PHP program to store page views count in SESSION, to increment the count on each refresh, and to show the count on web page. Create a XHTML form with Name, Address Line 1, Address Line 2, and E-mail text fields. On submitting, store the values in MySQL table. Retrieve and display the data based on Name. Build a Rails application to accept book information viz. Accession number, title, authors, edition and publisher from a web page and store the information in a database and to search for a book with the title specified by the user and to display the search results with proper headings

10.

11.

12.

DEPT OF CSE

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

INTRODUCTION What is HTML? HTML, stands for HyperText Markup Language, is the predominant markup language for web pages. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. It allows images and objects to be embedded and can be used to create interactive forms. The definition of HTML is.

HyperText is the method by which you move around on the web by clicking on special text called hyperlinks which bring you to the next page. Hyper just means it is not linear i.e. you can go to any place on the Internet whenever you want by clicking on links there is no set order to do things in.

Markup is what HTML tags do to the text inside them. They mark it as a certain type of text (italicised text, for example).

HTML is a Language, as it has code-words and syntax like any other language.

How does it work? HTML consists of a series of short codes typed into a text-file. The text is then saved as a html file, and viewed through a browser, like Internet Explorer or Netscape Navigator. This browser reads the file and translates the text into a visible form. Writing your own HTML entails using tags correctly to create your vision. You can use anything from a rudimentary text-editor to a powerful graphical editor to create HTML pages. What is HTTP? HyperText Transfer Protocol is the protocol for transferring hypertext requests and information between servers and browsers. HTTP defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands. For example, when you enter a URL in your browser, this actually sends an HTTP command to the Web server directing it to fetch and transmit the requested Web page. HTTP is called a stateless protocol because each command is executed independently, without any knowledge of the commands that came before it. This is the main reason that it is difficult to implement Web sites that react intelligently to user input.
DEPT OF CSE 3 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

URL (Uniform Resource Locator) Uniform Resource Locator is the global address of documents and other resources on the World Wide Web. The first part of the address is called a protocol identifier and it indicates what protocol to use, the second part is called a resource name and it specifies the IP address or the domain name where the resource is located. The protocol identifier and the resource name are separated by a colon and two forward slashes. For example: http://www.simplygraphix.com/ and a typical page on this site would be: http://www.simplygraphix.com/portfolio/4.html The above URL consists of:

Protocol: http Host computer name: www Domain name: simplygraphix Domain type: com Path: /portfolio File name 4.html

What is XHTML? XHTML eXtensable HyperText Markup Language has a more strict syntax rules in comparison of HTML. XHTML gives you a more consistent, well structured format so that your web pages can be easily parsed and processed by present and future web browsers. It also makes your website easier to maintain, edit, convert and format in the long run. XHTML is an official standard of the World Wide Web Consortium (W3C), your website will be compatible to more browsers and will be rendered more accurately. XHTML combines strength of HTML and XML and XHTML pages can be rendered by all XML enabled devices.

DEPT OF CSE

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

XHTML defines a quality standard for your webpages, if you follows that then your web pages will be counted quality web pages and W3C certifies those pages with their quality stamp. There are several main changes in XHTML from HTML: All tags must be in lower case All documents must have a document type. All tags must be closed All attributes must be added properly Attributes cannot be shortened All tags must be properly nested

What is XML? XML stands for EXtensible Markup Language. XML is a markup language much like HTML designed to carry data, not to display data. XML tags are not predefined. You must define your own tags. XML is designed to be self-descriptive XML is a W3C Recommendation. Why XML? XML was created so that richly structured documents could be used over the web. HTML and SGML, are not practical for this purpose.HTML, comes bound with a set of semantics and does not provide arbitrary structure. SGML provides arbitrary structure, but is too difficult to implement just for a web browser. Full SGML systems solve large, complex problems that justify their expense. Viewing structured documents sent over the web rarely carries such justification. While XML is being designed to deliver structured content over the web, some of the very features it lacks to make this practical, make SGML a more satisfactory solution for the creation and long-time storage of complex documents. The XML Prolog The prolog is an optional component of the XML document. If included, the prolog must appear before the root element. A prolog consists of two parts: the XML Declaration and the Document Type Declaration (DTD). Depending on your needs, you can choose to include both, either, or neither of these items in your XML document. XML Declaration :
DEPT OF CSE 5 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Syntax <?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?> The XML declaration may contain the following attributes: version Identifies the version of the XML markup language used in the data. This attribute is not optional. encoding Identifies the character set used to encode the data. "ISO-8859-1" is "Latin-1" the Western European and English language character set. The default is compressed Unicode: UTF-8. standalone Tells whether or not this document references an external entity or an external data type specification. If there are no external references, then "yes" is appropriate. XML Document Type Declaration (DTD) : The Document Type Declaration is a file that contains the necessary rules that the XML code in this file must follow. You may think of the DTD as the grammar that the XML document must abide by to be a valid XML file. Referencing an External DTD: There are two type declarations that may be used to reference an external DTD: PUBLIC and SYSTEM. When creating an XML document under the rules of a publicly distributed DTD, use PUBLIC. Otherwise, use the SYSTEM type declaration. The example below shows a prolog that would be used for an HTML document that is using an XML prolog. The DTD is publicly available. XML Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Let's take a look at each piece of this external DTD reference. !DOCTYPE - Tell the XML processor that this piece of code defines the Document Type Definition
6 MIT, MYSORE

DEPT OF CSE

PROGRAMMING THE WEB

[2013]

html - Specifies the root element of the XML document. Here our example is an HTML file, which has <html> as the root element. PUBLIC - Specifies that this is a publicly available DTD. "-//W3C//D..." - The definition of the public document. "http://www.w3.org/..." - The physical location of the DTD.

XML Namespace Syntax : The XML namespace is a special type of reserved XML attribute that you place in an XML tag. The reserved attribute is actually more like a prefix that you attach to any namespace you create. This attribute prefix is "xmlns:", which stands for XML Namespace. The colon is used to separate the prefix from your namespace that you are creating. xmlns must have a unique value that no other namespace in the document has. What is commonly used is the URI (Uniform Resource Identifier) or the more commonly used URL. Namespace attribute takes the form: xmlns : prefix="namespaceURI"

xmlns is required; it identifies this as an XML namespace declaration. :prefix (note the leading colon) is optional. If you include it, all element names in the document from the indicated namespace must be prefixed with these characters, followed by a colon.

namespaceURI is required. It uniquely identifies a namespace in this document and in others.

Example : <html xmlns="http://www.w3.org/1999/xhtml"> Applications of XML Although there are countless numbers of applications that use XML, here are a few examples of the current platforms and applications that are making use of this technology: Cell Phones - XML data is sent to some cell phones. The data is then formatted by the specification of the cell phone software designer to display text or images, and even to play sounds!

DEPT OF CSE

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

File Converters - Many applications have been written to convert existing documents into the XML standard. An example is a PDF to XML converter. VoiceXML - Converts XML documents into an audio format so that you can listen to an XML document.

Cascading Style Sheets (CSS): They are a way to control the look and feel of your HTML documents in an organized and efficient manner. With plain HTML you define the colors and sizes of text and tables throughout your pages. If you want to change a certain element you will therefore have to work your way through the document and change it. With CSS you define the colors and sizes in "styles". Then as you write your documents you refer to the styles. Therefore: if you change a certain style it will change the look of your entire site. Another big advantage is that CSS offers much more detailed attributes than plain HTML for defining the look and feel of your site. CSS can be written so the user will only need to download it once - in the external style sheet document. When surfing the rest of your site the CSS will be cached on the users computer, and therefore speed up the loading time.

CSS Syntax: Style rules are comprised of two things, the selector and the declaration.

selector - The HTML tag that will be affected by the rule declaration - The specific style calls that will affect the selector
The complete syntax for a style rule is: selector {property : value;}

Example :

b {color: red;}

You can also group together components that you would like to have the same style. For example, if you wanted all the H1, H2 and bold text red, you could write: b {color: red;} h1 {color: red;} h2 {color: red;}
DEPT OF CSE 8 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

You put them all on the same line: b, h1, h2 {color: red;} You can also group together rules (separated by a semi-colon (;) ). For example, to make all h3 text blue and Arial font, you would write: h3 { font-family: Arial; color: blue; } Placement of CSS Elements: Style sheets can be place in three places in a document, in the <head>, in an external file, or within an individual tag. Style calls placed within an individual tag will only affect that tag, while other style calls affect the entire page or any page that loads the style sheet. Styles within the Tags CSS is built in to every HTML tag. If you want to add a style inside an HTML element all you have to specify the desired CSS properties with the style HTML attribute. Example : <h4 style="color: #0000ff;">another blue headline</h4>

Styles within the Head of the Document To create a style sheet within the header of your HTML document, you enclose it in <style> tags. It is a good idea to define the mime type of the styles you are creating (usually text/css), and then to put the style rules within comment tags so that older browsers do not display them as text on the page. For example: <head> <style type="text/css"> <!-h4 { color: blue; } -->

DEPT OF CSE

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

</style> </head> Finally, you can create a separate document with all of your style information in it and either link or import it into your document. If you have a large site and would like to maintain consistency across it, then external style sheets are the way to go. They provide you with a simple way to dictate how all instances of various tags will be displayed. Linking a Style Sheet The benefit to linking a style sheet into your document is that it is supported by both the major 4.0 browsers. You call a linked style sheet like this: <link rel="stylesheet" type="text/css" href="stylesheet.css"> Importing a Style Sheet Importing style sheets are only currently supported by Internet Explorer 4.0. They allow you to keep all your style information in the same place, within the <style> element, while also loading external files as style commands. For example: <style> @import URL (http://yoursite.com/stylesheet.css); H4 { color: #0000ff; } </style> Advantages of CSS : Easy Maintenance File Size : Probably the mostly useful feature of CSS is that all of the style and layout is removed from the html, so the html page size is very much smaller. The CSS file is downloaded just once by the visitor's browser and re-used for different pages on a web site. This reduces the bandwidth requirements for your server and also ensures a faster download for your visitors. Accessibility : Separating style from content makes life very easy for visitors who prefer to view only the content of a web page, or to modify the content. These could be blind or partially sighted people who might use a screen reader to interpret a page.

DEPT OF CSE

10

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Consistency : Layout and position of navigation can be completely consistent across a site. This was previously possible only using frames. Improved Search Engine Results: With use of CSS, you can keep your HTML code much cleaner. As a result search engine bots do not have to separate the real content from the junk code. You are also free to put any content anywhere in your document with CSS. This will aid the search engine crawlers to identify the important content first.

Flexibility in defining style: The name cascading indicates that we can use more than one style and the priority is given to local styles first. We can override the global style declared and locally assign the style to the tag.

Java Script: JavaScript is a scripting language that will allow you to add real programming to your webpages. It can enhance the dynamics and interactive features of your page by allowing you to perform calculations, check forms, write interactive games, add special effects, customize graphics selections, and create security passwords.

What can a JavaScript do?

JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages

JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page

JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element

JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element

JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing

JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser

DEPT OF CSE

11

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer

Where to place JavaScript : There are three general areas that JavaScript can be placed for use in a webpage. 1. Inside the head tag 2. Within the body tag 3. In an external file The location choice of head or body is very simple. If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head. If you want the script to run when the page loads then you place the script within the body tag. CGI (Common Gateway Interface) CGI is one method by which a web server can obtain data from (or send data to) databases, documents, and other programs, and presents that data to viewers via the web. More simply, a CGI is a program intended to be run on the web. A CGI program can be written in any programming language, but Perl is one of the most popular language being used.

PHP PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly. Syntax : A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document. On servers with shorthand support enabled you can start a scripting block with <? and end with ?>.

DEPT OF CSE

12

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

XHTML and Java script


In programs numbering 1 to 3 Java script is embedded within the body of the XHTML file Execution steps for programs 1 to 3 Step 1: Start -> Text Editor(pluma) -> Type the Program. Step 2: Save the Program with .html extension. Step 3: File -> Open the file with extension .html to see the output. Error debugging of javascript can be done using the error console of firefox browser by selecting Tools->Error console->Errors as shown in screenshot below

DEPT OF CSE

13

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

1 Develop and demonstrate a XHTML file that includes JavaScript script for the following problems: a) Input: A number n obtained using prompt Output: The first n Fibonacci numbers Note:Javascript script is embedded within the body of the XHTML file. The script contains the code to accept the value of n using a prompt. The first n Fibonacci numbers are then calculated using a for loop. Each number is displayed in the browser window, in order.

1a.html <?xml version ="1.0" encoding ="utf-8" ?> <!DOCTYPE html PUBLIC "-//w3c/DTD XHTML 1.1 EN"> <html> <head> <title>Fibonacci Series</title> </head><body> <script type=text/javascript> var fib1=0,fib2=1,fib=0; var num = prompt("Enter a number : \n", ""); if(num!=null && num>0) { document.write("<h1>First \t" + num + "\t Fibonacci Numbers are <br> </h1>"); if(num==1) document.write("<h1>" + fib1 + "</h1>"); else document.write("<h1>" + fib1 + " <br> " + fib2 + "</h1>"); for(i=3;i<=num;i++) { fib=fib1 + fib2; document.write("<h1>" + fib + "</h1>"); fib1=fib2; fib2=fib; } } else
DEPT OF CSE 14 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

alert("No proper input"); </script> </body></html> Input snap of 1a.html

Output Snap of 1a.html

DEPT OF CSE

15

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

1 b) Input: A number n obtained using prompt Output: A table of numbers from 1 to n and their squares using alert
Note: Javascript script is embedded within body of XHTML document, which accepts the value of n using

a prompt.In a for loop that runs from 1 to n, for each value, the number and its square are displayed using the alert message box.

1b.html <?xml version ="1.0" encoding ="utf-8" ?> <!DOCTYPE html PUBLIC "-//w3c/DTD XHTML 1.1 EN"> <html> <head> <title>Number and its squares</title> </head> <body> <script type=text/javascript> var num = prompt("Enter a number : \n", " "); if(num>0 && num !=null) { msgstr="Number and its squares are \n"; for(i=1;i<=num;i++) { msgstr = msgstr + i + "-" + i * i + "\n"; } alert(msgstr) } else alert("no input supplied"); </script> </body> </html>

Inputsnap snap of 1b.html

DEPT OF CSE

16

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Output Snap of 1b.html

DEPT OF CSE

17

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

2 a) Develop and demonstrate, using Javascript script, a XHTML document that collects the USN ( the valid format is: A digit from 1 to 4 followed by two upper-case characters followed by two digits followed by two upper-case characters followed by three digits; no embedded spaces allowed) of the user. Event handler must be included for the form element that collects this information to validate the input. Messages in the alert windows must be produced when errors are detected.

Note: The USN is accepted through a text box. When the submit button is clicked, the javascript function for checking validity of the USN is called. The entered USN is compared with the valid pattern defined by a regular expression. If there is a mistake, an alert message is displayed saying so, and the USN typed in the textbox is focused so that the user can enter the right USN.

2a.html <?xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"> <html> <script type=text/javascript> function formValidator() { var usn=document.getElementById("req1");

if(validUsn(usn)) { alert(usn.value); return true; } return false; } function validUsn(elem) { exp=/^[1-4][A-Z][A-Z][0-9][0-9][A-Z][A-Z][0-9][0-9][0-9]$/ if(elem.value.length==0) { alert("US Number is empty"); return false;
DEPT OF CSE 18 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

} else if(!elem.value.match(exp)) { alert("US Number should be in DAADDAADDD format"); return false; } alert("US Number IS CORRECT"); return true; } </script><body bgcolor=green> <form onsubmit=formValidator()> Enter your USN. in DAADDAADDD format : <input type=text id=req1 /> <input type=submit value="Check Field" /> </form></body></html>

Input and OutputSnap 2a.html

DEPT OF CSE

19

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

2.b) Modify the above program to get the current semester also (restricted to be number from 1 to 8) Note: In addition to the above, the semester is also accepted. If the value entered is greater than 8, or lesser than 1, an alert message is displayed saying the same. The value is then focused so that the user can enter the correct value.

2b.html <?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"> <html> <head> <script type=text/javascript> function formValidator() { var usn = document.getElementById("req1"); var sem = document.getElementById("req2"); if(validUsn(usn)) { if(validSem(sem)) return true; } return false; }

function validSem(elem2) { var exp2=/^[1-8]$/ if(elem2.value.length == 0) { alert("Semester Number is empty"); elem2.focus(); return false; } else if(!elem2.value.match(exp2)) { alert("Invalid Semester Number"); elem2.focus(); return false;
DEPT OF CSE 20 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

} alert("Semester Number IS CORRECT"); return true; }

function validUsn(elem1) { var exp1=/^[1-4][A-Z][A-Z][0-9][0-9][A-Z][A-Z][0-9][0-9][0-9]$/ if(elem1.value.length == 0) { alert("US Number is empty"); elem1.focus(); return false; } else if(!elem1.value.match(exp1)) { alert("US Number should be in DAADDAADDD format"); elem1.focus(); return false; } alert("US Number IS CORRECT"); return true; } </script> </head> <body bgcolor=green> <form onsubmit="return formValidator();" > Enter your USN. in DUUDDUUDDD format : <input type=text id=req1 /> <br/> Enter your Sem. in D[1-8] format : <input type=text id=req2 /> <br/> <input type=submit value="Check Field" /> </form> </body> </html>

DEPT OF CSE

21

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

OutputSnap 2b.html

OutputSnap 2b.html

DEPT OF CSE

22

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

3 a) Develop and demonstrate, using Java Script ,a XHTML document that contains three short paragraphs of text ,stacked on top of each other , with only enough of each showing so that the mouse cursor can be placed over some part of them .when the cursor is placed over the exposed part of any paragraph , it should rise to the top to become completely visible Note: The javascript script embedded in the XHTML file consists of a mover function. The id of the paragraph that is currently on top is stor ed in a variable toplayer. The id of the paragraph that has been selected is passed as an argument to the function. Using the getElementById method, the z-Index(depth factor) of the paragraph that was previously on top is set to 0 and the z-Index of the newly selected paragraph is set to 10. The toplayer variable is updated to hold the id of the paragraph that is currently on top.Within the XHTML body, the paragraphs are defined. The element attributes are defined using an document level style sheet. The mover function is called whenever the mouse cursor is placed over any of the paragraphs(onmouseover tag attribute is used).

3a.html <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"> <html> <head> <title>The Stacking order</title> <style type=text/css> .layer1style { border:solid thick pink; padding:1em; width:500px; background-color:green; position:absolute; top:100px; left:400px; z-index:1;

} .layer2style
DEPT OF CSE 23 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

{ border:solid thick black; padding:1em; width:500px; background-color:blue; position:absolute; top:120px; left:420px; z-index:2;

} .layer3style { border:solid thick green; padding:1em; width:500px; background-color:white; position:absolute; top:140px; left:440px; z-index:3;

} </style> <script type=text/javascript> var topLayer="layer3"; function mover(toTop) { var oldTop=document.getElementById(topLayer).style; var newTop=document.getElementById(toTop).style; oldTop.zIndex=0; newTop.zIndex=25; topLayer=document.getElementById(toTop).id; }
DEPT OF CSE 24 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

</script></head> <body style=background-color:yellow> <h2 style=text-align:center;color:red> Program includes XHTML document to show the stacking of paragraphs </h2> <p class=layer1style id=layer1 onmouseover=mover("layer1")> HTML, stands for HyperText Markup Language, is the predominant markup language for web pages.It provides a means to create structured documents . </p> <p class=layer2style id=layer2 onmouseover=mover("layer2")> XHTML eXtensable HyperText Markup Language has a more strict syntax rules in comparison of HTML. XHTML gives a more consistent, well structured format. </p> <p class=layer3style id=layer3 onmouseover=mover("layer3")> Internet has evolved over the last 20 years and it has made the livings of millions highly dependent on it and hence it's necessary for all to learn the way of programming the WEB. </p></body></html> OutputSnap

3a.html

DEPT OF CSE

25

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

3 (b) Modify the above document so that when a paragraph is moved from the top stacking position ,it returns to its original position rather than to the bottom

3b.html <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"> <html> <head> <title>The Stacking order</title> <style type=text/css> .layer1style { border:solid thick pink; padding:1em; width:500px; background-color:green; position:absolute; top:100px; left:400px; z-index:1; } .layer2style { border:solid thick black; padding:1em; width:500px; background-color:blue; position:absolute; top:120px; left:420px; z-index:2; } .layer3style {
DEPT OF CSE 26 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

border:solid thick green ; padding:1em; width:500px; background-color:white; position:absolute; top:140px; left:440px; z-index:3; } </style> <script type=text/javascript> var topLayer="layer3"; var origpos;

function mover(toTop,pos) { var newTop=document.getElementById(toTop).style; newTop.zIndex=10; topLayer=document.getElementById(toTop).id; origPos=pos; } function moveBack() { document.getElementById(topLayer).style.zIndex=origPos; } </script> </head> <body> <body style=background-color:cyan> <h1 style=text-align:center;color:blue> Program includes XHTML document to show that the stacking of paragraphs when moved from the top position,it returns to it's Original position. </h1> <p class=layer1style id=layer1 onmouseover=mover("layer1",1) onmouseout=moveBack() >
DEPT OF CSE 27 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

HTML, stands for HyperText Markup Language, is the predominant markup language for web pages.It provides a means to create structured documents . </p>

<p class=layer2style id=layer2 onmouseover=mover("layer2",2) onmouseout=moveBack()> XHTML eXtensable HyperText Markup Language has a more strict syntax rules in comparison of HTML.XHTML gives a more consistent, well structured format. </p>

<p class=layer3style id=layer3 onmouseover=mover("layer3",3) onmouseout=moveBack() > Internet has evolved over the last 20 years and it has made the livings of millions highly dependent on it and hence it's necessary for all to learn the way of programming the web. </p></body></html>

OutputSnap 3b.html

DEPT OF CSE

28

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

XML AND XSLT


Programs 4a based on XML and 4b are based on XML and XSLT Execution steps for programs to 4a Step 1: Start -> Text Editor(pluma) -> Type the Program. Step 2: Save the Program with .xml extension. Step 3: Start -> Text Editor(pluma) -> Type the style sheet attributes and save it with extension .css Step 4: File -> double click on the file with extension .xml to see the output. Error debugging of XML can be done using the error messages displayed on the browser by the XML parser.

Execution steps for programs to 4b Step 1: Start -> Text Editor(pluma) -> Type the Program. Step 2: Save the Program with .xml extension. Step 3: Start -> Text Editor(pluma) -> Type the xsl program and save it with extension .xsl Step 4: File -> double click on the file with extension .xml to see the output. Error debugging of XML can be done using the error messages displayed on the browser by the XML parser as shown in the screen shot below.

DEPT OF CSE

29

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

4 a) Design an XML document to store information about a student in an engineering college affiliated to VTU. The information must include USN, Name, Name of the College, Brach, Year of Joining, and e-mail id. Make up sample data for 3 students. Create a CSS style sheet and use it to display the document.

Note: Create an XML document with the details of the students. User defined tags can be used for each detail such as <usn>, <name>, etc. Values can be given for the attributes of each of these tags in an external style sheet.

4a.xml <?xml-stylesheet type="text/css" href="stu.css" ?> <student_information> <label> <h2> student 1 </h2> usn:<usn>4mh09cs011</usn> name:<name>Rajesh</name> college:<college>MIT</college> branch:<branch>cse</branch> year of joining:<year>2009</year> email-id:<email>Rajesh@gmail.com</email> </label> <label> <h2> student 2 </h2><br/> usn:<usn>4mh09cs012 </usn> name:<name> Deepak</name> college:<college>MIT</college> branch:<branch>cse</branch> year of joining:<year>2009 </year> email-id:<email>deepak@gmail.com</email> </label> <label> <h2> student 3 </h2><br/> usn:<usn>4mh09cs013 </usn> name:<name>Girish</name>
DEPT OF CSE 30 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

college:<college>MIT</college> branch:<branch>cse</branch> year of joining:<year>2009</year> email-id:<email>girish@gmail.com</email> </label> </student_information>

stu.css label{display:block;} usn {color:red; font-size:12pt; margin-right:15px;} name {color:green; font-size:12pt; margin-right:15px;} college {color:blue; font-size:12pt; margin-right:15px;} branch {color:black; font-size:12pt; margin-right:15px;} year {color:yellow; font-size:12pt; margin-right:15px;} email {color:blue; font-size:12pt; margin-right:15px;} h3 {color:red; font-size:18pt;} h2 {color:black; font-size:18pt;}

OutputSnap 4a.html

DEPT OF CSE

31

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

4 b) Create an XSLT style sheet for one student element of the above document and use it to create a display of that element. Note: An XML file is created for a student record as in 6a,each value of a tag is selected based on template matching using XSL and inline style is applied to each value.

4b.xml <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "6b.xsl" ?> <VTU> <USN> 4mh09cs011 </USN> <name> rajesh </name> <college> MIT </college> <branch> CSE </branch> <YOJ> 2009 </YOJ> <email> Rajesh@gmail.com</email> </VTU>

4b.xsl <?xml version = "1.0"?> <xsl:stylesheet version = "1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "VTU"> <html><head><title> Style sheet for 6b.xml </title> </head><body> <h2> VTU Student Description </h2> USN:<span style = "font-style:normal; color: red;"><xsl:value-of select = "USN" /> </span><br/> Name:<span style = "font-style:italic; color: blue;"><xsl:value-of select = "name"/> </span><br/> College:<span style = "font-style:normal; color:green;"><xsl:value-of select = "college"/> </span><br/> Branch:<span style="font-style:italic; color:black;"><xsl:value-of select="branch"/> </span><br/> Year of Join:<span style = "font-style:normal; color:pink;"><xsl:value-of select = "YOJ" />
DEPT OF CSE 32 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

</span><br/> E-Mail:<span style = "font-style:italic;color:blue;"><xsl:value-of select = "email" /> </span><br/> </body></html> </xsl:template> </xsl:stylesheet>

OutputSnap 4b.html

DEPT OF CSE

33

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

HTML on client side and PERL on server side


Programs numbering from 5 to 8 are developed using HTML on client side and PERL on server side (HTML tags are embedded in server side PERL programs also) Common Execution steps for programs 5 to 8 Step 1: Start -> Text Editor(pluma) -> Type the client side HTML Program. Step 2: Save the Program with .html extension in any path. Step 3: Start -> Text Editor(pluma) -> Type the server side perl program and save it with extension .pl in the path /var/www/cgi-bin Step 4: Give Read write and execute permission for the perl program Step 5:double click on html file which opens in the browser using which you can send a request to the server .The perl program on the server side will execute and the response will be send back to the client which will be displayed on the browser.

Error debugging:we can check for errors in the perl program by using perl interpreter . Step 1: open the terminal and type cd /var/www/cgi-bin Step 2: Permissions for the perl program can be given in the terminal by command chmod 777 filename.pl Step 3:perl interpreter can be invoked by giving command perl filename.pl in terminal. Step 4:Error messages are displayed with line numbers. if there are no errors html tags will be displayed.(manual checking of program for possible errors in HTMLembedded in perl is suggested)

DEPT OF CSE

34

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Terminal snapshot

DEPT OF CSE

35

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

5 a) Write a Perl program to display various Server Information like Server Name, Server Software, Server protocol, CGI Revision etc.

5a.html <html> <head><title> server information </title> </head><body bgcolor=pink> <h1 align=center> server information </h1><br><hr> <form action=http://localhost/cgi-bin/5a.pl method=GET> <h1 align=center> <input type=submit value="click here to view the server information"> </h1></form></body></html>

5a.pl #!/usr/bin/perl print "content-type:text/html \n\n"; print" SERVER NAME: $ENV{'SERVER_NAME'} </br> SERVER PORT: $ENV{'SERVER_PORT'} </br> SERVER SOFTWARE: $ENV{'SERVER_SOFTWARE'}</br> SERVER PROTOCOL: $ENV{'SERVER_PROTOCOL'}</br> CGI REVISION: $ENV{'GATEWAY_INTERFACE'}</br>"

Snap5a.html

Snap5a.pl

DEPT OF CSE

36

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

5 b) Write a Perl program to accept UNIX command from a HTML form and to display the output of the command executed. 5b.html <html><head><title>Command Execution</title> </head><body bgcolor=lightyellow> <br><h1 align=center><font color=red>COMMAND EXECUTION</font></h1> <br><hr><marquee>COMMAND EXECUTION</marquee> <hr><br><h2 align=center> ENTER THE COMMAND TO EXECUTE <form action=http://localhost/cgi-bin/5b.pl method=POST> <input type=text size=40 name=command> <p><input type=submit value=Submit> <input type=reset value= Reset> </h2></form></body></html>

5b.pl #!/usr/bin/perl print "content-type:text/html \n\n"; use CGI; $q=new CGI; $com=$q->param('command'); if($com)
DEPT OF CSE 37 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

{ system($com); } else { print "Command not entered"; }

Snap 5b.html

Snap 5b.pl

DEPT OF CSE

38

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

6. a) Write a Perl program to accept the User Name and display a greeting message randomly chosen from a list of 4 greeting messages.

6a.html <html><head> <title>Greeting message </title> </head><body bgcolor=pink> <h1 align=center> Greeting message </h1> <br><hr> <form action=http://localhost/cgi-bin/6a.pl method=POST> <h1 align=center> <p>Enter the name: <input type=text size=40 name=var1><br> <input type=submit value=submit> <input type=reset value=reset> </p></h1></form></body></html>

6a.pl #!/usr/bin/perl use CGI; print "content-type:text/html \n\n"; $q=new CGI; $cmd=$q->param('var1'); @coins=("Welcome to MIT","Welcome to web lab","Have a nice day","All the best"); $range = 4; $random_number = int(rand($range)); if(!$cmd) { print "Error,name not entered"; } else { print "<br><b>hello $cmd , $coins[$random_number]</b>"; }
DEPT OF CSE 39 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Snap6a.html

Snap6a.pl

DEPT OF CSE

40

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

b) Write a Perl program to keep track of the number of visitors visiting the web page and to

display this count of visitors, with proper headings. Note: along with common execution steps specified above create a text file with name count.txt in the path /var/www give permissions to it and initialize it to 0. 6b.html <html><head> <title> Visitor Information </title> </head><body bgcolor=pink> <h1 align=center> Visitor Information </h1> <br><hr> <form action=http://localhost/cgi-bin/6b.pl method=GET> <h1 align=center> <input type=submit value="click here to view the Visitor Information"> </h1></form></body></html>

6b.pl #!/usr/bin/perl $file="/var/www/count.txt"; print"content-type:text/html \n\n"; if(!open(fh,"<$file")) { print "Error: cannot read from '$file': $!" ; exit; } $n=<fh>; close(fh); if(!open(fh,">$file")) { print "Error: cannot write to '$file': $!"; exit; } print fh ++$n; close(fh); print"<h3>Total visitors to this page=$n"; print"<form action=http://localhost/cgi-bin/8b.pl>"; print"<input type=submit value=Revisit>";
DEPT OF CSE 41 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Snap 6b.html

Snap 6b.pl

DEPT OF CSE

42

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

7. Write a Perl program to display a digital clock which displays the current time of the server Note: This program does not need client side HTML to send a request to the server. The server program 7.pl can be directly requested in the browser by entering URL http://localhost/cgi-bin/7.pl in the address bar of the browser

7.pl #!/usr/bin/perl $rf=1; print "refresh:",$rf,"\n"; print "content-type:text/html \n\n"; $d=`/bin/date | cut -d ' ' -f 4`; print "SERVER TIME IS $d";

Snap of 7.pl

DEPT OF CSE

43

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

8. Write a Perl program to insert name and age information entered by the user into a table created using MySQL and to display the current contents of this table. Note: along with the common execution steps specified above database and tables should be created using Mysql as shown in the snapshot below Open the terminal and login to the mysql server using command mysql u root p The terminal will prompt you for entering a password. root is the password that should be entered .here root is the user. (username and password are same)

DEPT OF CSE

44

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Introduction about the methods used DBI (Database Independent Interface) is a Perl Module that provides methods to manipulate SQL Databases. With DBI, one can connect to a database within a Perl script and issue all kinds of queries like select, insert and delete. The use DBI pragma makes use of this Perl module. The use strict pragma makes the user compulsorily declare a variable before it is used. This pragma overrides the Perls built in feature that states that variables can be used directly without declaration. Therefore with strict, if you use a variable before it is declared, an error is generated. Once this pragma is used, the my keyword is used to declare variables. The variable $dbh serves as a Database Handler. The connect( ) function is used to connect to the server. The first parameter indicates that the DBI Perl module is being used to the MySQL database and the database name. The second parameter indicates the user root and the third parameter indicates that the password(mitcs)

The variable $sth is the Statement handler that prepares the SQL statement (Query) to be executed. The execute ( ) function is used to execute the SQL query. The fetchrow ( ) function is used to loop through each record of the table and the records are stored in the variables. After this, ensure that you finish the statement handler and disconnect from the server by making use of the finish ( ) and disconnect ( ) functions respectively.

DEPT OF CSE

45

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

8.html <html><head> <title>PERSON INFORMATION</title> </head><body bgcolor=lightyellow> <br><h1 align=center>TABLE CONTENT</h1> <br><hr><marquee>ADD TO TABLE</marquee> <hr><br> ENTER THE FOLLOWING INFORMATION TO ADD A RECORD <form action=http://localhost/cgi-bin/8.pl METHOD=POST> <font color=blue> <p>First name : <input type=text size=40 name=fname></p> <p>Last name: <input type=text size=40 name=lname></p> <p>Age : <input type=text size=4 name=age></p>

<br><input type=submit value=Submit> <input type=reset value=Reset> </font></form></body></html>

8.pl #!/usr/bin/perl print "content-type:text/html \n\n"; use CGI; use CGI::Carp(fatalsToBrowser); use strict; use DBI; my $q=new CGI; my $first=$q->param('fname'); my $last=$q->param('lname'); my $age=$q->param('age'); if($first eq ` ` || $last eq ` ` || $age eq ` `) { print "All THE FIELDS HAVE NOT BEEN ENTERED"; exit; } else
DEPT OF CSE 46 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

{ my $dbh=DBI->connect('DBI:mysql:web','root','root') or die "can't connect:".DBI->errstr();

my $sth=$dbh->prepare('insert into age_inf(firstname,lastname,age) values(?,?,?)'); $sth->execute($first,$last,$age) or die "cant execute sql:" .$sth->errstr();

$sth=$dbh->prepare("select * from age_info"); $sth->execute();

print "YOUR RECORD IS ADDED TO THE TABLE</br></br>"; print "<table><tr><th>Firstname</th><th>Lastname</th> <th>Age</th></tr>";

while(($first,$last,$age)=$sth->fetchrow()) { print "<tr><td>$first</td> <td>$last</td> <td>$age</td> </tr>"; } print "</table>"; $sth->finish(); $dbh->disconnect(); }

DEPT OF CSE

47

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Snap 8.html

Snap 8.pl

DEPT OF CSE

48

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

HTML on client side and PHP on server side


Programs numbering from 9 to 11 are developed using HTML on client side and PHP on server side (HTML tags are embedded in server side PHP programs also) Common Execution steps for programs 9 to 11 Step 1: Start -> Text Editor(pluma) -> Type the client side HTML Program. Step 2: Save the Program with .html extension in any path. Step 3: Start -> Text Editor(pluma) -> Type the server side php program and save it with extension .php in the path /var/www/ Step 4: Give Read write and execute permission for the php program Step 5:double click on html file which opens in the browser using which you can send a request to the server .The php program on the server side will execute and the response will be send back to the client which will be displayed on the browser.

Error debugging:we can check for errors in the php program by using php interpreter . Step 1: open the terminal and type cd /var/www Step 2: Permissions for the php program can be given filename.php Step 3:php interpreter can be invoked by giving command php filename.php in terminal. Step 4:Error messages are displayed with line numbers. if there are no errors html tags will be displayed.(manual checking of program for possible errors in HTMLembedded in php is suggested) in the terminal by command chmod 777

DEPT OF CSE

49

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Terminal snapshot

DEPT OF CSE

50

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

9. Write a PHP program to store current date-time in a COOKIE and display the Last visited on date-time on the web page upon reopening of the same page. Note: This program does not need client side HTML to send a request to the server. Start from step 3 in execution steps. The server program 9.php can be directly requested in the browser by entering URL http://localhost/9.php in the address bar of the browser

9.php <?php if(isset($_COOKIE['LastVisit'])) { $visit = $_COOKIE['LastVisit']; echo "Your last visit was - ".$visit; } else echo "you've got some stale cookies!"; $inTwoMonths = 60 * 60 * 24 * 60 + time(); setcookie('LastVisit',date("g:i - m/d/y"), $inTwoMonths); ?>

DEPT OF CSE

51

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Snap 9.php Run1

Run2

DEPT OF CSE

52

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

10. Write a PHP program to store page views count in SESSION, to increment the count on each refresh, and to show the count on web page. Note: This program does not need client side HTML to send a request to the server. Start from step 3 in execution steps. The server program 10.php can be directly requested in the browser by entering URL http://localhost/10.php in the address bar of the browser

10.php <h3><marquee>SESSION INFORMATION DISPLAY</marquee></h3> <? session_register("count"); echo "The counter is now $_SESSION[count]"; $_SESSION["count"]=$_SESSION["count"]+1; echo "</br>Reload this page to increment"; ?>

Snap 10.pl

DEPT OF CSE

53

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

11. Create a XHTML form with Name, Address Line 1, Address Line 2, and E-mail text fields. On submitting, store the values in MySQL table. Retrieve and display the data based on Name. Note: along with the common execution steps specified above database and tables should be created using Mysql as shown in the snapshot below.Open the terminal and login to the mysql server using command mysql u root p The terminal will prompt you for entering a password. mitcs is the password that should be entered .here root is the user

DEPT OF CSE

54

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

11a.html <?xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"> <html> <head> <title>PERSON INFORMATION</title></head> <body bgcolor=pink> <h1 align=center> <font color=blue>PERSON INFORMATION</font></h1> <form action=http://localhost/11a.php method=POST> <h5 align=center><br> Name:<input type=text size=20 name=nm><br><br> ADDRESS1:<input type=text size=20 name=add1><br><br> ADDRESS2:<input type=text size=20 name=add2><br><br>
DEPT OF CSE 55 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

EMAIL:<input type=text size=20 name=em><br><br> <input type=submit value=insert> <input type=reset value=reset> </h5></form></body></html>

11a.php <? $a1=$_REQUEST['nm']; $b2=$_REQUEST['add1']; $c3=$_REQUEST['add2']; $d4=$_REQUEST['em']; if($a1==` ` || $b2== ` `||$c3==` ` ||$d4==` `) { echo "All fields are not entered"; exit; } $q="insert into person(name,address1,address2,email) values('$a1','$b2','$c3','$d4')"; $dbh=mysql_connect("localhost","root","root") or die("cannot connect to mysql"); $sth=mysql_db_query("web","$q") or die("query failed:" .mysql_errno() .mysql_error()); print "Record inserted"; mysql_close($mysql); ?>

DEPT OF CSE

56

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Snap 11a.html

Snap 11a.php

DEPT OF CSE

57

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

11b.html <?xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"> <html><head><title>QUERY USING PHP</title> </head><body bgcolor=lightGreen> <marquee>RETRIEVE THE DATABASE</marquee> <hr><form action=http://localhost/11b.php method=POST> <h2 align=center> <br> <label>Enter Name:<input type=text name=x></label> <br><input type=submit name=submit value="submit data"> <input type=reset name=reset value=clear> </form></h2></body></html>

11b.php <body bgcolor=lightgreen> <? $a=$_REQUEST['x'];

$dbh=mysql_connect("localhost","root","root") or die("could not connect to mysql".mysql_error());

$q="select * from person where name='$a'";

$sth=mysql_db_query("web","$q") or die("query failed".mysql_errno() .":" .mysql_error()); ?> <h2 align=center><font color=red>PERSON INFORMATION</font> <br><br> <? $i=mysql_num_rows($sth);

if($i==0): echo "No records found"; else:


DEPT OF CSE 58 MIT, MYSORE

PROGRAMMING THE WEB

[2013]

?> <table border=1> <tr> <th>NAME</th> <th>ADDRESS1</th> <th>ADDRESS2</th> <th>EMAIL</th> </tr> <? while($result=mysql_fetch_row($sth)): ?> <tr> <td><? echo $result[0];?></td> <td><? echo $result[1];?></td> <td><? echo $result[2];?></td> <td><? echo $result[3];?></td> </tr> <? endwhile; endif; mysql_close($dbh); ?>

DEPT OF CSE

59

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Snap 11b.html

Snap 11b.php

DEPT OF CSE

60

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

VIVA QUESTIONS

1) What is JavaScript?

JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A JavaScript consists of lines of executable computer code A JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license JavaScript's official name is "ECMAScript".

2) What can a JavaScript Do ?


JavaScript gives HTML designers a programming tool JavaScript can put dynamic text into an HTML page ,JavaScript can react to events ,JavaScript can read and write HTML elements

JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing

JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser

JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer

3) How is a JavaScript executed?

JavaScripts in a page will be executed immediately while the page loads into the browser, Sometimes we want to execute a script when a page loads, other times when a user triggers an event.

Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When the script is in head section, we mustl ensure that the script is loaded before anyone uses it

4) Interfacing JavaScript

JavaScript and the HTML DOM

DEPT OF CSE

61

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

With HTML 4, JavaScript can also be used to change the inner content and attributes of HTML elements dynamically. To change the content of an HTML element use: document.getElementById(id).innerHTML=new HTML To change the attribute of an HTML element use: document.getElementById(id).attribute=new value You will learn more about JavaScript and the HTML DOM in the next chapter of this tutorial.

JavaScript and HTML Events


New to HTML 4 is the ability to let HTML events trigger actions in the browser, like starting a JavaScript when a user clicks on an HTML element. To execute code when a user clicks on an element, use the following event attribute: onclick=JavaScript You will learn more about JavaScript and HTML Events in a later chapter.

JavaScript and CSS


With HTML 4, JavaScript can also be used to change the style of HTML elements. To change the style of an HTML element use: document.getElementById(id).style.property=new style 5) What is a Event handler? An event handler allows you to execute code when an event occurs.Events are generated by the browser when the user clicks an element, when the page loads, when a form is submitted, etc. 6) What is DHTML?

DEPT OF CSE

62

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

DHTML stands for Dynamic HTML. Dynamic HTML, a combination of HTML enhancements, scripting language and interface that are used to deliver animations, interactions and dynamic updating on web pages. DHTML is the merging of HTML and JavaScript. 7) What is the DOM? With JavaScript we can restructure an entire HTML document. You can add, remove, change, or reorder items on a page.To change anything on a page, JavaScript needs access to all elements in the HTML document. This access, along with methods and properties to add, move, change, or remove HTML elements, is given through the Document Object Model (DOM). In 1998, W3C published the Level 1 DOM specification. This specification allowed access to and manipulation of every single element in an HTML page. All browsers have implemented this recommendation, and therefore, incompatibility problems in the DOM have almost disappeared. The DOM can be used by JavaScript to read and change HTML, XHTML, and XML documents. The DOM is separated into different parts (Core, XML, and HTML) and different levels (DOM Level 1/2/3):

Core DOM - defines a standard set of objects for any structured document XML DOM - defines a standard set of objects for XML documents HTML DOM - defines a standard set of objects for HTML documents

8) Difference between XML and HTML? XML is not a replacement for HTML. XML and HTML were designed with different goals XML was designed to transport and store data, with focus on what data is.

HTML was designed to display data, with focus on how data looks. HTML is about displaying information, while XML is about carrying information.

9) What is XSLT? XSLT stands for XSL Transformations XSLT is the most important part of XSL
63 MIT, MYSORE

DEPT OF CSE

PROGRAMMING THE WEB

[2013]

XSLT transforms an XML document into another XML document XSLT uses XPath to navigate in XML documents

10) What is Perl? PERL- Practical Extraction and Report Language. Perl is a high-level programming language written by Larry Wall. It derives from the ubiquitous C programming language and to a lesser extent from sed, awk, the Unix shell, and at many other tools and languages. Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks involving quick prototyping, system utilities. software tools, system management tasks, database access, graphical programming, networking, and world wide web programming. Perl is a powerful free interpreter. Perl is portable, flexible and easy to learn.

11)What is PHP PHP stands for PHP: Hypertext Preprocessor. PHP is a server-side scripting language, like ASP. PHP scripts are executed on the server. PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.). PHP is an open source software. PHP is free to download and use.

12) What is a PHP File?


PHP files can contain text, HTML tags and scripts. PHP files are returned to the browser as plain HTML. PHP files have a file extension of ".php", ".php3", or ".phtml".

13) What is MySQL? MySQL is a database server. MySQL is ideal for both small and large applications. MySQL supports standard SQL. MySQL compiles on a number of platforms. MySQL is free to download and use.

DEPT OF CSE

64

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

14) Why PHP?


PHP runs on different platforms (Windows, Linux, Unix, etc.). PHP is compatible with almost all servers used today (Apache, IIS, etc.). PHP is FREE to download from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side. To get access to a web server with PHP support,Install Apache (or IIS) on your own server, install PHP, and MySQL.

15) What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases. SQL is an ANSI (American National Standards Institute) standard.

16)What Can SQL do?


SQL can execute queries against a database. SQL can retrieve data from a database. SQL can insert records in a database. SQL can update records in a database. SQL can delete records from a database. SQL can create new databases. SQL can create new tables in a database. SQL can create stored procedures in a database. SQL can create views in a database. SQL can set permissions on tables, procedures, and views.

17) ABOUT RDBMS RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collections of related data entries and it consists of columns and rows.

18) What is a Cookie?

DEPT OF CSE

65

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. 19) How to Create a Cookie The setcookie() function is used to set a cookie.Syntax setcookie(name, value, expire, path, domain); 20) About PHP session A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

When working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

21) Starting a PHP Session Before you can store user information in your PHP session, you must first start up the session. Using the session_start() function . 22) Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: 23) Destroying a Session

DEPT OF CSE

66

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable 24) What is CGI Scripting? CGI stands for Common Gateway Interface, which is the standard for creating dynamic files or web pages. CGI scripting actually refers to writing a program that will control how a website's content can be displayed to visitors. 25) What is a Web Browser? A web browser is a software application that enables users to access the World Wide Web (WWW). To do this, a web browser must provide these capabilities: A web browser must be able to understand data protocols utilized by web servers, such as HTML and XHTML. A web browser must be able to format (or render) the output of these languages.

26) What is World Wide Web? The World Wide Web is a system of interlinked hypertext documents contained on the Internet. With a web browser, one can view web pages that may contain text, images, videos, and other multimedia and navigate between them using hyperlinks.

27) What is World Wide Web Consortium (W3C)? The World Wide Web Consortium (W3C) is an international community that develops standardsto ensure the long-term growth of the Web.

28) Difference between Echo and print


Echo works faster than print(). Echo and print are language construct. Print behaves as a function and it returns an integer value. Echo does not return any values. Echo is not suitable for conditional construct

DEPT OF CSE

67

MIT, MYSORE

PROGRAMMING THE WEB Print is suitable for conditional construct Print process is slower than echo.

[2013]

29) What is a Web Server? Provides access to the web resources Server-side software responsible for handling incoming HTTP requests Computer running application software that listens and responds to a client computers request made through a web browser Machine that hosts web pages and other web documents Most commonly used Web Servers are: Apache, IIS More than 400 million web hosts in operation, more than 60% of which were Apache, around 30% were IIS Some popular Web Servers

Apache, IServer, Microsoft Internet Information Server, Macromedia ColdFusion, IBM Web Sphere Studio, Apple Webobject

30) What is a Web page?

Set of data consists of one or several web resources, that can be identified by an URI(Universal/Uniform Resource Identifier)

Electronic document that typically contains several types of information accessible via the World Wide Web

set of information created, and organized, using HTML and/or other web page authoring and development tools

Interpreted and displayed on the screen according to the instructions of the web page authoring tool

31) What is a Web Site? A collection of related web pages of a certain individual, group, or organization, connected through a system of hyperlinks, hosted in a particular domain can be a single web page that contains links to related information located on several web sites.

32) What is a home page? The main page of a web site that typically serves as an index or table of contents to other web pages usually the first web page or the welcome page the users see when they visit a web site.

DEPT OF CSE

68

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

XML Is a simplified subset of SGML. It stands for eXtensible Markup Language.

DTD Stands for Document Type Declaration. It is a set of instructions that states what tags are usable and what (re)action they create. Each browser has a DTD set in it's programming set by the browser companies. This is how some tags will work in only one type of browser or version. It has the tags stated in it's DTD. XML makes it possible to create unique tag sets by applying it's own DTD. This makes the DTD more compatible with more browsers.

XSLT Stands for eXtensible Stylesheet Language Transformation. It is a strong version of CSS that formats the XML page for viewing.

MIME type A Multipurpose Internet Mail Extension (MIME) type identifies the format of a file. The MIME type enables applications to read the file.

Uniform Resource Identifier A Uniform Resource Identifier (URI) is a string that identifies a particular location in a file system or on the Web. For example, the address of a web page is a URI.

Uniform Resource Locator A Uniform Resource Locator (URL) is the address of a particular location on the Web.

Internet A physical network connecting millions of computers using the protocols information (TCP/IP) In reality, the Internet is a network of networks. Basically, just a computer network spanning most of the world for sharing/transmitting

Server-side programming

DEPT OF CSE

69

MIT, MYSORE

PROGRAMMING THE WEB

[2013]

Server-side scripts or programs are simply programs that are run on the web server in response to requests from the client. Technologies such as CGI, Active Server Pages, Java Servlets and PHP run on Server. Best, if the program needs a lot of data and infrequent interactions with the server.

Client-side web programming Client-side scripts or programs are simply programs that are run on the web browser, downloaded from server. Technologies such as JavaScript, VBScript and Java applets all run in the client. Best, if applications that use less data and more interaction

The key difference between JavaScript and PHP: The key difference between JavaScript and PHP is that, while the Web browser interprets JavaScript once the Web page containing the script has been downloaded; server-side scripting languages like PHP are interpreted by the Web server before the page is even sent to the browser. Once interpreted, the PHP code is replaced in the Web page by the results of the script, so all the browser sees is a standard HTML file. The script is processed entirely by the server. Thus the designation: server-side scripting language.

DEPT OF CSE

70

MIT, MYSORE