0% found this document useful (0 votes)
103 views273 pages

R-16 IV/I Unit-I: HTML, Css UNIT-II: Java Script Unit-Iii: XML, Ajax Unit-Iv: PHP Unit-V: Perl Unit-Vi: Ruby

Uploaded by

rosie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views273 pages

R-16 IV/I Unit-I: HTML, Css UNIT-II: Java Script Unit-Iii: XML, Ajax Unit-Iv: PHP Unit-V: Perl Unit-Vi: Ruby

Uploaded by

rosie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 273

R- 16 IV/I

UNIT-I: HTML, CSS

UNIT-II: Java script

UNIT-III: XML , AJAX

UNIT-IV: PHP

UNIT-V: PERL

UNIT-VI: RUBY 1
Hyper Text Markup Language

2
 The Internet is the global system of interconnected computer networks that
uses the Internet protocol suite (TCP/IP) to communicate between networks
and devices. ...
 W W W – World Wide Web. It is the collections of Networks that make up
the internet
 URL – Uniform Resource Locator. The internet uses url to identify
resources available on the internet
protocol://domainname:port/websitename/webpagename
http://10.1.1.30:80/ecap/default.aspx
 HTTP – Hyper Text Transfer Protocol .The communications protocol used to
connect to Web servers on the Internet or on a local network (intranet).
Its primary function is to establish a connection with the server and send
HTML pages back to the user's browser.
It allows your web browser (i.e. Google Chrome, Mozilla Firefox, Apple
Safari or Internet Explorer) to communicate with the server where any given
website is hosted.

UNIT-1 HTML 3
UNIT-1 HTML 4
Web Application
A web application (or web app) is an application software that runs on
a web server, unlike computer-based software programs that are stored locally on
the Operating System (OS) of the device. Web applications are accessed by the
user through a web browser with an active internet connection.

Common web applications include email, online retail sales, online auctions,
wikis, instant messaging services and more.

Web Server
A web server is a computer that runs websites. It's a computer program that
distributes web pages as they are requisitioned. The basic objective of the web
server is to store, process and deliver web pages to the users. This
intercommunication is done using Hypertext Transfer Protocol (HTTP).

Web - Server Types


Apache HTTP Server
Internet Information Services.
Tomcat
XAMPP
UNIT-1 HTML 5
Web Browser
A web browser, or simply "browser," is an application used to access and view
websites. Common web browsers include Microsoft Internet Explorer, Google
Chrome, Mozilla Firefox, and Apple Safari. ...
Web Page
It is a document consists of plane text, hyper text, video files and links to another
pages to be displayed in a web borwser.
Static Web Page
Dynamic Web Page
Static Webpage : A page which don’t have any backend process is called Static
Web page
Ex : .html extension files.
Dynamic Webpage : A page which have got backend process is called dynamic
web page.
Ex : .php, .jsp, .aspx, .py extension files.

UNIT-1 HTML 6
HTML
Hyper Text Markup Language – The Language of Web Pages on the
World Wide Web.
HTML is a text formatting language.
HTML is a presentation language.
It is a collection of tags and elements.

Element
HTML element is the collection of start tag, its attributes, an end tag and everything in
between.
<body bgcolor=‘red’>Hello</body>
Tag
HTML tag (either opening or closing) is used to mark the start or end of an element
<body>,</body>
Attribute
An attribute is a keyword that is used in opening tag to give more information to the Web
Browser
<hr color=‘green’></hr>
<hr> - is a tag
color – attribute
green - value
UNIT-1 HTML 7
Block-level Elements
A block-level element always starts on a new line and takes up the full width
available (stretches out to the left and right as far as it can).
Here are the some block-level elements in HTML:
<p>,<div>,<form>,<table>,<ol>,<ul>,<h1>--<h6>,<hr>

Inline Elements
An inline element does not start on a new line and it only takes up as much width as
necessary.
<b>,<I,<br>,<img>,<span>,<input>

Codes enclosed in brackets


Usually paired
<TITLE>My Web Page</TITLE>
Not case sensitive
<TITLE> = <title> = <TITLE>

UNIT-1 HTML 8
Basic Structure of HTML document

<HTML>
<HEAD>
<TITLE>My Profile Page</TITLE>
</HEAD>
<BODY>
This is what is displayed.
</BODY>
</HTML>
◦ The file extension can be .html or .htm
◦ Comments <!-- code -->

UNIT-1 HTML 9
The Body Element
 The BODY element of a web page is an
important element in regards to the page’s
appearance.
Attributes:
 bgcolor
 background
 text
 link
<body bgcolor=‘green’ text=‘white’>
<body background=‘bg1.gif’>

UNIT-1 HTML 10
Headings, <H1> </H6>
<HTML>
<HEAD>
<TITLE> Example Page</TITLE>
</HEAD>
<BODY> Heading 1
<H1> Heading 1 </H1>
<H2> Heading 2 </H2> Heading 2
<H3> Heading 3 </H3> Heading 3
<H4> Heading 4 </H4> Heading 4
<H5> Heading 5 </H5>
Heading 5
<H6> Heading 6 </H6>
Heading 6
</BODY>
</HTML>

UNIT-1 HTML 11
Break <BR>
 Line breaks allow you to decide where the text will break on a line or continue to the end
of the window.
 A <BR> is an empty Element, meaning that it may contain attributes but it does not
contain content.
 The <BR> element does not have a closing tag.
Hello World<br>
<br>Hello World
Horizontal Rule <HR>
 The <HR> element causes the browser to display a horizontal line (rule) in your
document.
 <HR> does not use a closing tag, </HR>.
attribute : color,align,size,width
<hr color=‘red’ width=’50%’ align=‘center’ size=‘2’>

Paragraph <p></p>
A paragraph always starts on a new line, and browsers automatically add some white space (a
margin) before and after a paragraph.
attribute : align
values : left, right, center
<p align=‘right’>Hello World</p>

UNIT-1 HTML 12
 <B> Bold </B>

 <I> Italic </I>

 <U> Underline </U>

 <EM> Emphasis </EM> Browsers usually display this as italics.

 <STRONG> STRONG </STRONG> Browsers display this as bold.

 <TT> TELETYPE </TT> Text is displayed in a mono-spaced font. A typewriter text,


e.g. fixed-width font.

 <STRIKE> strike-through text</STRIKE>

 <BIG> places text in a big font</BIG>

 <SMALL> places text in a small font</SMALL>

 <SUB> places text in subscript position </SUB>

 <SUP> places text in superscript style position </SUP>

UNIT-1 HTML 13
List Elements
 unordered list — used to group a set of related items in no particular order
 ordered list — used to group a set of related items in a specific order
 description list — used to display name/value pairs such as terms and
definitions
 LI : to provide items in the List.
<UL> - UNORDERED LIST
attribute : type
values : circle, square, disk(default)
<ul type=‘square’>
<li>C</li>
</ul>
<OL> - ORDERED LIST
attribute : type
values : 1,a,A,i,I,
<ol type=‘A’>
<li>C</li>
</ol>
<DL> - DESCRIPTION LIST
<dt> - Defines a term in a description list
<dd> - Describes the term in a description list

UNIT-1 HTML 14
<IMG>

 <IMG>This element defines a graphic image on the page.

attributes
 SRC :This value will be a URL (location of the image)
 Alternate Text (ALT): This is a text field that describes an image or acts as a label.
It is displayed when they position the cursor over a graphic image.
 Alignment (ALIGN): This allows you to align the image on your page.
 Width (WIDTH): is the width of the image in pixels.
 Height (HEIGHT): is the height of the image in pixels.
 Border (BORDER): is for a border around the image, specified in pixels.
 HSPACE: is for Horizontal Space on both sides of the image specified in pixels. A
setting of 5 will put 5 pixels of invisible space on both sides of the image.
 VSPACE: is for Vertical Space on top and bottom of the image specified in pixels. A
setting of 5 will put 5 pixels of invisible space above and bellow the image.
<img src=‘logo.gif’ alt=‘Logo’ width=‘200’ height=‘200’ border=‘2’></img>

UNIT-1 HTML 15
<a> - anchor
HTML anchor tag defines a hyperlink that links one
page to another page. It can create hyperlink to other
web page as well as files, location, or any URL.

attributes
 href : Specifies the URL of the page the link goes to
 target : Specifies where to open the linked document

Values : _self, _top, _parent, _blank, framename

<a href=‘Two.html’>Two</a>

UNIT-1 HTML 16
Tables
The <TABLE></TABLE> element has four sub-elements:
1. Table Row<TR></TR>.Table Header <TH></TH>.
2. Table Data <TD></TD>.Caption <CAPTION></CAPTION>.
 <table> attributes
 BGColor: Some browsers support background colors in a table.
 Width: you can specify the table width as an absolute number of
pixels or a percentage of the document width. You can set the width
for the table cells as well.
 Border: You can choose a numerical value for the border width,
which specifies the border in pixels.
 CellSpacing: Cell Spacing represents the space between cells and is
specified in pixels.
 CellPadding: Cell Padding is the space between the cell border and
the cell contents and is specified in pixels.
 Align: tables can have left, right, or center alignment.
 Background: Background Image.
UNIT-1 HTML 17
<td> and <th> attributes

 Colspan: Specifies how many cell columns of the table this cell
should span.
 Rowspan: Specifies how many cell rows of the table this cell
should span.
 Align: cell data can have left, right, or center alignment.
 Valign: cell data can have top, middle, or bottom alignment.
 Width: you can specify the width as an absolute number of pixels
or a percentage of the document width.
 Height: You can specify the height as an absolute number of pixels
or a percentage of the document height.

UNIT-1 HTML 18
Basic Table Code

<TABLE BORDER=1 width=50%>


<CAPTION> <h1>Spare Parts <h1> </Caption>
<TR><TH>Stock Number</TH><TH>Description</TH><TH>List
Price</TH></TR>
<TR><TD bgcolor=red>3476-AB</TD><TD>76mm
Socket</TD><TD>45.00</TD></TR>
<TR><TD >3478-AB</TD><TD><font color=blue>78mm Socket</font>
</TD><TD>47.50</TD></TR>
<TR><TD>3480-AB</TD><TD>80mm Socket</TD><TD>50.00</TD></TR>
</TABLE>

UNIT-1 HTML 19
<FONT>
The font tag is used to change the color, size, and type of a text.
attributes:
 Size : to adjust the size of the text ( 1 to 7)
 Face/Type : to set the type of the font
 Color : to set the text color

<font size=5 color=‘green’>Hello World</font>


<font face=‘verdana’ size=5 color=‘green’>Hello World</font>
MARQUEE
The <marquee> tag is a container tag of HTML is implemented for creating scrollable
text or images within a web page from either left to right or vice versa, or top to bottom
or vice versa
attributes:
 width,height,direction,scrollamount,behavior,loop,bgcolor,vspace,hspace
<marquee width="60%" direction="up" height="100px">
This is a sample scrolling text that has scrolls in the upper direction.
</marquee>

UNIT-1 HTML 20
Frames
 A framed page is actually made up of multiple HTML
pages. There is one HTML document that describes how
to break up the single browser window into multiple
windowpanes. Each windowpane is filled with an
HTML document.
Main.html
Top.html

L
e
f
t
Right.html
.
h
t
m
l

UNIT-1 HTML 21
 The <FRAMESET> describes the amount of screen real estate given to each windowpane by
dividing the screen into ROWS or COLS.
 The <FRAMESET> will then contain <FRAME> elements, one per division of the browser
window.
<frameset> attributes
◦ rows
◦ cols
◦ bordercolor
◦ frameborder : yes or no
<frame> attributes
◦ name
◦ src
◦ scrolling : yes or no
◦ noresize
◦ marginwidth
◦ marginheight

UNIT-1 HTML 22
Main.html

<frameset rows=‘20%,*” bordercolor=‘red’>


<frame name=‘top’ src=‘top.html’>
<frameset cols=‘30%,*’ bordercolor=‘red’>
<frame name=‘left’ src=‘left.html’>
<frame name=‘right.html’ src=‘right.html’>
</frameset>
</frameset>

Top.html
<html>
<body bgcolor=‘green’>
<font color=‘white’><h1>USHA RAMA COLLEGE OF
ENGINEERING</h1></font>
</body>
</html>

UNIT-1 HTML 23
left.html
<html>
<body bgcolor=‘pink’>
<a href=‘aboutus.html’ target=‘right’>About Us<a><br>
<a href=‘departments.html’ target=‘right’>Departments<a><br>
<a href=‘facilities.html’ target=‘right’>Facilities<a><br>
<a href=‘contact.html’ target=‘right’>Contact Us<a><br>
</body>
</html>
right.html
<html>
<body bgcolor=‘yellow’ text=‘red’>
<h5>
Usha Rama College of Engineering and Technology, established by Usha Rama
Educational Academy, with the aim of inculcating quality education to students and
produce young technocrats having good knowledge. The college is approved by
AICTE and affiliated to JNTU-Kakinada. It is sponsored by Chicago based Multi
Million Dollar Advansoft group.
</h5>
</body>
</html>

UNIT-1 HTML 24
Summary of Tags
 <head>
 <title>
 <body>
 <h1>---</h6>
 <p>
 <br>
 <hr>
 <img>
 <a>
 Lists : <ul>,<ol>,<dl>
 Table : <table>,<caption>,<tr>,<th>,<td>
 <font> , <marquee>
 Frames : <frameset>, <frame>
 <b>,<i>,<u>,<em>
 <center>,<sub>,<sup>
 <big>,<small>
 <strong>,<strike>

UNIT-1 HTML 25
Forms
 Forms add the ability to web pages to not only provide the person
viewing the document with dynamic information but also to
obtain information from the person viewing it, and process the
information.
Objectives:
Upon completing this section, you should be able to
1. Create a FORM.
2. Add elements to a FORM.
3. Define CGI (Common Gateway Interface).
4. Describe the purpose of a CGI Application.
5. Specify an action for the FORM.
 Forms work in all browsers.
 Forms are Platform Independent.

UNIT-1 HTML 26
Forms
 To insert a form we use the <FORM></FORM> tags. The rest of
the form elements must be inserted in between the form tags.
<HTML> <HEAD>
<TITLE> Sample Form</TITLE>
</HEAD>
<BODY BGCOLOR=“FFFFFF”>
<FORM ACTION = http://www.xnu.com/formtest.asp>
<P> First Name: <INPUT TYPE=“TEXT” NAME=“fname”
MAXLENGTH=“50”> </P>
<P> <INPUT TYPE=“SUBMIT” NAME=“fsubmit1” VALUE=“Send
Info”> </P>
</FORM>
</BODY> </HTML>

UNIT-1 HTML 27
<FORM> element attributes
 ACTION: is the URL of the CGI (Common Gateway
Interface) program that is going to accept the data from
the form, process it, and send a response back to the
browser.

 METHOD: GET (default) or POST specifies which


HTTP method will be used to send the form’s contents
to the web server. The CGI application should be written
to accept the data from either method.

 NAME: is a form name used by VBScript or


JavaScripts.

 TARGET: is the target frame where the response page


will show up.

UNIT-1 HTML 28
 Form Controls

◦ Text Box
◦ Password Field
◦ Text Area
◦ Check Box
◦ Radio Button
◦ Hidden Control
◦ File Upload
◦ Choice Control
◦ Push Button
◦ Submit Button
◦ Reset Button

UNIT-1 HTML 29
 Text Box
This is a single-line editable control
<input type=‘text’>
<input type=‘text’ size=’20’>
<input type=‘text’ size=’20’ value=‘URCE’>
<input type=‘text’ size=’20’ value=‘URCE’ readonly>
<input type=‘text’ maxlength=‘20’>

 Password Field
It contains only “*” .
<input type=‘password’ size=‘20’ value=‘URCE’ readonly>

 Text Area
It can be used to enter multiple lines and multiple characters . It is created with
<textarea>.
<textarea rows=‘10’ cols=‘20’></textarea>
<textarea rows=‘10’ cols=‘20’>Welcome</textarea>

UNIT-1 HTML 30
 Check Box
This is Known as on or off control and displays small box with in tickmark in
it.It does not provide tickmark by default. It is unchecked.
<input type=‘checkbox’>I Agree
<input type=‘checkbox’ checked>I Agree
 Radio Button
Displayed usually as a circle. When selected displays a dot in the middle.
<input type=‘radio’ name=‘gender’>Male
<input type=‘radio’ name=‘gender’>Female
<input type=‘radio’ name=‘gender’ checked>Female
 Hidden Control
This control is used to store data that is not visible to the user.
<input type=‘hidden’ name=‘empid’ value=‘101’>
 Fileupload Control
This control allow the user to upload files to the Web Server.
<input type=‘file’ name=‘profilepic’>

UNIT-1 HTML 31
 Choice Control or Selection List
This is like a drop down list boxes. It is created the <select> tag.
attributes :
size : specifies the number of items to be displayed at a time.
multiple : specifies more than 1 item to be selected.
<select name=‘courses’>
<select name=‘courses’ size=4>
<select name=‘courses’ size=4 multiple>

◦ <option> tag
This tag is used to provide items to drop down list.
<option value=‘’>itemtext</option>

<select name=‘courses’>
<option value=‘1000’>C</option>
<option value=‘1500’>CPP</option>
<option value=‘4000’>Java</option>
</select>

UNIT-1 HTML 32
 Button
Buttons are the standard and clickable buttons.
<input type=‘button’ value=‘’>
Value attribute specifies the caption of the button.

◦ Submit Button
The submit button is used to send data from client to Web Server.
<input type=‘submit’> - Submit Query
<input type=‘submit’ value=‘’>

◦ Reset Button
It is used to allow the user to clear all the input data they have entered.
<input type=‘reset’> - Reset
<input type=‘reset’ value=‘’>

UNIT-1 HTML 33
UNIT-1 HTML 34
HTML HTML5

It didn’t support audio and video without the It supports audio and video controls with the use

use of flash player support. of <audio> and <video> tags.

It does not allow drag and drop effects. It allows drag and drop effects.

Not possible to draw shapes like circle, HTML5 allows to draw shapes like circle,

rectangle, triangle etc. rectangle, triangle etc.

New element for web structure like nav, header,

Elements like nav, header were not present. footer etc.

It is almost impossible to get true One can track the GeoLocation of a user easily

GeoLocation of user with the help of browser. by using JS GeoLocation API.

UNIT-1 HTML-5 2
HTML5 Features
 The canvas element for drawing
 The video and audio elements for media
playback
 Better support for local offline storage
 New content specific elements, like
article, footer, header, nav, section
 New form controls, like date, datetime,
email, url, color, image, number, tel

UNIT-1 HTML-5 3
HTML5 document
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple HTML5 document</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

UNIT-1 HTML-5 4
Structure Of HTML 5 Document

UNIT-1 HTML-5 5
<header> Tag
The <header> element represents a container for introductory content
or a set of navigational links.

A <header> element typically contains:

 one or more heading elements (<h1> - <h6>)


 logo or icon
 authorship information

<header>
<h1>Main page heading here</h1>
<p>Posted by John Doe</p>
</header>

UNIT-1 HTML-5 6
<nav> Tag
The <nav> element is used to mark up a collection of links to external
pages or sections within the current page. As well as being used for the
main website navigation.

<nav>
<ul>
<li><a href="#chapter-one">Chapter One</a>
<li><a href="#chapter-two">Chapter Two</a>
<li><a href="#chapter-three">Chapter Three</a>
</ul>
</nav>

o/p :

 Chapter One
 Chapter Two
 Chapter Three

UNIT-1 HTML-5 7
<article> Tag
 The article element represents a component of a page that consists
of a self-contained composition in a document
 Ex. Blog, newspaper article

<h1>This is the main header</h1>


<article>
<h1>Apple</h1>
<p>The <b>apple</b> is the pomaceous fruit of the apple
tree...</p>
...
</article>

O/P :
This is the main header
Apple
The apple is the pomaceous fruit of the apple tree...
... UNIT-1 HTML-5 8
<section> Tag
The section tag divides the content into section and subsections. The
section tag is used when requirements of two headers or footers or any
other section of documents needed.

<h1>How to Fish</h1>
<section>
<h2>Introduction</h2>
<p>People have been catching fish for food since before recorded
history…</p>
</section>
<section>
<h2>Equipment</h2>
<p>The first thing you’ll need is a fishing rod or pole that you find
comfortable and is strong enough for the kind of fish you’re expecting to
land…</p>
</section>

UNIT-1 HTML-5 9
<aside> Tag
The HTML <aside> element represents a portion of a document whose
content is only indirectly related to the document's main content.
Asides are frequently presented as sidebars or call-out boxes.

<aside>
<p>The Rough-skinned Newt defends itself with a deadly
neurotoxin.</p>
</aside>

UNIT-1 HTML-5 10
<footer> Tag
 The <footer> element is used to represent information about a
section such as the author, copyright information, or links to related
web pages.

<footer>
Copyright Matt West 2014
</footer>

O/P :

Copyright Matt West 2014

UNIT-1 HTML-5 11
 <progress> tag
The HTML <progress> element displays an indicator showing the
completion progress of a task, typically displayed as a progress bar.

attributes :

Value : It defines that how much work the task has been completed.
Max : It defines that how much work the task requires in total.

<progress id="file" max="100" value="70"> 70% </progress>

UNIT-1 HTML-5 12
 <audio> tag
 HTML audio tag is used to define sounds such as music and other
audio clips. Currently there are three supported file format for HTML 5
audio tag.
◦ mp3, wav , ogg
attributes:
controls : It defines the audio controls which is displayed with play/pause buttons.
Autoplay : It specifies that the audio will start playing as soon as it is ready.
Loop :It specifies that the audio file will start over again, every time when it is completed.
Muted : It is used to mute the audio output.
Preload : It specifies the author view to upload audio file when the page loads.
Src : It specifies the source URL of the audio file.

<audio controls>
<source src="myAudio.mp3" type="audio/mpeg">
<source src="myAudio.ogg" type="audio/ogg">
</audio>

UNIT-1 HTML-5 13
 <vedio> tag
 HTML 5 supports <video> tag also. The HTML video tag is used for
streaming video files such as a movie clip, song clip on the web page.
Currently, there are three video formats supported for HTML video tag:
◦ Mp4 , webM , ogg
attributes:
Controls : It defines the video controls which is displayed with play/pause buttons.
Height : It is used to set the height of the video player.
Width : It is used to set the width of the video player.
Poster : It specifies the image which is displayed on the screen when the video is not played.
Autoplay : It specifies that the video will start playing as soon as it is ready.
Loop : It specifies that the video file will start over again, every time when it is completed.
Muted : It is used to mute the video output.
Preload : It specifies the author view to upload video file when the page loads.
Src : It specifies the source URL of the video file.

<video controls>
<source src="movie.ogg" type="video/ogg">
</video>

UNIT-1 HTML-5 14
New Form Elements
 color
color provide a user interface element that lets a user specify a color,
either by using a visual color picker interface

<input type=‘color’ value=‘green’>

 date
date create input fields that let the user enter a date, either with a
textbox that validates the input or a special date picker interface.

<input type="date" id="start" name="trip-start"


value="2018-07-22"
min="2018-01-01" max="2018-12-31">

 email
email is used to let the user enter and edit an e-mail address, or, if the
multiple attribute is specified, a list of e-mail addresses.
<input type="email" id="email“>

UNIT-1 HTML-5 15
New Form Elements
 image
image is used to create graphical submit buttons, i.e. submit buttons
that take the form of an image rather than text.
<input type="image" id="image" alt="Login“ src=“button.gif">

 number
number is used to let the user enter a number. They include built-in
validation to reject non-numerical entries.
<input type="number" id="tentacles" name="tentacles“ min="10"
max="100">

 tel
tel is used to let the user enter and edit a telephone number.
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
<small>Format: 123-456-7890</small>

UNIT-1 HTML-5 16
New Form Elements
 url
url is used to let the user enter and edit a URL
<input type="url" name="url"
id="url“placeholder="https://example.com"
size="30“ required>

 datetime-local
datetime-local create input controls that let the user easily enter both a
date and a time, including the year, month, and day as well as the time
in hours and minutes.
<input type="datetime-local" id="meeting-time"
name="meeting-time" value="2018-06-12T19:30"
min="2018-06-07T00:00" max="2018-06-14T00:00">

UNIT-1 HTML-5 17
1
ADAVANTAGES OF CSS

• CSS is a formatting language used to provide more customized pages


and make it easier to make multiple pages use the same style.

• CSS separates the presentation style of document from the content of


document makes the web site maintenance a lot easier.

• CSS provides web designers with sophisticated layout opportunities


supported by all web browsers.

CSS can be applied to a Web Page in three ways

• Inline or attribute style


• Internal or tag or Embedded style
• External or link style

UNIT-1 CSS 2
Inline or Attribute style

• Inline styles are used to apply the unique style rules to an element by
putting the CSS rules directly into the start tag. It can be attached to an
element using the style attribute.

• The style attribute includes a series of CSS property and value pairs.
Each "property: value" pair

<h1 style=“color:white;background-color:blue”>Hello</h1>

tag

property
attribute value

UNIT-1 CSS 3
Internal or tag or Embedded style

• Embedded or internal style sheets only affect the document they are
embedded in.

• Embedded style sheets are defined in the <head> section of an HTML


document using the <style> element. You can define any number of
<style> elements in an HTML document but they must appear between
the <head> and </head> tags.
tag
<html>
<head>
<title>My HTML Document</title>
<style>
body { background-color: YellowGreen; }
p { color: #fff; }
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</body>
</html>
UNIT-1 CSS 4
External or Link style
• An external style sheet is ideal when the style is applied to many pages of the
website.
• An external style sheet holds all the style rules in a separate document that you can
link from any HTML file on your site.You can change the look of an entire website
by changing just one file.
• You can attach external style sheets in two ways — linking and importing.
Linking External Style Sheets
• Before linking, we need to create a style sheet first.
• An external style sheet can be linked to an HTML document using the <link> tag.
The <link> tag goes inside the <head> section
style.css Test.html
<html lang="en">
body { <head>
background: lightyellow; <title>My HTML Document</title>
font: 18px Arial, sans- <link rel="stylesheet" href="css/style.css">
serif; </head>
} <body>
h1 { <h1>This is a heading</h1>
color: orange; <p>This is a paragraph of text.</p> </body>
</html>
}

UNIT-1 CSS 5
CSS PROPERTIES

• Color and Background Properties


• Font Properties
• Text Properties
• Border Properties
• Link Properties
• List Properties
• Width and Height Properties

UNIT-1 CSS 6
Color and Background Properties
• The color property defines the text color of an element.

h1 { color: red; }
p { color: purple; }

The background properties are


• background-color : to set the background color of an element
• background-image: set an image as a background of an HTML element
• background-repeat: allows you to control how a background image is repeated
values : repeat-X, repeat-Y, no-repeat, repeat (default)
• background-attachment : determines whether the background image is fixed
with regard to the viewport or scrolls along with the containing block.
values : fixed, scroll(default)
• background-position : to control the position of the background image
values : center center, left top, right top, left bottom, right bottom,
center top, center bottom

UNIT-1 CSS 7
• background-color
body { background-color: green; }

• background-image
body { background-image: url(“bg1.gif"); }

• background-repeat
body { background-image: url("images/gradient.png");
background-repeat: repeat-x; }

• background-attachment
body {
background-image: url("images/bell.png");
background-repeat: no-repeat;
background-attachment: fixed;
}
• background-position
body {
background-image: url("images/robot.png");
background-repeat: no-repeat;
background-position: right top;
} UNIT-1 CSS 8
• FONT Properties
• CSS provide several properties for styling the font of the text, including
changing their face, controlling their size and boldness, managing variant, and
so on.
The font properties are:
font-family : to specify the font to be used to render the text
body { font-family: Arial, Helvetica, sans-serif; }

font-style : to set the font face style for the text content of an element
values : normal, italic or oblique.
p{ font-style: oblique; }

font-weight : specifies the weight or boldness of the font


values : normal, bold, bolder, lighter, 100
p{ font-weight: larger;}

font-size : to set the size of font for the text content of an element.
p{ font-size: 20px;}

font-variant : allows the text to be displayed in a special small-caps variation.


values : small-caps
p{ font-variant: small-caps;}
UNIT-1 CSS 9
• TEXT Properties
• CSS provides several properties that allows you to define various text styles
such as color, alignment, spacing, decoration, transformation, etc. very easily
and effectively.
• The text properties are:
text-align : to set the horizontal alignment of the text.
values : left, right, center
h1 { text-align: center; }
text-decoration : to set or remove decorations from text
values : none, underline, overline, line-through
a{ text-decoration: none; }
text-transform : to set the cases for a text.
values : uppercase, lowercase, capitalize
p{ text-transform : uppercase; }
text-indent : to set the indentation of the first line of text within a block of text
p{ text-indent : 25px }
line-height : to set the height of the text line.
p { line-height: 1.2; }
letter-spacing : to set extra spacing between the characters of text.
h1{ letter-spacing: 10px; }
word-spacing : to specify additional spacing between the words
h1{ word-spacing: 20px; }
UNIT-1 CSS 10
• BORDER Properties
• The CSS border properties allow you to define the border area of an element's
box.

The Border Properties are

border-style : sets the style of a box's border


values : solid, dashed, dotted, double, inset, outset, groove, and ridge.
h1 { border-style : dashed; }

border-color : specifies the color of the border area


h1 { border-style : dashed; border-color: green;}

border-width : specifies the width of the border area


h1 { border-style : dashed; border-color: green;border-width:10px;}
Border shorthand property

p {
border: 5px solid red;
}
UNIT-1 CSS 11
• LINK Properties
• A link has four different states — link, visited, active and hover. These four
states of a link can be styled differently through using the following anchor
pseudo-class selectors.
a:link : define styles for normal or unvisited links.
a:visited : define styles for links that the user has already visited.
a:hover : define styles for a link when the user place the mouse pointer over it.
a:active : define styles for links when they are being clicked.
a:link { /* unvisited link */
color: YELLOW;
text-decoration: none;
border-bottom: 1px solid;
}
a:visited { /* visited link */
color: RED;
}
a:hover { /* mouse over link */
color: GREEN;
border-bottom: none;
}
a:active { /* active link */
color: BLUE;
} UNIT-1 CSS 12
• LIST Properties
• CSS provides the several properties for styling and formatting the most
commonly used unordered and ordered lists.

• Changing the Marker Type of Lists


ul { list-style-type: square; }
ol { list-style-type: upper-roman; }

• Changing the Position of List Markers


li { list-style-position: inside; }
li { list-style-position: outside; }

• Using Images as List Markers


li { list-style-image: url("images/bullet.png"); }

• WIDTH and HEIGHT Properties


• These properties are used to resize the element.
p { width:300px;height:200px;border-width:10px;border-color:blue }

UNIT-1 CSS 13
• CSS Selectors
• A CSS selector is a pattern to match the elements on a web page. The style rules associated
with that selector will be applied to the elements that match the selector pattern.
CSS Element Selector : The Element selector selects the HTML element by name.
p { color: blue; }
CSS ID Selector : The id selector is used to define style rules for a single or unique element.
The id selector is defined with a hash sign (#) immediately followed by the id value.

<style> <body>
#error { <p id="error">This is a
color: #ff0000; warning!</p>
}
</style>
</body>

CSS Class Selector :The class selectors can be used to select any HTML
element that has a class attribute. All the elements having that class will be
formatted according to the defined rule. The class selector is defined with a period
sign (.) immediately followed by the class value.
<style>
.blue { <h1 class="blue">This is a
color: red; heading</h1>
} <p class="blue">This is a
</style> paragraph.</p>
14
UNIT-1 CSS
• CSS Selectors
Global or Universal Selector
CSS universal selectors select any type of elements in an HTML page.
An asterisk ( i.e. "*" ) is used to denote a CSS universal selector. An asterisk
can also be followed by a selector. This is useful when you want to set a style
for of all the elements of an HTML page or for all of the elements within an
element of an HTML page.
* { CSS-Property: value; ........................ }
*{
color: blue; /* color of all the elements should be blue */
background: silver; /* silver background is set for all the
elements */
}
Select all elements inside <div> elements and set their background color
to yellow:
div * {
background-color: yellow;
}
15
UNIT-1 CSS
• CSS BOX MODEL
• All HTML elements can be considered as boxes. In CSS, the term "box
model" is used when talking about design and layout.
• The CSS box model is essentially a box that wraps around every HTML
element. It consists of:
margins, borders, padding, and the actual content

16
UNIT-1 CSS
• CSS BOX MODEL
Margin - Clears an area outside the border. The margin is transparent
Border - A border that goes around the padding and content
Padding - Clears an area around the content. The padding is transparent
Content - The content of the box, where text and images appear
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: lightgrey; width: 300px; border: 15px solid green;
padding: 50px; margin: 20px; }
</style>
</head>
<body>
<h2>Demonstrating the Box Model</h2>
<p>The CSS box model is essentially a box that wraps around every HTML element. It
consists of: borders, padding, margins, and the actual content.</p>
<div>
Content
</div>
</body>
</html> 17
UNIT-1 CSS
• CSS POSITION PROPERTY
The CSS position property defines the position of an element in a document.
This property works with the left, right, top, bottom and z-index properties to
determine the final position of an element on a page.
position: value;
Value Description
Normal position for the element (where top, right,
static bottom, and left have no effect)
div { position: static; }

Position the element relative to where its normal


relative position would have been
div { position: relative; top: 10px; left: 15px; }

Position the element absolutely relative to its


absolute container
div { position: absolute; top: 10px; left: 15px; }

Position the element relative to the screen's


fixed viewport and stay fixed on screen when scrolling
div { position: fixed; top: 10px; left: 15px; }

18
UNIT-1 CSS
• CSS CURSOR PROPERTY
The cursor property specifies the mouse cursor to be displayed when pointing
over an element.
cursor: value;

• copy The cursor indicates something is to be copied


• Cell The cursor indicates that a cell (or set of cells) may be
selected
• Crosshair The cursor render as a crosshair
• Progress The cursor indicates that the program is busy (in progress)
• Text The cursor indicates text that may be selected
• Wait The cursor indicates that the program is busy
• zoom-in The cursor indicates that something can be zoomed in
• zoom-out The cursor indicates that something can be zoomed out
• No-drop The cursor indicates that the dragged item cannot be
dropped here
<div style=“cursor:no-drop”>Hello!</div>
19
UNIT-1 CSS
1
•JavaScript was originally developed as LiveScript by Netscape in the mid
1990s.
•It was later renamed to JavaScript in 1995, and became an ECMA standard in
1997. (European Computer Manufacturers Association (ECMA).
•JavaScript is the standard client-side scripting language for web-based
applications, and it is supported by virtually all web browsers available today,
such as Google Chrome, Mozilla Firefox, Apple Safari, etc.
•JavaScript is an object-oriented language, and it also has some similarities in
syntax to Java programming language. But, JavaScript is not related to Java in
any way.
What You Can Do with JavaScript
•You can modify the content of a web page by adding or removing elements.
•You can change the style and position of the elements on a web page.
•You can monitor events like mouse click, hover, etc. and react to it.
•You can perform and control transitions and animations.
•You can create alert pop-ups to display info or warning messages to the user.
•You can perform operations based on user inputs and display the results.
•You can validate user inputs before submitting it to the server.

UNIT-2 JAVA SCRIPT 2


•Difference Between Client-side and Server-side Scripting
Client-side scripting languages such as JavaScript, VBScript, etc. are
interpreted and executed by the web browser
while server-side scripting languages such as PHP, ASP, Java, Python, Ruby,
etc. runs on the web server and the output sent back to the web browser in
HTML format.

•Adding JavaScript to Your Web Pages


There are typically three ways to add JavaScript to a web page:

•Embedding the JavaScript code between a pair of <script> and </script> tag.
<script> document.write(“HEELO”);</script>

•Creating an external JavaScript file with the .js extension and then load it
within the page through the src attribute of the <script> tag.
<script src="js/hello.js"></script>

•Placing the JavaScript code directly inside an HTML tag using the special tag
attributes such as onclick, onmouseover, onkeypress, onload, etc.
<button onclick="alert('Hello World!')">Click Me</button>
UNIT-2 JAVA SCRIPT 3
•JavaScript Syntax

•A JavaScript consists of JavaScript statements that are placed within


the <script></script> HTML tags in a web page.
•JavaScript is case-sensitive. This means that variables, language keywords,
function names, and other identifiers must always be typed with a consistent
capitalization of varters.
•JavaScript support single-line as well as multi-line comments
single line //
multil line /* code */

•JavaScript Variables
Variables are fundamental to all programming languages. Variables are used to
store data, like string of text, numbers, etc. The data or value stored in the
variables can be set, updated, and retrieved whenever needed
•You can create a variable with the var keyword.

var name = "Peter Parker";


var age = 21;
var isMarried = false;
UNIT-2 JAVA SCRIPT 4
•JavaScript Syntax

•A JavaScript consists of JavaScript statements that are placed within


the <script></script> HTML tags in a web page.
•JavaScript is case-sensitive. This means that variables, language keywords,
function names, and other identifiers must always be typed with a consistent
capitalization of varters.
•JavaScript support single-line as well as multi-line comments
single line //
multil line /* code */

•JavaScript Variables
Variables are fundamental to all programming languages. Variables are used to
store data, like string of text, numbers, etc. The data or value stored in the
variables can be set, updated, and retrieved whenever needed
•You can create a variable with the var keyword.

var name = "Peter Parker";


var age = 21;
var isMarried = false;
UNIT-2 JAVA SCRIPT 5
•JavaScript Generating Output
Writing Output to Browser Console
•outputs a message or writes data to the browser console using the console.log()
console.log("Hello World!");
Writing Output to the Browser Window
document.write() method to write the content to the current document
document.write("Hello World!");
Displaying Output in Alert Dialog Boxes
alert dialog boxes to display the message or output data to the user. An alert
dialog box is created using the alert() method
alert("Hello World!");
Prompt Dialog Box
A prompt box is often used if you want the user to input a value before entering
a page.
prompt(“message”)
Confirm Dialog Box
A confirm box is often used if you want the user to verify or accept something.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
confirm(“sometext”)

UNIT-2 JAVA SCRIPT 6


•JavaScript Data Types
•Data types basically specify what kind of data can be stored and manipulated
within a program.

•The String Data Type


•The string data type is used to represent textual data (i.e. sequences of
characters). Strings are created using single or double quotes surrounding one
or more characters
var a = 'Hi there!'; // using single quotes
var b = "Hi there!"; // using double quotes
•The Number Data Type
The number data type is used to represent positive or negative numbers with or
without decimal place
var a = 25; // integer
var b = 80.5; // floating-point number

•The Boolean Data Type


The Boolean data type can hold only two values: true or false
var isReading = true;
var isSleeping = false;
UNIT-2 JAVA SCRIPT 7
•JavaScript Operators
Operators are symbols or keywords that tell the JavaScript engine to perform
some sort of actions.

•Arithmetic Operators
+,-,*,/,%

•Assignment Operators
=,+=,-=,*=,/=.%=

•Incrementing and Decrementing Operators


++,---
•Logical Operators
&&,||,!

•Comparison Operators
<,>,<=,>=,==,!=

•The Ternary Operator


?:
UNIT-2 JAVA SCRIPT 8
•JavaScript Conditional Statements
JavaScript also allows you to write code that perform different actions based
on the results of a logical or comparative test conditions at run time.

•The if statement
The if statement is used to execute a block of code only if the specified
condition evaluates to true.
if(condition){
// Code to be executed
}

•The if...else statement


The if...else statement allows you to execute one block of code if the specified
condition is evaluates to true and another block of code if it is evaluates to
false.
if(condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}
UNIT-2 JAVA SCRIPT 9
•JavaScript Conditional Statements
•The if...else if....else statement
The if...else if...else a special statement that is used to combine
multiple if...else statements.
if(condition1){
} else
if(condition2){
} else {
}
•The switch...case statement
The switch..case statement is an alternative to the if...else if...else statement,
which does almost the same thing. The switch...case statement tests a variable
or expression against a series of values until it finds a match, and then executes
the block of code corresponding to that match.
switch(x){
case value1:
break;
case value2:
break;
...
default:
} UNIT-2 JAVA SCRIPT 10
•JavaScript Loops
•while
loops through a block of code as long as the condition specified evaluates to
true.
while(condition) {
// Code to be executed
}
•do…while
loops through a block of code once; then the condition is evaluated. If the
condition is true, the statement is repeated as long as the specified condition is
true.
do {
// Code to be executed
}
while(condition);
•for
loops through a block of code until the counter reaches a specified number.
for(initialization; condition; increment) {
// Code to be executed
}
UNIT-2 JAVA SCRIPT 11
•JavaScript Loops

•for…in
loops through the properties of an object.
for(variable in object) {
// Code to be executed
}

•for…of
loops over iterable objects such as arrays, strings, etc.
for(var variable of array)
{
// Code to be executed
}
• break
terminates the current execution of the loop
break;
• continue:
terminates the current iteration of the loop
continue;
UNIT-2 JAVA SCRIPT 12
•JavaScript Arrays
Arrays are complex variables that allow us to store more than one value or a
group of values under a single variable name. JavaScript arrays can store any
valid value, including strings, numbers, objects, functions, and even other
arrays, thus making it possible to create more complex data structures such as
an array of objects or an array of arrays.

Creating an Array
var myArray = [element0, element1, ..., elementN];
var colors = ["Red", "Green", "Blue"];
var myArray = new Array(element0, element1, ..., elementN);
var colors = new Array["Red", "Green", "Blue"];
•Accessing the Elements of an Array
Array elements can be accessed by their index using the square bracket
notation. An index is a number that represents an element's position in an
array.Array indexes are zero-based.
document.write(colorss[0]);
•Getting the Length of an Array
The length property returns the length of an array
document.write(colors.length);
UNIT-2 JAVA SCRIPT 13
•JavaScript Functions
A function is a group of statements that perform specific tasks and can be kept and
maintained separately form main program. Functions provide a way to create
reusable code packages which are more portable and easier to debug

Advantages of using functions:


•Functions reduces the repetition of code within a program — Function allows you
to extract commonly used block of code into a single component. Now you can
perform the same task by calling this function wherever you want within your script
without having to copy and paste the same block of code again and again.

•Functions makes the code much easier to maintain — Since a function created once
can be used many times, so any changes made inside a function automatically
implemented at all the places without touching the several files.

•Functions makes it easier to eliminate the errors — When the program is


subdivided into functions, if any error occur you know exactly what function
causing the error and where to find it. Therefore, fixing errors becomes much easier.

UNIT-2 JAVA SCRIPT 14


•Defining and Calling a Function
The declaration of a function start with the function keyword, followed by the
name of the function you want to create, followed by parentheses i.e. () and
finally place your function's code between curly brackets {}.
function functionName() { // Code to be executed }
function sayHello() {
alert("Hello, welcome to this website!"); }
// Calling function
sayHello();
•Adding Parameters to Functions
You can specify parameters when you define your function to accept input
values at run time. The parameters work like placeholder variables within a
function; they're replaced at run time by the values (known as argument)
provided to the function at the time of invocation.
function functionName(parameter1, parameter2, parameter3) {
// Code to be executed
}
function displaySum(num1, num2) {
var total = num1 + num2; alert(total);
}
UNIT-2 JAVA SCRIPT 15
•Default Values for Function Parameters
you can specify default values to the function parameters. This means that if no
arguments are provided to function when it is called these default parameters
values will be used.
function sayHello(name = 'Guest') { alert('Hello, ' + name); }
sayHello(); // 0utputs: Hello, Guest
sayHello('John'); // 0utputs: Hello, John
• Returning Values from a Function
A function can return a value back to the script that called the function as a
result using the return statement. The value may be of any type, including
arrays and objects.
The return statement usually placed as the last line of the function before the
closing curly bracket and ends it with a semicolon
function getSum(num1, num2) { var total = num1 + num2; return total; }
• Understanding the Variable Scope
• By default, variables declared within a function have local scope that
means they cannot be viewed or manipulated from outside of that function
• Any variables declared in a program outside of a function has global scope
var x=10; //global
function test(){var y=20; // local }
UNIT-2 JAVA SCRIPT 16
•Java Script Events
• An event is something that happens when user interact with the web page, such
as when he clicked a link or button, entered text into an input box or textarea,
made selection in a select box, pressed key on the keyboard, moved the mouse
pointer, submits a form, etc.
• When an event occur, you can use a JavaScript event handler (or an event
listener) to detect them and perform specific task or set of tasks.
• By convention, the names for event handlers always begin with the word "on",
so an event handler for the click event is called onclick, similarly an event
handler for the load event is called onload, event handler for the blur event is
called onblur, and so on.
• Common HTML Events
• onchange An HTML element has been changed
• onclick The user clicks an HTML element
• onmouseover The user moves the mouse over an HTML element
• onmouseout The user moves the mouse away from an HTML element
• onkeydown The user pushes a keyboard key
• onload The browser has finished loading the page
• onfocus An HTML element has got focus
• onblur An HTML element has lost the focus.

UNIT-2 JAVA SCRIPT 17


•Java Script Events Example

• There are several ways to assign an event handler.The simplest way is to add
them directly to the start tag of the HTML elements using the special event-
handler attributes. For example, to assign a click handler for a button element,
we can use onclick attribute, like this:

<input type="button" value=“Click Me” onclick="alert('Hello World!')">

• To keep the JavaScript seperate from HTML, you can set up the event handler
in an external JavaScript file or within the <script> and </script> tags, like this:

<input type="button" value=“Click Me” onclick=“sayHello();”>


<script>
function sayHello() {
alert('Hello World!');
}
</script>

UNIT-2 JAVA SCRIPT 18


• DHTML – Dynamic HTML
Dynamic HTML, or DHTML, is a collection of technologies used together to
create interactive and animated websites by using a combination of
• a static markup language (such as HTML),
• a client-side scripting language (such as JavaScript),
• a presentation definition language (such as CSS),
• the Document Object Model (DOM).

Features of DHTML

• Tags and their properties can be changed using DHTML.


• It is used for real-time positioning.
• Dynamic fonts can be generated using DHTML.
• It is also used for data binding.
• It makes a webpage dynamic and be used to create animations, games,
applications along with providing new ways of navigating through websites.
• DHTML also facilitates the use of methods, events, properties, and codes.
• Include rollover buttons or drop-down menus.
• It is supported by big browser manufacturers like Microsoft and Netscape.

UNIT-2 JAVA SCRIPT 19


• DOM – DOCUMENT OBJECT MODEL
When a web page is loaded, the browser creates a Document Object
Model of the page.

The HTML DOM model is constructed as a tree of Objects:

UNIT-2 JAVA SCRIPT 20


The HTML DOM is an API (Programming Interface) for JavaScript:
The HTML DOM can be accessed with JavaScript (and with other programming
languages).

• In the DOM, all HTML elements are defined as objects.


• The programming interface is the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of an
HTML element).
• A method is an action you can do (like add or devaring an HTML element).

The getElementById Method


• The most common way to access an HTML element is to use the id of the
element. <p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello
World!";
</script>

The innerHTML Property


The innerHTML property is useful for getting or replacing the content of HTML
elements. UNIT-2 JAVA SCRIPT 21
•Finding HTML Elements by TagName
The getElementsByTagName() method returns a collection of all elements
in the document with the specified tag name

document.getElementsByTagName(tagname)
var x = document.getElementsByTagName("LI").length;

•Create New HTML Element


The createElement() method creates an Element Node with the specified name.
document.createElement(nodename)

After the element is created, use the element.appendChild() method to add it to


the document.

Remove Element
The removeChild() method is used to remove element.

UNIT-2 JAVA SCRIPT 22


Regular Expression
• A regular expression is a sequence of characters that forms a search pattern.
• The search pattern can be used for text search, text to replace and extract
information.
• In JavaScript, regular expressions are objects.
Creating a regular expression
• To create a regular expression in JavaScript,
• Enclose its pattern in forward-slash (/) characters like this:
var re = /hi/
• Using the RegExp constructor
var re = new RegExp('hi');
Both regular expressions are the instances of the RegExp type. They match the
string 'hi‘
Testing for matching
The test() method that allows you to test if a string contains a match of the pattern
in the regular expression. The test() method returns true if the string argument
contains a match.
var re = /hi/;
var result = re.test('hi John');
console.log(result); // true
UNIT-2 JAVA SCRIPT 23
Using pattern flags
Besides a pattern, a RegExp object also accepts an optional flag parameter. Flags
are settings that change the searching behavior.
1) The ignore flag (i)
• Regular expressions have many flags. For example, the ignore or i flag ignores
cases when searching.
• By default, searches are case-sensitive. For example /hi/ only matches the
string hi not Hi, or HI.
• To search for a string with any cases, you use the i flag:

var re = /hi/i; var re = new RegExp('hi','i');


var result = re.test('Hi John'); var result = re.test('HI John');
console.log(result); // true console.log(result); // true

24
UNIT-2 JAVA SCRIPT
2) The global flag (g)
• Without the global flag, the RegExp object only checks if there is a match in a
string and returns the first match.

• When the g flag is available, the RegExp looks for all matches and returns all
of them.It’s possible to combine flags e.g., gi flags combine the ignore (i) and
the global flag (g) flags.

• The exec() method of the RegExp performs a search for a match in a string
and returns an array that contains detailed information about the match.

var message = 'Hi, are you there? hi, HI...';


var re = /hi/gi;
re.exec(message);

25
UNIT-2 JAVA SCRIPT
Searching strings
• The method str.match(regexp) returns all matches of regexp in the string str.
• To find all matches, you use the global flag (g). And to find the matches
regardless of cases, you use the ignore flag (i).
var str = "Are you Ok? Yes, I'm OK";
var result = str.match(/OK/gi);
console.log(result); [“Ok”,”OK”]

Replacing strings
The replace() method to replace the first occurrence of the string.
var str = "Are you OK? Yes, I'm OK.";
var result = str.replace('Ok','fine');
console.log(result); Are you fine? Yes, I'm OK

Ignore and global flags to replace all occurrences regardless of cases.


var str = "Are you Ok? Yes, I'm OK.";
var result = str.replace(/OK/gi,'fine');
console.log(result); Are you fine? Yes, I'm fine.

26
UNIT-2 JAVA SCRIPT
Searching strings
The search() method uses an expression to search for a match, and returns the
position of the match.
var re = /Are/i;
var str = 'hi There! How are you?';
var index = str.search(re);
document.write(index); // 14

Regular Expression: Character Classes


\d – The digit character class which matches any single character.
var phone = ‘+1408';
var re = /\d/;
console.log(phone.match(re)); [“1”]
var re = /\d/g;
console.log(phone.match(re)); [“1”,”4”,”0”,”8”,]
\w - It matches the ASCII character [A-Za-z0-9_] including Latin alphabets,
digits, and the underscore (_)
var str = 'O2 is oxygen';
var re = /\w\d/g
console.log(str.match(re));
27
UNIT-2 JAVA SCRIPT
Regular Expression Anchors
Anchors have special meaning in regular expressions. They do not match
any character. Instead, they match a position before or after characters:

^ – The caret anchor matches the beginning of the text.


var str = 'JavaScript';
console.log(/^J/.test(str)); // true
var str = 'JavaScript';
console.log(/^S/.test(str)); // false

$ – The dollar anchor matches the end of the text.


var str = 'JavaScript';
console.log(/t$/.test(str)); // true

var isValid = /^\d\d:\d\d$/.test('12:05');


console.log(isValid); // true

var valid = /^\d\d:\d\d$/.test('12:105');


console.log(valid); // false

28
UNIT-2 JAVA SCRIPT
Regular Expression Quantifiers
Quantifiers match a number of instances of a character, group, or character
class in a string.
Exact count {n}
A number in curly braces {n}is the simplest quantifier. When you append it
to a character or character class, it specifies how many characters or
character classes you want to match.
var str = 'ECMAScript 2020';
var re = /\d{4}/;
var result = str.match(re);
console.log(result); // [“2020”]
+ - Match one or more times.
var phone = "+1-(408)";
var result = phone.match(/\d+/g);
console.log(result); // [“1”,”408”]
* - Match zero or more times.
var str = 'JavaScript is not Java';
var re = /Java\w*/g
var results = str.match(re);
console.log(results); // [“JavaScript”,”Java”]
29
UNIT-2 JAVA SCRIPT
Quantifier Description
* Match zero or more times.
+ Match one or more times.
? Match zero or one time.
{n} Match exactly n times.
{ n ,} Match at least n times.
{n,m} Match from n to m times.

• Whole numbers:/^\d+$/
• Decimal numbers:/^\d*.\d+$/
• Whole numbers and decimal numbers:/^\d*(.\d+)?$/
• Negative, positive whole numbers & decimal numbers:/^-?\d*(.\d+)?$/

30
UNIT-2 JAVA SCRIPT
Regular Expression Sets and Ranges

Sets
The square brackets search for any character in a set.
var str = 'How cats, rats, and bats became Halloween animals';
var re = /[cbr]ats/g;
var results = str.match(re);
console.log(results); // [“cats”,”rats”,”bats”]
Ranges
The square brackets can contain character ranges. For example, [a-z] is a character
range from a to z. And [0-9] is a digit from 0 to 9.

Excluding ranges
To negate a range, you use the excluding range like: [^...].
For example, [^0-9] matches any character except a digit.
Or, the [^aeiou] matches any character except 'a', 'e', 'i', 'o' and 'u'.

31
UNIT-2 JAVA SCRIPT
Java Script Objects

• An object is unordered collection of related data of primitive or reference types.


• An object is collection of properties (state) and methods (behavior).
• An object is formed by key-value pairs in JavaScript.

Company Model

Year Color

here
• Car is an Object
• Company, Model, Year and Color are properties of Car
• start(), stop() and accelerate() are methods of Car object.

32
UNIT-2 JAVA SCRIPT
Java Script Object Creation

There are three ways:

• Object Literal

var object ={property1:value, property2:value,….}

• Instance of Object

var objectname = new Object();

• Constructor Function

function object(list of values){}

33
UNIT-2 JAVA SCRIPT
Java Script Built-in Objects
Math Object
• Math object is a built-in static object.
• It is used for performing complex math operations.
Methods Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a
number.
ceil() Returns the smallest integer greater than or
equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or
equal to a number.
log() Returns the natural logarithm (base E) of a
number.
max() Returns the largest of zero or more
numbers.
min() Returns the smallest of zero or more
numbers.
pow() Returns base to the exponent power, that is
base exponent.
34
UNIT-2 JAVA SCRIPT
Java Script Built-in Objects

Date Object
• Date is a data type.
• Date object manipulates date and time.
• Date() constructor takes no arguments.
• Date object allows you to get and set the year, month, day, hour, minute, second
and millisecond fields.

35
UNIT-2 JAVA SCRIPT
Methods Description

Date() Returns current date and time.


getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1, 1970 at 12:00
AM.
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.

getMonth() Returns the month.


setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.
setMilliseconds() Sets the milliseconds.
setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.

setMonth() Sets the month.


toDateString() Returns the date portion of the Date as a human-readable string.

toLocaleString() Returns the Date object as a string.


toGMTString() Returns the Date object as a string in GMT timezone.

valueOf() Returns the primitive value of a Date object.

36
UNIT-2 JAVA SCRIPT
Java Script Built-in Objects
String Object
• String objects are used to work with text.It works with a series of characters.
Methods Description
charAt() It returns the character at the specified index.

charCodeAt() It returns the ASCII code of the character at the


specified position.
concat() It combines the text of two strings and returns a new
string.
indexOf() It returns the index within the calling String object.

match() It is used to match a regular expression against a string.

replace() It is used to replace the matched substring with a new


substring.
search() It executes the search for a match between a regular
expression.
slice() It extracts a session of a string and returns a new string.

split() It splits a string object into an array of strings by


separating the string into the substrings.

toLowerCase() It returns the calling string value converted lower case.

toUpperCase() Returns the calling string value converted to uppercase.

37
UNIT-2 JAVA SCRIPT
X M L

1
What is xml ?

• Xml (eXtensible Markup Language) is a mark up language.


• XML is designed to store and transport data.
• Xml was released in late 90’s.
• it was created to provide an easy to use and store self describing data.
• XML became a W3C Recommendation.
• XML is designed to carry data, not to display data.
• XML tags are not predefined. You must define your own tags.
• XML was designed to be both human- and machine-readable.

Features and Uses of XML

• XML separates data from HTML


• XML simplifies data sharing
• XML simplifies data transport
• XML simplifies Platform change

UNIT-3 XML 2
Difference between xml and html
• Html tags are predefined, whereas xml tags are not.
• Html is used to display data, taking care of how data is being presented. xml is
used to carry data. It takes care of how data works.
• Opening and closing tags of an xml document must be of same case. html does
not have any such restriction.
• In xml, end tags are required for well-formed (i.e. valid) document. But not in
html.
• Quotes are required around attributes values in xml, in html it is not required.
• Slash (/) required in empty tags as far as xml is concerned, html does not need
that.
XML Example
XML documents create a hierarchical structure looks like a tree so it is known as
XML Tree that starts at "the root" and branches to "the leaves".
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
UNIT-3 XML 3
Example of XML Document PROLOG

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
ROOT <to>Tove</to> CHILD
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

• The first line is the XML declaration or XML Prolog. It defines the XML
version (1.0) and the encoding used (ISO-8859-1 = Latin-1/West
European character set). UTF-8 is the default character encoding for XML
documents.
• The next line describes the root element of the document.
• The next 4 lines describe 4 child elements of the root (to, from, heading,
and body).
• And finally the last line defines the end of the root element.
UNIT-3 XML 4
Example of XML Document
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore> UNIT-3 XML 5
Well Formed XML (Valid XML)

• It must begin with the XML declaration.


• It must have one unique root element.
• All start tags of XML documents must match end tags.
• XML tags are case sensitive.
• All elements must be closed.
• All elements must be properly nested.
• All attributes values must be quoted.
• XML entities must be used for special characters.

• A "well formed" XML document is not the same as a "valid" XML


document.
• A "valid" XML document must be well formed. In addition, it must conform
to a document type definition.

There are two different document type definitions that can be used with XML:

• DTD - The original Document Type Definition


• XML Schema - An XML-based alternative to DTD
UNIT-3 XML 6
DTD : Document Type Definition
DTD check the validity of structure and vocabulary of an XML document against the
grammatical rules of the XML language

The following are some important points that a DTD describes.


• The element that can appear in an XML document.
• The order in which they appear.
• Optional and mandatory elements.
• Element attributes and whether they are optional or mandatory.
• Whether attributes can have default values.
Basic syntax of a DTD is as follows −
<!DOCTYPE root-element [
element declarations
]>
• DTD starts with <!DOCTYPE delimiter.
• An element tells the parser to parse the document from the specified root
element.
• The square brackets [ ] enclose an optional list of entity declarations called
internal subset.

UNIT-3 XML 7
Types of DTD
• Internal DTD : a DTD is declared within the file it is called Internal DTD
• External DTD : a DTD is declared in a separate file it is called External DTD.
Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML
files. To reference it as internal DTD, standalone attribute in XML declaration must
be set to yes. This means the declaration works independent of external source.
address.xml
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Mr.K.Ravi Kumar</name>
<company>Usharama</company>
<phone>9848209419</phone>
</address>
UNIT-3 XML 8
External DTD
• In external DTD elements are declared outside the XML file.
• They are accessed by specifying the system attributes which may be either the
legal .dtd file
• To reference it as external DTD, standalone attribute in the XML declaration
must be set as no. Declaration includes information from the external source.

address.xml
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Mr.K.Ravi Kumar</name>
<company>Usharama</company>
<phone>9848209419</phone>
</address>
address.dtd
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
UNIT-3 XML 9
Defining Elements in XML
• XML elements can be defined as building blocks of an XML document.
Elements can behave as a container to hold text, elements, attributes, media
objects or mix of all.
• A DTD element is declared with an ELEMENT declaration. When an XML file
is validated by DTD, parser initially checks for the root element and then the
child elements are validated.
Syntax
All DTD element declarations have this general form −
<!ELEMENT elementname (content)>
• ELEMENT declaration is used to indicate the parser that you are about to define
an element.
• elementname is the element name (also called the generic identifier) that you are
defining.
• content defines what content (if any) can go within the element.

<!ELEMENT elementname (child1, child2...)>

child1, child2.. are the elements and each element must have its own definition
within the DTD.
UNIT-3 XML 10
Defining the Order of Child Elements in XML
When there are no.of child elements you must specify the order of occurance.There
are two ways to specify the order of occurrence.

1. Using the comma between child element name and the next element child
element name that indicates the child elements will occur in the given order.

<!ELEMENT address (name,company,phone)>

2. Using a vertical line means that either one or the other child element will occur.

<!ELEMENT address (mobile | landline)>

Defining the No.of Occurances


The no.of occurrences specified with the following symbols

* - may occur 0 or more times


+ - may occur 1 or more times
? - may occur 0 or once
None – one time UNIT-3 XML 11
Defining attributes in XML Elements
• Attribute gives more information about an element or more precisely it defines a
property of an element.
• An XML attribute is always in the form of a name-value pair. An element can
have any number of unique attributes.
Syntax

<!ATTLIST element-name attribute-name attribute-type attribute-value>

• The DTD attributes start with <!ATTLIST keyword if the element contains the
attribute.
• element-name specifies the name of the element to which the attribute applies.
• attribute-name specifies the name of the attribute which is included with the
element-name.
• attribute-type defines the type of attributes.
• attribute-value takes a fixed value that the attributes must define.

<!ATTLIST hr color #PCDATA>

UNIT-3 XML 12
Attribute Values
Within each attribute declaration, you must specify how the value will appear in the
document. You can specify if an attribute −
• can have a default value
<!ATTLIST element-name attribute-name attribute-type "default-value">
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA "0">

• can have a fixed value


<!ATTLIST element-name attribute-name attribute-type #FIXED "value" >
<!ELEMENT company (#PCDATA)>
<!ATTLIST company name CDATA #FIXED “usharama">

• is required
<!ATTLIST element-name attribute-name attribute-type #REQUIRED>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA #REQUIRED>

• is implied
<!ATTLIST element-name attribute-name attribute-type #IMPLIED>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA #IMPLIED>
UNIT-3 XML 13
Limitations of DTD

• It does not support the namespaces. Namespace is a mechanism by which element


and attribute names can be assigned to groups. However, in a DTD namespaces
have to be defined within the DTD, which violates the purpose of using
namespaces.
• It supports only the text string data type.
• It is not object oriented. Hence, the concept of inheritance cannot be applied on
the DTDs.
• Limited possibilities to express the cardinality for elements.

UNIT-3 XML 14
XML Schema
• XML Schema is commonly known as XML Schema Definition (XSD).
• It is used to describe and validate the structure and the content of XML data.
• XML schema defines the elements, attributes and data types.
• Schema element supports Namespaces.
• It is similar to a database schema that describes the data in a database.
Elements
An element can be defined within an XSD

<xs:element name = "x" type = "y"/>

XML Schema Data Types:


XML Schema has a lot of built-in data types. The most common types
are:
• xs:string
• xs:decimal
• xs:integer
• xs:boolean
• xs:date
• xs:time
UNIT-3 XML 15
Types of Schema Elements
• Simple Type : simple types can only have content directly contained between the
element’s opening and closing tags. They cannot have attributes or child elements.
• Complex Type :complex types can have attributes, can contain other elements,
can contain a mixture of elements and text, etc etc.
Defining a Simple Type Element
A simple type element can be defined with <xs:simpleType>

<xs:element name=“data”>
<xs:simpleType>
<xs:element name=“firstname” type=“xs:string” />
<xs:element name=“phone” type=“xs:integer”/>
</xs:simpleType>
</xs:element>

<data>
<firstname>Ravi</firstname>
<phone>9848209419</phone>
</data>
UNIT-3 XML 16
Defining a Complex Type Element
A complex type element can be defined with <xs:complexType>

<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

• shipto is a root element.


• <xs:complexType> : It defines that the element ‘shipto’ is a complex type.
• <xs:sequence> : It is a compositor. Compositors provide rules that determine
how and in what order there children can appear within XML document

UNIT-3 XML 17
Defining Compositors
Compositors provide rules that determine how and in what order there children can
appear within XML document.
There are three types of compositors \

<xs:sequence>
The child elements in the XML document MUST appear in the order they are
declared in the XSD schema.

<xs:choice>
Only one of the child elements described in the XSD schema can appear in the XML
document.

<xs:all>
The child elements described in the XSD schema can appear in the XML document
in any order

UNIT-3 XML 18
<xs:choice>
<xs:element name=“course”>
<xs:complexType>
<xs:choice>
<xs:element name=“course1” type=”xs:string”/>
<xs:element name=“course2” type=”xs:string”/>
</xs:choice>
</xs:complexType>
</xs:element>

<xs:all>
<xs:element name=“course”>
<xs:complexType>
<xs:all>
<xs:element name=“course1” type=”xs:string”/>
<xs:element name=“course2” type=”xs:string”/>
</xs:all>
</xs:complexType>
</xs:element>
UNIT-3 XML 19
Occurrence Indicators
• It is possible to constraint the number of occurrences of an XML element that
appear in an XML document.
• The occurrence is specified using the minOccurs and maxOccurs attributes,
and allows an element to be specified as mandatory, optional, or can appear up to
a set number of times.
• The default values for minOccurs and maxOccurs is 1. Therefore, if both the
minOccurs and maxOccurs attributes are absent, the element must appear once
and once only.

<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" minOccurs="0"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>

UNIT-3 XML 20
XSD Restrictions
Restrictions are used to define acceptable values for XML elements or attributes.

<xs:restriction base = "element-type"> restrictions </xs:restriction>

base : type of the Element on which restriction is to be applied.

<xs:restriction base = "xs:integer">

specifies that this restriction is specific to an element of type int.

restriction : restriction is normally a range of conditions to be applied on the


element's value

<xs:minInclusive value = "0"/>


<xs:maxInclusive value = "100"/>

UNIT-3 XML 21
S.No. Restriction & Description

1 enumeration
Defines a list of values which are acceptable.
2 fractionDigits
Defines the maximum number of decimal places allowed(zero or more).
4 maxExclusive
Defines upper bounds for numeric values excluding this number.
5 maxInclusive
Defines upper bounds for numeric values including this number.
6 maxLength
Defines maximum length in terms of characters of string or items in a list(zero or more).
7 minExclusive
Defines lower bounds for numeric values excluding this number.
8 minInclusive
Defines lower bounds for numeric values including this number.
9 minLength
Defines minimum length in terms of characters of string or items in a list(zero or more).
10 pattern
Defines the exact sequence of characters identified by the pattern that are acceptable
11 totalDigits
Defines the exact number of digits allowed in the number(always greater than zero)

UNIT-3 XML 22
Attributes in XSD

An attribute provides extra information within an element. Attributes have name and
type properties

<xs:attribute name="x" type="y"/>

where x is the name of the attribute and y specifies the data type of the attribute

<xs:attribute name="lang" type="xs:string"/>

Default and Fixed Values for Attributes

A default value is automatically assigned to the attribute when no other value is


specified.

<xs:attribute name="lang" type="xs:string" default="EN"/>

UNIT-3 XML 23
A fixed value is also automatically assigned to the attribute, and you cannot
specify another value.

<xs:attribute name="lang" type="xs:string" fixed="EN"/>

Optional and Required Attributes

Attributes are optional by default. To specify that the attribute is required, use the
"use" attribute:

<xs:attribute name="lang" type="xs:string" use="required"/>

<xs:attribute name="lang" type="xs:string" use=“optional"/>

UNIT-3 XML 24
XML Parsing
• The purpose of parsing an XML document is to make some interfaces
available to an application that needs to make use of the document ; using
those interfaces , the application can inspect, retrieve, and modify the
document’s contents .
• Parsing is the dissection of a block of text into discernible words (also known
as tokens).
• The XML parser sits in the middle between an XML document and an
application that uses it.

There are two common ways to parse an XML document:


1. Document Object Model (DOM)
2. Simple API for XML (SAX)

UNIT-3 XML 25
What is the DOM?
• DOM is an acronym for Document Object Model.
• DOM parser loads the complete XML file into memory and creates a tree
structure where each node in the tree represents a component of XML file.
• With DOM parser you can create nodes, remove nodes, change their contents
and traverse the node hierarchy.
• DOM provides maximum flexibility while working with XML files but it comes
with a cost of potentially large memory footprint and significant processor
requirements in case of large XML files

A DOM as a tree of nodes.

UNIT-3 XML
Dom Standards

The DOM has steadily evolved by increasing the detail of the representation, the
scope of the representation, and adding new manipulation methods.
There are currently three DOM levels:
DOM Level 1:
This set of classes represents XML 1.0 and HTML 4.0 documents.
DOM Level 2:
This extends Level 1 to add support for namespaces; cascading style
sheets, level 2 (CSS2); alternate views; user interface events; and
enhanced tree manipulation via interfaces for traversal and ranges.
DOM Level 3:
This extends Level 2 by adding support for mixed vocabularies (different
namespaces), XPath expressions, load and save methods, and a
representation of abstract schemas (includes both DTD and XML
Schema).

UNIT-3 XML
Document Object Model
Generic Form:

XML Parser DOM Application


Document
Programme

UNIT-3 XML
Document Object Model
Programming interface:

• Builds a representation of an XML document in memory,

• DOM is an hierarchical data structure containing all the information in


the XML document,

• Provides access to the object representation using standard properties


and methods,

• Allows programmers access to the XML data without having to


process the actual XML statements.

UNIT-3 XML
DOM Example

<?xml version=“1.0”?>

<addressbook> Node addressbook

<person> Node person


<name>John Doe</name>
Node Name=“John Doe”
<email>[email protected]</email>
Node [email protected]
XML
</person>
Parser

<person> Node person

<name>Jane Doe</name>
Node Name=“John Doe”
<email>[email protected]</email>
Node [email protected]
</person>
</addressbook>

UNIT-3 XML
Common DOM Methods

 Node.getNodeType()- the type of the underlying object, e.g.


Node.ELEMENT_NODE.

 Node.getNodeName() - value of this node, depending on its type, e.g. for


elements it‘s tag name, for text nodes always string #text.

 Node.getFirstChild() and Node.getLastChild()- the first or last child of a given


node.

 Node.getNextSibling() and Node.getPreviousSibling()- the next or previous


sibling of a given node.

 Node.getAttributes()- collection containing the attributes of this node (if it is an


element node) or null.

UNIT-3 XML
Common DOM methods
 Node.getNodeValue()- value of this node, depending on its type, e.g. value of an
attribute but null in case of an element node.

 Node.getChildNodes()- collection that contains all children of this node.

 Node.getParentNode()- parent of this node.

 Element.getAttribute(name)- an attribute value by name.

 Element.getTagName()- name of the element.

 Element.getElementsByTagName()- collection of all descendant Elements with


a given tag name.

UNIT-3 XML
Common DOM methods

 Element.setAttribute(name,value)- adds a new attribute, if an attribute with


that name is already present in the element, its value is changed.

 Attr.getValue()- the value of the attribute.

 Attr.getName()- the name of this attribute.

 Document.getDocumentElement()- allows direct access to the child node that


is the root element of the document.

 Document.createElement(tagName)- creates an element of the type specified.

UNIT-3 XML
Simple API for XML (SAX)

 SAX is an acronym for Simple API for XML.

 SAX Parser parses the XML file line by line and triggers events when it
encounters opening tag, closing tag or character data in XML file.

 SAX parser is called an event-based parser

 Parser sends events to programmer‘s code (start and end of every


component).

 Programmer decides what to do with every event.

 SAX parser does not create any objects at all, it simply delivers events.

UNIT-3 XML
SAX features
 SAX API acts like a data stream.

 Stateless.

 Events are not permanent.

 Data not stored in memory.

 Impossible to move backward in XML data.

 Impossible to modify document structure.

 Fastest and least memory intensive way of working with XML.

UNIT-3 XML
Basic SAX events

 startDocument – receives notification of the beginning of a document.

 endDocument – receives notification of the end of a document.

 startElement – gives the name of the tag and any attributes it might have.

 endElement – receives notification of the end of an element.

 characters – parser will call this method to report each chunk of character
data.

UNIT-3 XML
Additional SAX events

 ignorableWhitespace – allows to react (ignore) whitespace in element content.

 warning – reports conditions that are not errors or fatal errors as defined by the
XML 1.0 recommendation, e.g. if an element is defined twice in a DTD.

 error – non-fatal error occurs when an XML document fails a validity


constraint.

 fatalError – a non-recoverable error e.g. the violation of a well-formed-ness


constraint; the document is unusable after the parser has invoked this method.

UNIT-3 XML
SAX events in a simple example

<?xml version="1.0"?> startDocument()


<xmlExample> startElement(): xmlExample
<heading> startElement(): heading
This is a simple characters(): This is a simple example
example. endElement(): heading
</heading> characters(): That is all folks
That is all folks. endElement(): xmlExample
</xmlExample> endDocument()

UNIT-3 XML
How Does SAX work?

XML Document SAX Objects


<?xml version=“1.0”?> Parser startDocument

<addressbook> Parser startElement


<person>
<name>John Doe</name> Parser startElement & characters
<email>[email protected]</email> Parser startElement & characters
</person> Parser endElement

<person> Parser startElement


<name>Jane Doe</name> Parser startElement & characters
<email>[email protected]</email> Parser startElement & characters
</person> Parser endElement
</addressbook> Parser endElement & endDocument

UNIT-3 XML
DOM vs SAX

DOM (Document Object Model)


 Parses entire document
 Represents result as a tree
 Lets you search tree
 Lets you modify tree
 Good for reading data/configuration files
SAX (Simple API for XML)
 Parses until you tell it to stop
 Fires event handlers for each:
◦ Start tag
◦ Tag body
◦ End tag
 Low level APIs
 Good for very large documents, especially if you only care about very
small portions of the document.

UNIT-3 XML
XSLT

XSLT stands for eXtensible Stylesheet Language Transformation


XSLT is a transformation language that is used to transform/convert source XML
documents to XML documents or to other formats such as HTML, PDF by
using XSL-FO (Formatting Objects), etc.

XSL
 Before learning XSLT, we should first understand XSL which stands for
EXtensible Stylesheet Language. It is similar to XML as CSS is to HTML.
 In case of HTML document, tags are predefined such as table, div, and span; and
the browser knows how to add style to them and display those using CSS styles.
 But in case of XML documents, tags are not predefined. In order to understand
and style an XML document, World Wide Web Consortium (W3C) developed
XSL which can act as XML based Stylesheet Language.
 An XSL document specifies how a browser should render an XML document.

UNIT-3 XML
How XSLT Works
 An XSLT stylesheet is used to define the transformation rules to be applied on
the target XML document. XSLT stylesheet is written in XML format.
 XSLT Processor takes the XSLT stylesheet and applies the transformation rules
on the target XML document and then it generates a formatted document in the
form of XML, HTML, or text format.
 This formatted document is then utilized by XSLT formatter to generate the
actual output which is to be displayed to the end-user.

UNIT-3 XML
XSLT ELEMENTS
1. <xsl:stylesheet>
Every XSLT code must start with the root element either <xsl:stylesheet> or
<xsl:transform>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="2.0">

UNIT-3 XML
2. <xsl:template>
This declaration defines a set of rules applied to process or transform the selected
input element of the source document to the defined target element rules of the
output documents.
Basically two types of templates are available as per their attributes:
(i) Named Template: When the xsl: template element contains @name attribute
then this is called Named Template.
<xsl:template name="book">
Named templates are called by xsl:call-template element.
<xsl:call-template name="book">
(ii) Match Template: The xsl:template element contains @match attribute that
contains a matching pattern or XPath applied at the input nodes.
<xsl:template match="/">
<xsl:template match=“//book”>
Match templates are called by xsl:apply-template element.
<xsl:apply-templates select="book"/>

UNIT-3 XML
3. <xsl:value-of>
◦ The <xsl:value-of> element extracts the value of a selected node.
◦ The <xsl:value-of> element can be used to select the value of an XML element
and add it to the output.
<xsl:value-of select="expression“>
select : an attribute
expression : An XPath expression that specifies which node/attribute to extract the
value from.
<xsl:value-of select="catalog/cd/title" />
4. <xsl:if>
To put a conditional if test against the content of the XML file, add an <xsl:if>
element to the XSL document.
<xsl:if test="expression">
...some output if the expression is true...
</xsl:if>

<xsl:if test="price &gt; 10">

UNIT-3 XML
<xsl:for-each>
The XSL <xsl:for-each> element can be used to select every XML element of a
specified node-set:

<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>

UNIT-3 XML
<xs:sort>
The <xsl:sort> element is used to sort the output.
<xsl:for-each select="catalog/cd">
<xsl:sort select="artist"/>
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>

UNIT-3 XML
PHP

UNIT - 4 PHP 1
 The Internet is the global system of interconnected computer networks that
uses the Internet protocol suite (TCP/IP) to communicate between networks
and devices. ...
 W W W – World Wide Web. It is the collections of Networks that make up
the internet
 URL – Uniform Resource Locator. The internet uses url to identify
resources available on the internet
protocol://domainname:port/websitename/webpagename
http://10.1.1.30:80/ecap/default.aspx
 HTTP – Hyper Text Transfer Protocol .The communications protocol used to
connect to Web servers on the Internet or on a local network (intranet).
Its primary function is to establish a connection with the server and send
HTML pages back to the user's browser.
It allows your web browser (i.e. Google Chrome, Mozilla Firefox, Apple
Safari or Internet Explorer) to communicate with the server where any given
website is hosted.

UNIT-4 PHP 2
UNIT-4 PHP 3
Web Application
A web application (or web app) is an application software that runs on
a web server, unlike computer-based software programs that are stored locally on
the Operating System (OS) of the device. Web applications are accessed by the
user through a web browser with an active internet connection.

Common web applications include email, online retail sales, online auctions,
wikis, instant messaging services and more.

Web Server
A web server is a computer that runs websites. It's a computer program that
distributes web pages as they are requisitioned. The basic objective of the web
server is to store, process and deliver web pages to the users. This
intercommunication is done using Hypertext Transfer Protocol (HTTP).

Web - Server Types


Apache HTTP Server
Internet Information Services.
Tomcat
XAMPP
UNIT-4 PHP 4
Web Browser
A web browser, or simply "browser," is an application used to access and view
websites. Common web browsers include Microsoft Internet Explorer, Google
Chrome, Mozilla Firefox, and Apple Safari. ...
Web Page
It is a document consists of plane text, hyper text, video files and links to another
pages to be displayed in a web borwser.
Static Web Page
Dynamic Web Page
Static Webpage : A page which don’t have any backend process is called Static
Web page
Ex : .html extension files.
Dynamic Webpage : A page which have got backend process is called dynamic
web page.
Ex : .php, .jsp, .aspx, .py extension files.

UNIT-4 PHP 5
What is PHP?
• PHP stands for Hypertext Preprocessor.
• PHP is a very popular and widely-used open source server-side
scripting language to write dynamically generated web pages.
• PHP was originally created by Rasmus Lerdorf in 1994.
• It was initially known as Personal Home Page.
• PHP scripts are executed on the server and the result is sent to the
web browser as plain HTML.
• PHP can be integrated with the number of popular databases,
including MySQL, PostgreSQL, Oracle, Microsoft SQL Server,
Sybase, and so on.
• The current major version of PHP is 7

UNIT - 4 PHP 6
What You Can Do with PHP
• You can generate pages and files dynamically.
• You can create, open, read, write and close files on the server.
• You can collect data from a web form such as user information,
email, phone no, etc.
• You can send emails to the users of your website.
• You can send and receive cookies to track the visitor of your
website.
• You can store, delete, and modify information in your database.
• You can restrict unauthorized access to your website.
• You can encrypt and decrypt data for safe transmission over
internet.

UNIT - 4 PHP 7
Setting Up a Local Web Server
PHP script execute on a web server running PHP. So before you start writing any
PHP program you need the following program installed on your computer.

• The Apache Web server


• The PHP engine
• The MySQL database server

You can either install them individually or choose a pre-configured package for
your operating system like Linux and Windows.
Popular pre-configured package are XAMPP and WampServer.

UNIT - 4 PHP 8
XAMPP Web Server

• XAMPP stands for Cross-Platform (X), Apache (A), MySQL (M),


PHP (P) and Perl (P).
• It is a simple, lightweight Apache distribution that makes it extremely
easy for developers to create a local web server for testing purposes.
Everything you need to set up a web server – server application
(Apache), database (MySQL), and scripting language (PHP) – is
included in a simple extractable file.
• XAMPP is also cross-platform, which means it works equally well on
Linux, Mac and Windows.

XAMPP Installation Steps

UNIT - 4 PHP 9
PHP File

• PHP is file the combination of template text and PHP Script


• template text can be plain text or HTML.
• template text is executed at the client side ie Web Browser.
• A PHP script is executed on the server, and the plain HTML result is
sent back to the browser.
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
• The default file extension for PHP files is ".php".

UNIT - 4 PHP 10
PHP Comments

• A comment in PHP code is a line that is not executed as a part of the


program. Its only purpose is to be read by someone who is looking at
the code.
• Singleline Comment
• //
• #
• Multiline Comment
/*
PHP code
*/

UNIT - 4 PHP 11
PHP output statements
The PHP echo Statement
• The echo statement can output one or more strings.
• The echo statement can display anything that can be displayed to the browser,
such as string, numbers, variables values, the results of expressions etc.
• you can use it without parentheses e.g. echo or echo().
• If you want to pass more than one parameter to echo, the parameters must not
be enclosed within parentheses.
<?php
// Displaying HTML code
echo "<h4>This is a simple heading.</h4>";
echo "<h4 style='color: red;'>This is heading with style.</h4>";
?>
The PHP print Statement
• You can also use the print statement (an alternative to echo) to display output to
the browser.
• You can also use it without parentheses like: print or print().
• Both echo and print statement works exactly the same way except that the print
statement can only output one string, and always returns 1.
<?php
// Displaying HTML code
print "<h4>This is a simple heading.</h4>";
print "<h4 style='color: red;'>This is heading with style.</h4>";
?> UNIT - 4 PHP 12
PHP processor modes

• The PHP processor has two modes:

• copy
• interpret.

• The processor starts off in copy mode; text from the file, typically HTML, is
copied to the network connection and sent to the client browser.
• When a <?php processing instruction is encountered the processor switches to
interpret mode. The PHP statements are interpreted, and their output, if any, is
sent to the browser. The processor remains in interpret mode until a ?> is
encountered.
• which switches it back to copy mode.

UNIT - 4 PHP 13
PHP Variables
• Variables are used to store data, like string of text, numbers, etc. Variable
values can change over the course of a script.
• In PHP, a variable does not need to be declared before adding a value to it.
• PHP automatically converts the variable to the correct data type, depending on
its value.
Naming Conventions for PHP Variables
• All variables in PHP start with a $ sign, followed by the name of the variable.
• A variable name must start with a letter or the underscore character _.
• A variable name cannot start with a number.
• A variable name in PHP can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _).
• A variable name cannot contain spaces.

$txt = "Hello World!";


$number = 10;

UNIT - 4 PHP 14
PHP Constants
• A constant is a name or an identifier for a fixed value. Constant are like
variables, except that once they are defined, they cannot be undefined or
changed
• Constants are very useful for storing data that doesn't change while the script is
running.
• Common examples of such data include configuration settings such as database
username and password, website's base URL, company name, etc.
• Constants are defined using PHP's define() function, which accepts two
arguments: the name of the constant, and its value. Once defined the constant
value can be accessed at any time just by referring to its name

<?php
//Defining constant
define("SITE_URL", "https://www.tutorialrepublic.com/");
// Using constant
echo ‘ Thank you for visiting - ' . SITE_URL;
?>

UNIT - 4 PHP 15
Data Types in PHP
The values assigned to a PHP variable may be of different data types including
simple string and numeric types to more complex data types like arrays and
objects.

PHP supports total eight primitive data types:

•Integer
•Float
•String
•Boolean
• Array
•Object
• resource
•NULL

UNIT - 4 PHP 16
PHP Operators
Operators are symbols that tell the PHP processor to perform certain actions.
Arithmetic Operators
+ - Addition
- - Subtraction
* - multiplication
/ - Division
% - Modulus
Assignment Operators
= - Assign
+= - Add and Assign
-= - Subtract and Assign
*= - Multiply and Assign
/= - Division and Assign
%= - Modulus and Assign
Comparison Operators
< - less than
> - greater than
<= - less than or equal to
>= - greater than or euqal to
== - equals
!= - not equals UNIT - 4 PHP 17
PHP Operators
Logical Operators
and - And
or - or
xor - Xor
&& - And
|| - Or
! - Not

Incrementing and Decrementing Operators


++ - increment
-- - decrement

String Operators
. - concatenation
.= - concatenation assignment

UNIT - 4 PHP 18
PHP Data type Conversion
The mechanism of converting one type data into another type is called data
type conversion

There are two types of conversion

• Implicit type conversion


• Explicit type conversion or type casting

Implicit type conversion


• PHP is a loosely typed language that allows you to declare a variable and
its type simply by using it.
• It also automatically converts values from one type to another whenever
required. This is called implicit casting.
<?php
$a = 56;
$b = 12;
$c = $a / $b;
echo $c; # 4.66
?>

UNIT - 4 PHP 19
PHP Data type Conversion
Explicit type conversion
Type casting refers to changing an variable of one data type into another
explicitly.
By placing the type name in parentheses in front of a variable, PHP converts
the value to the desired type:

Cast type Description


(int) (integer) Cast to an integer by dropping the decimal
portion

(bool) (boolean) Cast to a Boolean

(float) (double) (real) Cast to a floating-point number

(string) Cast to a string

(array) Cast to an array

(object) Cast to an object

$c = (int) ($a / $b);

UNIT - 4 PHP 20
PHP GET and POST
Methods of Sending Information to Server
A web browser communicates with the server typically using one of the two HTTP
(Hypertext Transfer Protocol) methods — GET and POST
The GET Method
In GET method the data is sent as URL parameters that are usually strings of name
and value pairs separated by ampersands (&). In general, a URL with GET data
will look like this:
http://www.example.com/action.php?name=john&age=24
Advantages and Disadvantages of Using the GET Method
• Since the data sent by the GET method are displayed in the URL, it is possible
to bookmark the page with specific query string values.
• The GET method is not suitable for passing sensitive information such as the
username and password, because these are fully visible in the URL query string
as well as potentially stored in the client browser's memory as a visited page.
• Because the GET method assigns data to a server environment variable, the
length of the URL is limited. So, there is a limitation for the total data to be
sent.
• PHP provides the super global variable $_GET to access all the information
sent either through the URL or submitted through an HTML form using the
method="get".
UNIT - 4 PHP 21
PHP GET and POST
The POST Method

In POST method the data is sent to the server as a package in a separate


communication with the processing script. Data sent through POST method will
not visible in the URL.

Advantages and Disadvantages of Using the POST Method

• It is more secure than GET because user-entered information is never visible in


the URL query string or in the server logs.
• There is a much larger limit on the amount of data that can be passed and one
can send text data as well as binary data (uploading a file) using POST.
• Since the data sent by the POST method is not visible in the URL, so it is not
possible to bookmark the page with specific query.
• Like $_GET, PHP provide another super global variable $_POST to access
all the information sent via post method or submitted through an HTML form
using the method="post".

UNIT - 4 PHP 22
PHP GET and POST
The $_REQUEST Variable

PHP provides another superglobal variable $_REQUEST that contains the values
of both the $_GET and $_POST variables as well as the values of the $_COOKIE
superglobal variable.

$name = $_GET[‘uname’]

$name = $_POST[‘uname’]

$name = $_REQUEST[‘uname’]

UNIT - 4 PHP 23
PHP Conditional Statements
PHP also allows you to write code that perform different actions based on the
results of a logical or comparative test conditions at run time.
• The if statement
• The if...else statement
• The if...else if....else statement
• The switch...case statement
The if Statement
The if statement is used to execute a block of code only if the specified condition
evaluates to true.
if(condition){
// Code to be executed
}
The if...else Statement
The if...else statement allows you to execute one block of code if the specified
condition is evaluates to true and another block of code if it is evaluates to false.
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
UNIT - 4 PHP 24
PHP Conditional Statements
The if...else if...else Statement
The if...else if...else a special statement that is used to combine multiple if...else
statements.
if(condition1){
// Code to be executed if condition1 is true
} else if(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
Switch…Case Statements
The switch-case statement is an alternative to the if-else if-else statement, which
does almost the same thing. The switch-case statement tests a variable against a
series of values until it finds a match, and then executes the block of code
corresponding to that match.
switch(n){
case label1:
// Code to be executed if n=label1
break;
case label2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels} UNIT - 4 PHP 25
PHP Loops
• Loops are used to execute the same block of code again and again, as long as a
certain condition is met.
• The basic idea behind a loop is to automate the repetitive tasks within a program
to save the time and effort
• while
• do-while
• for
• foreach
while Loop
The while statement will loops through a block of code as long as the condition
specified in the while statement evaluate to true.
while(condition){
// Code to be executed
}
do…while Loop
With a do-while loop the block of code executed once, and then the condition is
evaluated, if the condition is true, the statement is repeated as long as the specified
condition evaluated to is true.
do{
// Code to be executed
}while(condition);
UNIT - 4 PHP 26
PHP Loops
for Loop

The for loop repeats a block of code as long as a certain condition is met. It is
typically used to execute a block of code for certain number of times.

for(initialization; condition; increment){


// Code to be executed
}

foreach Loop
The foreach loop is used to iterate over arrays.

foreach($array as $value){
// Code to be executed
}

UNIT - 4 PHP 27
PHP Arrays
Arrays are complex variables that allow us to store more than one value or a
group of values under a single variable name.

Types of Arrays in PHP


There are three types of arrays that you can create. These are:
• Indexed or Numeric Arrays: An array with a numeric index where
values are stored linearly.
• Associative Arrays: An array with a string index where instead of linear
storage, each value can be assigned a specific key.
• Multidimensional Arrays: An array which contains single or multiple
array within it and can be accessed via multiple indices.

• An array is created using an array() function in PHP.

Indexed or Numeric Arrays


These type of arrays can be used to store any type of elements, but an index is
always a number. By default, the index starts at zero.

$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");


echo $name_one[0]; # Zack
UNIT - 4 PHP 28
PHP Arrays
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage,
every value can be assigned with a user-defined key of string type.

$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
echo "Salary of mohammad is ". $salaries['mohammad']

Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array
and each element in the sub-array can be an array or further contain array within
itself and so on. $contacts = array(
array(
"name" => "Peter Parker",
"email" => "[email protected]",
),
array(
"name" => "Clark Kent",
"email" => "[email protected]",
);
echo "Peter Parker's Email-id is: " .
$contacts[0]["email"];
# [email protected]
29
UNIT - 4 PHP
PHP Functions
Advantages of using functions:

• Functions reduces the repetition of code within a program


• Functions makes the code much easier to maintain.
• Functions makes it easier to eliminate the errors.
• Functions can be reused in other application

Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:

function functionName() {
code to be executed;
}
<?php
function writeMsg() {
echo "Hello world!";
}

To call the function, just write its name followed by brackets ():
writeMsg(); // call the function
UNIT - 4 PHP 30
PHP Functions
Functions with Parameters
• You can specify parameters when you define your function to accept input
values at run time.
• The parameters work like placeholder variables within a function; they're
replaced at run time by the values (known as argument) provided to the
function at the time of invocation.
function myFunc($oneParameter, $anotherParameter){
// Code to be executed
}
Functions with Optional Parameters and Default Values
You can also create functions with optional parameters — just insert the parameter
name, followed by an equals (=) sign, followed by a default value
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello,
world!</p>";
}
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
UNIT - 4 PHP 31
PHP Functions
Returning Values from a Function

A function can return a value back to the script that called the function using the
return statement. The value may be of any type, including arrays and objects.
A function can not return multiple values. However, you can obtain similar results
by returning an array

function getSum($num1, $num2){


$total = $num1 + $num2;
return $total;
}
function divideNumbers($dividend, $divisor){
$quotient = $dividend / $divisor;
$array = array($dividend, $divisor, $quotient);
return $array;
}

UNIT - 4 PHP 32
PHP Functions
Passing Arguments to a Function by Reference
• In PHP there are two ways you can pass arguments to a function: by value
and by reference.
• By default, function arguments are passed by value so that if the value of the
argument within the function is changed, it does not get affected outside of
the function.
• To allow a function to modify its arguments, they must be passed by
reference.
• Passing an argument by reference is done by prepending an ampersand (&) to
the argument name in the function definition

function selfMultiply(&$number){
$number *= $number;
return $number;
}

UNIT - 4 PHP 33
PHP Functions
Understanding the Variable Scope
• you can declare the variables anywhere in a PHP script.
• The location of the declaration determines the extent of a variable's visibility
within the PHP program i.e. where the variable can be used or accessed. This
accessibility is known as variable scope.
• By default, variables declared within a function are local and they cannot be
viewed or manipulated from outside of that function

The global Keyword


you can use the global keyword before the variables inside a function. This
keyword turns the variable into a global variable, making it visible or accessible
both inside and outside the function

$greet = "Hello World!";


function test(){
global $greet;
echo $greet;
}

UNIT - 4 PHP 34
PHP Cookies
What is a Cookie

A cookie is a small text file that lets you store a small amount of data (nearly
4KB) on the user's computer. They are typically used to keeping track of
information such as username that the site can retrieve to personalize the page
when user visit the website next time

Setting a Cookie in PHP

The setcookie() function is used to set a cookie in PHP. Make sure you call the
setcookie() function before any output generated by your script otherwise cookie
will not set
setcookie(name, value, expire, path, domain, secure);

parameters of the Cookie

setcookie("username", "John Carter");

UNIT - 4 PHP 35
PHP Cookies
Accessing Cookies Values
The PHP $_COOKIE superglobal variable is used to retrieve a cookie value. It
typically an associative array that contains a list of all the cookies values sent by
the browser in the current request, keyed by cookie name. The individual cookie
value can be accessed using standard array notation
echo $_COOKIE["username"];
it's a good practice to check whether a cookie is set or not before accessing its
value. To do this you can use the PHP isset() function
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
Removing Cookies
You can delete a cookie by calling the same setcookie() function with the cookie
name and any value (such as an empty string) however this time you need the set
the expiration date in the past
setcookie("username", "", time()-3600);

UNIT - 4 PHP 36
PHP Sessions
• Although you can store data using cookies but it has some security issues.
Since cookies are stored on user's computer it is possible for an attacker to
easily modify a cookie content to insert potentially harmful data in your
application that might break your application.

• Also every time the browser requests a URL to the server, all the cookie data
for a website is automatically sent to the server within the request. It means if
you have stored 5 cookies on user's system, each having 4KB in size, the
browser needs to upload 20KB of data each time the user views a page, which
can affect your site's performance.

• You can solve both of these issues by using the PHP session.
• A PHP session stores data on the server rather than user's computer.
• In a session based environment, every user is identified through a unique
number called session identifier or SID.
• This unique session ID is used to link each user with their own
information on the server like emails, posts, etc.

UNIT - 4 PHP 37
PHP Sessions
Starting a PHP Session
Before you can store any information in session variables, you must first start up
the session. To begin a new session, simply call the PHP session_start() function.
It will create a new session and generate a unique session ID for the user.
session_start();
The session_start() function first checks to see if a session already exists by
looking for the presence of a session ID. If it finds one, i.e. if the session is already
started, it sets up the session variables and if doesn't, it starts a new session by
creating a new session ID.
Storing and Accessing Session Data
You can store all your session data as key-value pairs in the $_SESSION[]
superglobal array. The stored data can be accessed during lifetime of a session.
Consider the following script, which creates a new session and registers two
session variables.
session_start();
// Storing session data
$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker";
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];

UNIT - 4 PHP 38
MYSQL DATABASE
• It is open-source database software, which is supported by Oracle Company.
• It is fast, scalable, and easy to use database management system in comparison
with Microsoft SQL Server and Oracle Database.
• It is developed, marketed, and supported by MySQL AB, a Swedish company,
and written in C programming language and C++ programming language.

PHP Connect to MySQL Server


• The mysqli_connect() function is used to connection.
• All communication between PHP and the MySQL database server takes place
through this connection.

$link = mysqli_connect("hostname", "username", "password", "database");

• The hostname parameter specify the host name (e.g. localhost), or IP address of
the MySQL server,
• whereas the username and password parameters specifies the credentials to
access MySQL server,
• The database parameter, if provided will specify the default MySQL database
to be used when performing queries.
UNIT - 4 PHP 39
Inserting Data into a MySQL Database Table
• The mysqli_query() function to insert data in table

mysqli_query(connection, query, resultmode)

connection : required
query : required
resultmode : optional

Retrieving data from a database


The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set
and returns it as an enumerated array.

mysqli_fetch_row(result)

The fetch_array() / mysqli_fetch_array() function fetches a result row as an


associative array, a numeric array, or both.

mysqli_fetch_array(result,resulttype)
UNIT - 4 PHP 40
AJAX
• AJAX stands for Asynchronous Javascript And XML.It is a technique for
better, faster and more interactive Web Applications with the help and Java
Script
• Synchronous Model : A Synchronous request blocks the client until operation
completes.
• Asynchronous Model : An Asynchronous request does not block the client
operation, at that time user can perform another operation also.

AJAX Benefits
• Reduce the server traffic in both side request. Also reducing the time
consuming on both side response.
• AJAX is much responsive.
• AJAX make asynchronous calls to a web server. This means client browsers
are avoid waiting for all data arrive before start the rendering.
• Form are common element in web page. Validation should be instant and
properly, AJAX gives you all of that, and more.
• No require to completely reload page again. AJAX is improve the speed and
performance. Fetching data from database and storing data into database
perform background without reloading page.

UNIT - 4 PHP 41
HOW AJAX WORKS?

UNIT - 4 PHP 42
AJAX
• User sends a request from the UI and a javascript call goes to
XMLHttpRequest object.
• HTTP Request is sent to the server by XMLHttpRequest object.
• Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
• Data is retrieved.
• Server sends XML data or JSON data to the XMLHttpRequest callback
function.
• HTML and CSS data is displayed on the browser.

Processing steps
To write an AJAX based application a programmer should follow the below steps
1. Create an XMLHttpRequest
It provides a set of properties and methods that are used to send httprequest and to
retrieve data from the server.
2. Specify handels
We must specify a function to be called when the http response from the server
comes back. We call this function as response handler. This function will receive
information returned by the server, extract the data and perform a specific task.

UNIT - 4 PHP 43
AJAX
Processing steps
3. AJAX readystate property
The process of communicating with the server for sending HttpRequest to getting
a response involves 5 states.
Property Description

onReadyStateChange It is called whenever readystate


attribute changes. It must not be used
with synchronous requests.
readyState represents the state of the request. It
ranges from 0 to 4.0 UNOPENED open()
is not called.
1 OPENED open is called but send() is
not called.
2 HEADERS_RECEIVED send() is called,
and headers and status are available.
3 LOADING Downloading data;
responseText holds the data.
4 DONE The operation is completed
fully.

reponseText returns response as text.


responseXML returns response as XML

UNIT - 4 PHP 44
AJAX
• Sending a request consists of two steps
1. Open a connection
2. Sending an HttpRequest.

Open a coonection : The open() is used establish communication between Web


Browser and Web Server.

open(method,URL)
open(method,URL,boolean)

Sending an HttpRequest.:

Once the TCP connection is established We can send the HttpRequest through the
server with this connection using send() method.

void send()
Retrieving Information :
We can retrieve the server’s response by using responseText or responseXML
properties. The response may be a simple string or a complete XML.

UNIT - 4 PHP 45
UNIT-5 PERL 1
• Perl is the Practical Extraction and Report Language
• Perl is a general-purpose programming language originally developed
for text manipulation and now used for a wide range of tasks including
system administration, web development, network programming, GUI
development, and more.
• Perl was created by Larry Wall.
• Perl is a stable, cross platform programming language.
• Perl is a portable, command line driven, interpreted
Programming/scripting language.
• It is used for mission critical projects in the public and private sectors.
• Perl is Open Source software, licensed under the GNU General
Public License(GPL).
UNIT-5 PERL 2
Perl Features
• It has a very simple Object-oriented programming syntax.
• It is easily extendible as it supports 25,000 open source modules.
• It supports Unicode.
• It includes powerful tools to process text to make it compatible with mark-up
languages like HTML, XML.
• It supports third party database including Oracle, MySQL and many others.
• It is embeddable in other systems such as web servers and database servers.
• It is open source software licensed under GNU.
• Many frameworks are written in Perl.
• It can handle encrypted web data including e-commerce transactions.
• It is a cross platform language.
• It offers a regular expression engine which is able to transform any type of
text. UNIT-5 PERL 3
Perl Syntax
• A Perl program consists of a sequence of declarations and statements, which
run from the top to the bottom.
• Loops, subroutines, and other control structures allow you to jump around
within the code.
• Every simple statement must end with a semicolon (;).
• Perl is case-sensitive.
First Perl Program
Interactive Mode Programming
• You can use Perl interpreter with -e option at command line, which lets you
execute Perl statements from the command line.

$perl -e “print “’Hello World\n’”

Perl File Extension


• A Perl script can be created inside of any normal simple-text editor program.
• As a Perl convention, a Perl file must be saved with a .pl or .PL file extension
in order to be recognized as a functioning Perl script.
perl hello.pl

UNIT-5 PERL 4
Perl Variables
Variables are the reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.

Perl has the three basic data types −


• Scalars
• Arrays
• Hashes
Scalars
A scalar is a single unit of data. That data might be an integer number, floating
point, a character, a string, a paragraph, or an entire web page.
Numeric Scalars
A scalar is most often either a number or a string.

$integer = 200;
$negative = -300;
$floating = 200.340;

UNIT-5 PERL 5
Perl Variables
Variables are the reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.

Perl has the three basic data types −


• Scalars
• Arrays
• Hashes
Scalars
A scalar is a single unit of data. That data might be an integer number, floating
point, a character, a string, a paragraph, or an entire web page. A scalar variable
starts with a dollar sign ($)
Numeric Scalars
A scalar is most often either a number or a string.
$integer = 200;
$negative = -300;
$floating = 200.340;

String Scalars
$var = "This is string scalar!";
$quote = 'I m inside single quote - $var'; UNIT-5 PERL 6
Perl Arrays
An array is a variable that stores an ordered list of scalar values. Array variables
are preceded by an "at" (@) sign.
Array Creation
Array variables are prefixed with the @ sign and are populated using either
parentheses or the qw operator.

@array = (1, 2, 'Hello');


@array = qw/This is an array/;

Accessing Array Elements


When accessing individual elements from an array, you must prefix the variable
with a dollar sign ($) and then append the element index within the square
brackets

print $array[0];

Perl returns element referred to by a negative index from the end of the array.

print $array[-1];
UNIT-5 PERL 7
Perl Arrays
Sequential Number Arrays
Perl offers a shortcut for sequential numbers and letters. Rather than typing out
each element

@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);

Array Size
The size of an array can be determined using the scalar context on the array - the
returned value will be the number of elements in the array −

$count = @days;

Adding and Removing Elements in Array


The push() function appends one or more elements to the end of the array, while
the pop() function removes the last element from the end of the array.
push(@array,”aaa”);
pop(@array);
UNIT-5 PERL 8
Perl Hashes
• A hash is a set of key/value pairs. Hash variables are preceded by a percent
(%) sign.
• A hash is sometimes referred to as an associative array.
• The keys are unique strings and values are scalar values.

%capitals = (
"India" => "New Delhi",
"South Korea" => "Seoul",
"USA" => "Washington, D.C.",
"Australia" => "Canberra"
);
print"$capitals{'India'}\n";
print"$capitals{'South Korea'}\n";
print"$capitals{'USA'}\n";
print"$capitals{'Australia'}\n";

UNIT-5 PERL 9
Perl Hashes
Add a new element
To add a new element to hash, you use a new key-pair value.

$langs{'Italy'} = 'Italian';

Remove a single key/value pair


If you know the hash key, you can remove single key-value pair from the hash by
using delete() function as follows:

delete $langs{'China'};

Modify hash elements


You can modify value of existing key/value pair by assigning a new value as
shown in the following example:
# add new key value pair
$langs{'India'} = 'Many languages';
# modify official language of India
$langs{'India'} = 'Hindi'; #

UNIT-5 PERL 10
Perl Operators

Perl language supports many operator types but following is a list of most
frequently used operators:

•Arithmetic Operators
•Relational Operators
•Logical Operators
•Assignment Operators
•Bitwise Operators

chop : removes the last character of the string completely

chomp : removes the last character if it is a newline.

UNIT-5 PERL 11
if statement
An if statement consists of a Boolean expression followed by one or
more statements.

if...else statement
An if statement can be followed by an optional else statement.

if...elsif...else statement
An if statement can be followed by an optional elsif statement and then
by an optional else statement.

UNIT-5 PERL 12
unless statement
An unless statement consists of a Boolean expression followed by one
or more statements. If the boolean expression evaluates to false, then the
block of code inside the unless statement will be executed
unless...else statement
An unless statement can be followed by an optional else statement.
unless...elsif..else statement
An unless statement can be followed by an optional elsif statement and
then by an optional else statement.
switch statement
With latest versions of Perl, We can make use of switch statement
which allows a simple way of comparing a variable value against various
conditions.

UNIT-5 PERL 13
Control Structures
A loop statement allows us to execute a statement or group of statements multiple times.
Perl programming language provides following four types of loops to handle looping
requirements
while
Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.
do..while
Like a while statement, except that it tests the condition at the end of the
loop body
for
Execute a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
foreach
The foreach loop iterates over a normal list value and sets the variable
VAR to be each element of the list in turn.

UNIT-5 PERL 14
Control Structures
A loop statement allows us to execute a statement or group of statements
multiple times. Perl programming language provides following four types
of loops to handle looping requirements
until
Repeats a statement or group of statements until a given condition becomes true. It tests the
condition before executing the loop body.
nested loops
We can use one or more loop inside any another while, for or do..while
loop.
next
next operator in Perl skips the current loop execution and transfers the
iterator to the value specified by the next.
last
The last keyword is a loop-control statement that immediately causes the
current iteration of a loop to become the last. No further statements are
executed, and the loop ends.

UNIT-5 PERL 15
Perl Functions/Subroutines
A Perl subroutine or function is a group of statements that together perform a
task. We can divide up the code into separate subroutines. Perl uses the terms
subroutine, method and function interchangeably.
 You define functions with the sub keyword.
 A function can be placed anywhere in your Perl source code file.

Define and Call a Function


The general form of a function is:
sub functionName
{
body of the functions
}
Function calling

functionname();functioname
functionname();

UNIT-5 PERL 16
Example
# Function definition
sub Hello
{
print "Hello, World!\n";
}
# Function call
Hello();

Passing Arguments to a Function


We can pass various arguments to a subroutine and they can be accessed inside the function using the
special array @_ . Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.
sub Sum
{
$sum = 0;
($a,$b,$c) = @-;
$sum = $a+$b+$c;
print "Sum of the given numbers :
$sum\n";
}
# Function call
Sum(10, 20, 30);
UNIT-5 PERL 17
Returning Value from a Function

sub Average
{
# get total number of arguments passed.
$n = @_;
$sum = 0;
foreach $item (@_)
{
$sum += $item;
}
$average = $sum / $n;
return $average;
}
# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers : $num\n";

UNIT-5 PERL 18
Perl I/O
Standard I/O
In Perl, the file handles STDIN, STDOUT, and STDERR stand for the standard
input (from keyboard), standard output (to screen), and standard error output (to
screen, no buffering) respectively. The notation
<input-source> is handy to read lines from an input source.

For example,
$line = <STDIN>; /* or simply $line = <> */

Reads one line from standard input. Repeated execution of this statement will let
you read line by line. The value of $line has the line termination character at the
end.

A handy function to remove any line terminator is the Perl built-in function
chomp:
$str = chomp($line);

UNIT-5 PERL 19
File I/O
Opening and Closing Files
There are following two functions with multiple forms which can be used to open any new
or existing file in Perl.

open FILEHANDLE, EXPR


open FILEHANDLE
sysopen FILEHANDLE, FILENAME, MODE, PERMS
sysopen FILEHANDLE, FILENAME, MODE

Here FILEHANDLE is the file handle returned by open function and EXPR is the
expression having file name and mode of opening the file.

Open Function
Following is the syntax to open file.txt in read-only mode. Here less than < sign
indicates that file has to be opened in read-only mode.

open(IN, "<file.txt");

Here IN is the file handle which will be used to read the file. Here is the example which
will open a file and will print its content over the screen.

UNIT-5 PERL 20
creating or writing mode.
Here greater than ( > ) sign indicates that file has to be opened in writing mode

open(OUT, ">file.txt") or die "Couldn't open file file.txt, $!";

If we want to open a file for reading and writing, we can put a plus sign (+)
before the > or < characters.
For example, to open a file for updating without truncating it:

open(OUT, "+<file.txt") or die "Couldn't open file file.txt, $!";

We can open a file in append mode. In this mode writing point will be set to the
end of the file.

open(OUT,">>file.txt") || die "Couldn't open file file.txt, $!";

A double >> opens the file for appending, placing the file pointer at the end, so
that we can immediately start appending information.

UNIT-5 PERL 21
Following is the table which gives possible values of different modes

< or r Read Only Access


> or w Creates, Writes, and Truncates
>> or a Writes, Appends, and Creates
+< or r+ Reads and Writes
+> or w+ Reads, Writes, Creates, and Truncates
+>> or a+ Reads, Writes, Appends, and Creates

Close Function

To close a filehandle, and therefore disassociate the file handle from the corresponding file,
we use the close
function. This flushes the file handle’s buffers and closes the system's file descriptor.

close FILEHANDLE close

If no FILEHANDLE is specified, then it closes the currently selected filehandle. It returns


true only if it could successfully flush the buffers and close the file.

close (IN) or die "Couldn't close file properly";

UNIT-5 PERL 22
seek
This function moves to a specified position in a file.
You can move relative to

seek FILEHANDLE,POSITION,WHENCE
the beginning of the file (WHENCE = 0),
the current position (WHENCE = 1),
or the end of the file (WHENCE = 2).

This function is mainly used with fixed length records to randomly access specific records of
the file.

seek $fh, 20, SEEK_SET;

tell
Returns the current position in bytes for FILEHANDLE

tell(FILEHANDLE)

UNIT-5 PERL 23
PERL – CGI
Common Gateway Interface (CGI)
The Common Gateway Interface (CGI) provides the middleware between
WWW servers and external databases and information sources. The World
Wide Web Consortium (W3C) defined the Common Gateway Interface (CGI)
and also defined how a program interacts with a Hyper Text Transfer Protocol
(HTTP) server. The Web server typically passes the form information to a
small application program that processes the data and may send back a
confirmation message. This process or convention for passing data back and
forth between the server and the application is called the common gateway
interface (CGI).
Features of CGI:
 It is a very well defined and supported standard.
 CGI scripts are generally written in either Perl, C, or maybe just a simple
shell script.
 CGI is a technology that interfaces with HTML.
 CGI is the best method to create a counter because it is currently the
quickest
 CGI standard is generally the most compatible with today’s browsers

UNIT-5 PERL 24
PERL – CGI

Advantages of CGI:

 The advanced tasks are currently a lot easier to perform in CGI than in Java.
 It is always easier to use the code already written than to write your own.
 CGI specifies that the programs can be written in any language, and on any
platform, as long as they conform to the specification.
 CGI-based counters and CGI code to perform simple tasks are available in
plenty.

Disadvantages of CGI:
There are some disadvantages of CGI which are given below:
 In Common Gateway Interface each page load incurs overhead by having to
load the programs into memory.
 Generally, data cannot be easily cached in memory between page loads.
 There is a huge existing code base, much of it in Perl.
 CGI uses up a lot of processing time.

UNIT-5 PERL 25
PERL – CGI

Common Gateway Interface (CGI) is nothing more than a protocol which


defines the interaction of web servers with some executable programs in order
to produce dynamic web pages.
Basically, it shows how the web server sends information to the program and
the program sends the information back to the web server which in turn can be
sent back to the browser. Between web servers and external programs, it is
considered as the standard programming interface.

CGI stands for:

 Common: Interaction with many different OS.


 Gateway: It provides the way to the users in order to gain access to different
programs such as picture generator or databases etc.
 Interface: It uses a method for interaction with Web server.

UNIT-5 PERL 26
CGI ARCHITECTURE

UNIT-5 PERL 27
Web Server Support & Configuration
Before you proceed with CGI Programming, make sure that your Web Server
supports CGI and it is configured to handle CGI Programs. All the CGI
Programs be executed by the HTTP server are kept in a pre-configured
directory. This directory is called CGI Directory and by convention it is named
as /cgi-bin. By convention PERL CGI files will have extention as .cgi.

First CGI Program


#!/usr/bin/perl

print "Content-type:text/html\r\n\r\n"; print '<html>';


print '<head>';
print '<title>Hello Word - First CGI Program</title>'; print '</head>';
print '<body>';
print '<h2>Hello Word! This is my first CGI program</h2>'; print '</body>';
print '</html>'; 1;

Output :
Hello Word! This is my first CGI program

UNIT-5 PERL 28
Web Server Support & Configuration
Before you proceed with CGI Programming, make sure that your Web Server
supports CGI and it is configured to handle CGI Programs. All the CGI
Programs be executed by the HTTP server are kept in a pre-configured
directory. This directory is called CGI Directory and by convention it is named
as /cgi-bin. By convention PERL CGI files will have extention as .cgi.

First CGI Program


#!/usr/bin/perl

print "Content-type:text/html\r\n\r\n"; print '<html>';


print '<head>';
print '<title>Hello Word - First CGI Program</title>'; print '</head>';
print '<body>';
print '<h2>Hello Word! This is my first CGI program</h2>'; print '</body>';
print '</html>'; 1;

Output :
Hello Word! This is my first CGI program

UNIT-5 PERL 29
CGI Environment Variables
All the CGI program will have access to the following environment
variables. These variables play an important role while writing any CGI
program.
CONTENT_TYPE
The data type of the content. Used when the client is sending attached content to the
server. For example file upload etc.
CONTENT_LENGTH
2 The length of the query information. It's available only for POST requests.
HTTP_COOKIE
Return the set cookies in the form of key & value pair.
HTTP_USER_AGENT
The User-Agent request-header field contains information about the user agent
originating the request. Its name of the web browser.
PATH_INFO
The path for the CGI script.
QUERY_STRING
The URL-encoded information that is sent with GET method request.
REMOTE_ADDR
The IP address of the remote host making the request. This can be useful for logging or
for authentication purpose.

UNIT-5 PERL 30
REMOTE_HOST
The fully qualified name of the host making the request. If this information is not
available then REMOTE_ADDR can be used to get IR address.
REQUEST_METHOD
The method used to make the request. The most common methods are GET and POST.
SCRIPT_FILENAME
The full path to the CGI script.
SCRIPT_NAME
The name of the CGI script.
SERVER_NAME
The server's hostname or IP Address.
SERVER_SOFTWARE
The name and version of the software the server is running.

UNIT-5 PERL 31
Pattern Matching or Regular Expressions in Perl
 A regular expression is a string of characters that defines the pattern or patterns
you are viewing.
 The syntax of regular expressions in Perl is very similar to what you will find
within other regular expression. Supporting programs, such as sed, grep, and
awk.

There are three regular expression operators inside perl:

 Matching regular expression operator


 Substitute regular expression operator
 Transliterate regular expression operator

Perl Matching Operator =~


The matching operator =~ is used to match a word in the given string. It is case
sensitive, means if string has a lowercase letter and you are searching for an
uppercase letter then it will not match.

UNIT-5 PERL 32
The following are some simple matching examples involving the string $line:

$line=”A big fat hen”;


if ( $line =~ /hen/ ) ## contains hen
if ( $line =~ /Hen/ ) ## does not contain Hen
if ( $line =~ /Hent/i ) ## contains Hen, ignoring case
if ( $line =~ /^Hen/ ) ## Hen at beginning of line
if ( $line =~ /hen$/ ) ## hen at end of line

If the pattern contains / then it is convenient to use a leading m which allows you to use any non-
alphanumeric character as the pattern delimiter:

Pattern Meaning
\n A newline
\t A tab
\w Any alphanumeric (word) character, same as [a-zA-Z0-9_]
\W Any non-word character, same as [^a-zA-Z0-9_]
\d Any digit. The same as [0-9]
\D Any non-digit. The same as [^0-9]
\s Any whitespace character: space, \t, \n, etc
\S Any non-whitespace character

UNIT-5 PERL 33
The Perl relational operators =~ (match) and !~ (non-match) are used for pattern matching. In Perl,
patterns are specified as extended regular expressions. Patterns are given inside /'s (the pattern delimiter).
Symbol
Meaning
/ / Represents a pattern
^At beginning of the string
$At the end of the string
I ignore case
G global search

UNIT-5 PERL 34
UNIT-6 RUBY 1
Ruby is "A Programmer's Best Friend".
Ruby is an object-oriented programming language. It was created in 1993 by
Yukihiro Matsumoto of Japan. Matsumoto is also known as ―Matz in the Ruby
community.

Features of ruby:
• Ruby is an open-source and is freely available on the Web, but it is
subject to a license.
• Ruby is a general-purpose, interpreted programming language.
• Ruby is an object-oriented programming language.
• Ruby is a server-side scripting language similar to Python and PERL.
• Ruby can be embedded into Hypertext Markup Language (HTML).
• Ruby is very much scalable and big programs written in Ruby are easily
maintainable.
• Ruby can be used for developing Internet and intranet applications.
• Ruby can be installed in Windows and POSIX environments.
• Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL.
• Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase.
• Ruby has a rich set of built-in functions, which can be used directly into
Ruby scripts.
UNIT-6 RUBY 2
Variables
Ruby variables are locations which hold data to be used in the programs. Each variable has
a different name. These variable names are based on some naming conventions. Unlike
other programming languages, there is no need to declare a variable in Ruby. A prefix is
needed to indicate it.

There are four types of variables in Ruby:

• Local variables
• Class variables
• Instance variables
• Global variables

Local Variables:
• A local variable name always starts with a lowercase letter(a-z) or underscore (_).
These variables are local to the code construct in which they are declared.
• A local variable is only accessible within the block of its initialization. Local variables
are not available outside the method. There is no need to initialize the local variables.

Example:
age = 10 _Age = 20

UNIT-6 RUBY 3
Class Variables:
• A class variable name starts with @@ sign. They need to be initialized before
use.
• A class variable belongs to the whole class and can be accessible from
anywhere inside the class. If the value will be changed at one instance, it will
be changed at every instance.
• A class variable is shared by all the descendents of the class. An uninitialized
class variable will result in an error.

class States
@@no_of_states=0
def initialize(name)
@states_name=name
@@no_of_states += 1
end
end

UNIT-6 RUBY 4
Instance Variables:
• An instance variable name always starts with a @ sign. They are similar to
Class variables but their values are local to specific instances of an object.
• Instance variables are available across methods for any specified instance or
object i.e. instance variables can change from object to object. There is no
need to initialize the instance variables and uninitialized instance variable
always contains a nil value.

Example:

class Customer
def initialize(id, name, addr)
# Instance Variables
@cust_id = id
@cust_name = name
@cust_addr = addr
end
end

UNIT-6 RUBY 5
Global Variables
• A global variable name always starts with $. Class variables are not available
across classes. If you want to have a single variable, which is available across
classes, you need to define a global variable.
• Its scope is global, means it can be accessed from anywhere in a program. By
default, an uninitialized global variable has a nil value and its use can cause
the programs to be cryptic and complex.

Example:
# global variable
$global_variable = 10
class Class1
def print_global
puts "Global variable in Class1 is #$global_variable"
end
end

UNIT-6 RUBY 6
SIMPLE I/O
All the I/O methods are derived from the class IO.

The class IO provides all the basic methods, such as read, write, gets, puts,
readline, getc, and print.

The puts Statement


The puts statement instructs the program to display the value stored in the
variable. This will add a new line at the end of each line it writes.

val1 = "This is variable one"


puts val1

The gets Statement


The gets statement can be used to take any input from the user from standard
screen called STDIN.

puts "Enter a value :"


val = gets
puts val

UNIT-6 RUBY 7
The putc Statement

Unlike the puts statement, which outputs the entire string onto the screen,
the putc statement can be used to output one character at a time.

The output of the following code is just the character H −

str = "Hello Ruby!"


putc str

The print Statement

The print statement is similar to the puts statement. The only difference is that
the puts statement goes to the next line after printing the contents, whereas with
the print statement the cursor is positioned on the same line.

print "Hello World"


print "Good Morning“

UNIT-6 RUBY 8
Ruby – Operators
Operators are a symbol which is used to perform different operations.

Types of operators:

• Arithmetic operator : +, - , * , / , %, **
• Assignment operator : =, += , -= , *= , /= , %=, **=
• Comparison operator : < , > , <= , >= , == , !=
• Logical operator : &&, ||, !
• Bitwise operator : & , | , << , >> , ^ , ~
• Ternary operator : ?:
• Range operator : .. , …

UNIT-6 RUBY 9
Ruby Control Statements

• if statement
• if-else statement
• if-else-if (elsif) statement
if statement
Ruby if statement tests the condition. The if block statement is executed if
condition is true.

if (condition)
//code to be executed
end
a = gets.chomp.to_i
if a >= 18
puts "You are eligible to vote."
end

UNIT-6 RUBY 10
Ruby Control Statements

if -- else
Ruby if else statement tests the condition. The if block statement is executed if
condition is true otherwise else block statement is executed.

if(condition)
//code if condition is true
else
//code if condition is false
end

a = gets.chomp.to_i
if a >= 18
puts "You are eligible to vote."
else
puts "You are not eligible to vote."
end

UNIT-6 RUBY 11
if else if (elsif)
Ruby if else if statement tests the condition. The if block statement is executed if
condition is true otherwise else block statement is executed.

if(condition1)
//code to be executed if condition1is true
elsif (condition2)
//code to be executed if condition2 is true
else (condition3)
//code to be executed if condition3 is true
end
a = gets.chomp.to_i
if a > 0
puts “Positive:;
elsif a < 0
puts “Negative”;
else
puts “ZERO”;

UNIT-6 RUBY 12
Ruby while Loop
The Ruby while loop is used to iterate a program several times. If the number of
iterations is not fixed for a program, while loop is used.

Ruby while loop executes a condition while a condition is true. Once the
condition becomes false, while loop stops its execution.

while conditional [do]


code
end
x = gets.chomp.to_i
while x >= 0
puts x
x -=1
end

UNIT-6 RUBY 13
do -- loop
The Ruby do while loop iterates a part of program several times. It is quite
similar to a while loop with the only difference that loop will execute at least
once.

loop do
#code to be executed
break if booleanExpression
end
loop do
puts "Checking for answer"
answer = gets.chomp
if answer != '5'
break
end
end

UNIT-6 RUBY 14
Until Loop
The Ruby until loop runs until the given condition evaluates to true. It exits the
loop when condition becomes true. It is just opposite of the while loop which runs
until the given condition evaluates to false.

The until loop allows you to write code which is more readable and logical.

until conditional
code
end
i=1
until i == 10
print i*10, "\n"
i += 1
end

UNIT-6 RUBY 15
Ruby for Loop

Ruby for loop iterates over a specific range of numbers. Hence, for loop is used if
a program has fixed number of iterations.

Ruby for loop will execute once for each element in expression.

for variable [, variable ...] in expression [do]


code
end

a = gets.chomp.to_i
for i in 1..a do
puts i
end

UNIT-6 RUBY 16
Break Statement

The Ruby break statement is used to terminate a loop. It is mostly used in while
loop where value is printed till the condition is true, then break statement
terminates the loop.

The break statement is called from inside the loop.

break

i=1
while true
if i*5 >= 25
break
end
puts i*5
i += 1
end

UNIT-6 RUBY 17
Next Statement
The Ruby next statement is used to skip loop's next iteration. Once the next
statement is executed, no further iteration will be performed.

The next statement in Ruby is equivalent to continue statement in other


languages.

next

for i in 5...11
if i == 7 then
next
end
puts i
end

UNIT-6 RUBY 18
Ruby Arrays
Ruby arrays are ordered collections of objects. They can hold objects like integer, number,
hash, string, symbol or any other array.
Its indexing starts with 0. The negative index starts with -1 from the end of the array. For
example, -1 indicates last element of the array and 0 indicates first element of the array.

Creating Ruby Arrays


A Ruby array is created in many ways.

Using literal constructor []


Using new class method

Using literal construct []


A Ruby array is constructed using literal constructor []. A single array can contain different
type of objects.
exm = [4, 4.0, "Jose", ]
puts exm

Using new class method


A Ruby array is constructed by calling ::new method with zero, one or more than one
arguments.
arrayName = Array.new
arrayName = Array.new(10)
UNIT-6 RUBY 19
Accessing Array Elements
Ruby array elements can be accessed using [] method. You can pass one or more than one
arguments or even a range of arguments.

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]


puts days[0]

at method
To access a particular element, at method can also be used.

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]


puts days.at(0)
puts days.at(-1)

first and last method


The first and last method will return first and last element of an array respectively

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]


puts days.first
puts days.last

UNIT-6 RUBY 20
Adding Items to Array
Ruby array elements can be added in different ways.

• push or <<
• unshift
• insert
push or <<
Using push or <<, items can be added at the end of an array.
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
puts days.push("Today")
puts days << ("Tomorrow")
unshift
Using unshift, a new element can be added at the beginning of an array.
days = ["Fri", "Sat", "Sun"]
puts days.unshift("Today")
insert
Using insert, a new element can be added at any position in an array. Here, first we
need to mention the index number at which we want to position the element.
days = ["Fri", "Sat", "Sun"]
puts days.insert(2, "Thursday")
UNIT-6 RUBY 21
Removing Items from Array
Ruby array elements can be removed in different ways.
• pop
• shift
• delete
• uniq
pop
Using pop, items can be removed from the end of an array. It returns the removed item.

shift
Using shift, items can be removed from the start of an array. It returns the removed item.

delete
Using delete, items can be removed from anywhere in an array. It returns the removed item.

uniq
Using uniq, duplicate elements can be removed from an array. It returns the remaining array.

UNIT-6 RUBY 22
Ruby Hashes
A Ruby hash is a collection of unique keys and their values. They are similar to
arrays but array use integer as an index and hash use any object type. They are
also called associative arrays, dictionaries or maps.

If a hash is accessed with a key that does not exist, the method will return nil.

name = {"key1" => "value1", "key2" => "value2", "key3" => "value3"...}
OR
name = {key1: 'value1', key2: 'value2', key3: 'value3'...}

Creating Ruby Hash


Ruby hash is created by writing key-value pair within {} curly braces.

To fetch a hash value, write the required key within [] square bracket.

color = {
"Rose" => "red",
"Lily" => "purple",
}
puts color['Rose']
UNIT-6 RUBY 23
Ruby Hashes Methods

has_key?
The has_key? method allows you to check if a hash contains a specific key. It
returns a boolean value.
name_and_age.has_key?("Steve")

select
The select method allows you to pass a block and will return any key-value pairs
that evaluate to true when ran through the block.

name_and_age.select { |k,v| k == "Bob" }

fetch
The fetch method allows you to pass a given key and it will return the value for that
key if it exists. You can also specify an option for return if that key is not present.

name_and_age.fetch("Larry", "Larry isn't in this hash");

UNIT-6 RUBY 24
Ruby Hashes Methods

to_a
The to_a method returns an array version of your hash when called. Let's see it in
action. It doesn't modify the hash permanently though.

name_and_age.to_a;

keys and values


if you want to just retrieve all the keys or all the values out of a hash, you can do so
very easily:
name_and_age.keys
name_and_age.values

UNIT-6 RUBY 25
Ruby - Methods

Ruby methods are very similar to functions in any other programming language.
Ruby methods are used to bundle one or more repeatable statements into a single
unit.
Method names should begin with a lowercase letter. If you begin a method name
with an uppercase letter, Ruby might think that it is a constant and hence can
parse the call incorrectly.

def method_name [( [arg [= default]]...[, * arg [, &expr ]])]


expr..
end

def method_name (var1 = value1, var2 = value2)


expr..
end

Whenever you call the simple method, you write only the method name as
follows −
method_name
method_name 25, 30
UNIT-6 RUBY 26
Default Arguments

def test(a1 = "Ruby", a2 = "Perl")


puts "The programming language is #{a1}"
puts "The programming language is #{a2}"
end
test "C", "C++"
test

def test
i = 100
j = 200
k = 300
return i, j, k
end

var = test
puts var

UNIT-6 RUBY 27
Variable Number of Parameters

def sample (*test)


puts "The number of parameters is #{test.length}"
for i in 0...test.length
puts "The parameters are #{test[i]}"
end
end

sample "Zara", "6", "F"


sample "Mac", "36", "M", "MCA"

UNIT-6 RUBY 28
Ruby - Iterators
Iterators are nothing but methods supported by collections. Objects that store a
group of data members are called collections. In Ruby, arrays and hashes can be
termed collections.
Ruby each Iterator
The each iterator returns all the elements of an array or a hash.

collection.each do |variable|
code
end
ary = [1,2,3,4,5]
ary.each do |i|
puts i
end

Ruby Step Iterator


A step iterator is used to iterate while skipping over a range.
(10..50).step(5) do |n|
puts n
end
UNIT-6 RUBY 29
Ruby Times Iterator
A loop is executed specified number of times by the times iterator. Loop will start
from zero till one less than specified number.

x.times do |variable|
code...
end

5.times do |n|
puts n
end

Ruby Upto and Downto Iterators


An upto iterator iterates from number x to number y.

x.upto(y) do |variable|
code
end
1.upto(5) do |n|
puts n
end
UNIT-6 RUBY 30
Ruby - Classes and Objects

Ruby is a pure object-oriented language and everything appears to Ruby as an


object.
Every value in Ruby is an object, even the most primitive things: strings, numbers
and even true and false.
Even a class itself is an object that is an instance of the Class class.

Ruby Class Definition

A class definition starts with the keyword class followed by the class name and is
delimited with an end.

class Box
code
End

UNIT-6 RUBY 31
Define Ruby Objects
A class provides the blueprints for objects, so basically an object is created from a
class. We declare objects of a class using new keyword.

box1 = Box.new
box2 = Box.new

The initialize Method


The initialize method is a standard Ruby class method and works almost same
way as constructor works in other object oriented programming languages. The
initialize method is useful when you want to initialize some class variables at the
time of object creation. This method may take a list of parameters and like any
other ruby method it would be preceded by def keyword

class Box
def initialize(w,h)
@width, @height = w, h
end
end

UNIT-6 RUBY 32
The accessor & setter Methods
To make the variables available from outside the class, they must be defined within
accessor methods, these accessor methods are also known as a getter methods
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# accessor methods
def printWidth
@width
end
def printHeight
@height
end
end
# create an object
box = Box.new(10, 20)
# use accessor methods
x = box.printWidth()
y = box.printHeight()
puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"
UNIT-6 RUBY 33
Similar to accessor methods, which are used to access the value of the variables,
Ruby provides a way to set the values of those variables from outside of the class
using setter methods.

class Box
def initialize(w,h)
@width, @height = w, h
end
# accessor or getter methods
def getWidth
@width
end
def getHeight
@height
end
# setter methods
def setWidth=(value)
@width = value
end
def setHeight=(value)
@height = value
end
End

UNIT-6 RUBY 34
# create an object
box = Box.new(10, 20)

# use setter methods


box.setWidth = 30
box.setHeight = 50

# use accessor methods


x = box.getWidth()
y = box.getHeight()

puts "Width of the box is : #{x}"


puts "Height of the box is : #{y}"

UNIT-6 RUBY 35
Access Control

 Ruby gives you three levels of protection at instance methods level, which
may be public, private, or protected.
 Ruby does not apply any access control over instance and class variables.

Public Methods − Public methods can be called by anyone. Methods are public
by default except for initialize, which is always private.

Private Methods − Private methods cannot be accessed, or even viewed from


outside the class. Only the class methods can access private members.

Protected Methods − A protected method can be invoked only by objects of the


defining class and its subclasses. Access is kept within the family.

UNIT-6 RUBY 36
Inheriatnce

 Inheritance allows the programmer to inherit the characteristics of one class


into another class.
 Inheritance provides the concept of “reusability”.
 Ruby supports only single class inheritance, it does not support multiple class
inheritance but it supports mixins.
 The mixins are designed to implement multiple inheritances in Ruby, but it
only inherits the interface part.
 Super class:The class whose characteristics are inherited is known as a
superclass or base class or parent class.
 Sub class:The class which is derived from another class is known as a
subclass or derived class or child class. You can also add its own objects,
methods in addition to base class methods and objects etc.

subclass_name < superclass_name


class B < A
end

UNIT-6 RUBY 37
Method Overriding
 In method overriding, subclass and superclass contain the same method’s
name, but performing different tasks or we can say that one method overrides
another method.
 If superclass contains a method and subclass also contain same method name
then subclass method will get executed.
super
A super method is defined by super keyword. Whenever you want to call parent
class method of the same name so you can simply write super or super().
Freezing Objects
 The freeze method in Object allows us to turning an object into a constant.
 Any object can be frozen by invoking Object.freeze.
 A frozen object may not be modified: you can't change its instance variables.

box.freeze
box
box = Box.new(10,
= Bo x.new(10, 20)20)
box.freeze

UNIT-6 RUBY 38
RUBY – Regular Expressions

• A regular expression is also spelled as regexp which holds a regular


expression, used to match a pattern against strings.
• In Ruby, a pattern is written between forward slash characters. They describe
the content of a string. Ruby regular expression is more similar to Perl regular
expression.

Advantages of Pattern Matching:

• You can test a string to see whether it matches a pattern.


• You can extract from a string the sections that match all or part of a pattern.
• You can change the string, replacing parts that match a pattern.

• The most common is to write regular expression is between forward slashes


/string/

UNIT-6 RUBY 39
=∽ and #match operators

The pattern matching is achieved by using =∽ and #match operators.

=∽

print /Hello/ =~ “Hello World”

If a match is found, the operator returns index of first match otherwise nil.

#match

This operator returns a MatchData object on matching otherwise nil.

print /Hello/.match(“Hello World”)

UNIT-6 RUBY 40

You might also like