You are on page 1of 164

SYLLABUS

3161611
Advanced Web Programming
-

Examination Marks
Credits Total Mark
Theor Marks Practical Marks
C
PA (M) ESE (V) PA ()
FSE E)
70 30 30 20
4 150

CSSS
1. Refreshing Java Script and
CSS syntax. benefits. Responsive design. Bootstrap introduction, Java script syntax, Java script inbuilt ohiccts ror

handling and event handing. DOM. Asynchronous Programming. (Chapter 1) -

2. Introduction to Angular JS

Basics and Symtax of Angular JS. Features, Advantages, Application Structure, Basics of routes and navigation, MVC
with Angular JS. Services. (Chapter - 2)

3. Angular JS in Details

Modules. Directives. Routes. Angular JS Forms and Validations, Data binding, Creating single page website using
AngularJS. (Cbapter-3)

4. Introduction to Node JS

Setup Node JS Environment, Package Manager, Features, Console Object, Concept o f Callbacks. (Chapter - 4)

5. Node JS in details

Evenis and Event Loop. timers. Eror Handling, Buffers, Streams, Work with File System, Networking with Noue

ODP and HTTP clients and servers), Web Module, Debugging, Node JS REST API, Sessions and CooNIC
Design pattems, caching. scalability. (Chapter -5)
6. Database Programming with Node JS
and MongoDB
Basics of r,
MongoDB, Data types, Connect Node JS with data (Insert, Find,
Delete, Update) using Node
MongoDB, Operations on ucry
IS. (Chapter -6)

(iv)
TABLE OF CONTENTS
Chapter 1 Refreshing Java Script and CSS (1 1) to (1 114)
Part: CSS and Bootstrap
1.1 Introduction to CSS ***
. 1-2

1.1.1 Benefts of CSS .1-2

1.2 CSS Syntax and Structure.. 1-2


1.3 Location of Styles.. .. 1-5
1.3.1 Inline Style Sheet.
.1-5
1.3.2 Document Leve! Style Sheet. .1-6
1.3.3 External Stylesheet. .1-8

1.4 Selectors.. 1-10

1.4.1 Simple Selector Form.. .1-10

1.4.2 Class Selectors. . 1 - 11

1.4.3 Generic Selectors .1- 14


*****

1.4.4 Id Selectors ******************-********* . 1 15


1.4.5 Universal Selectors ... 1- 16
1.4.6 Attribute Selector ****"******** **** 1-17

1.4.7 Contextual Selector . ***** *********** ************************* -*** * *** ... 1 - 18

1.5 Background. .1-19

1.6Color and Color Properties. .1-22

1.6.1 Color Groups.. .. 1 -22

1.6.2 Color Properties. ***************************** ...1 -23

1.7 Manipulating Texts and Fonts . . .1-24


1.7.1 Font Families...
******************** ***
*** .1-24

1.7.2 Font Sizes. **** ***


...1-25
1.7.3 Font Variants. ********
*** ... 1- 26

1.7.4 Font Styles ******************** **


****** 1- 27

(v)
1.7.5 Font Weights. . 28
1.7.6 Font Shorthands.. .l 29
1.7.7Text Decoration. 30

1.7.8 Alignment of Text. 31

.133
1.8 Lists.
1.9 Responsive Design... T-39

1.9.1 Setting Viewports.


.1-40
.141
1.9.2 Media Queries...
. . . 1-43
1.10 Bootstrap Introduction.
.1-46
1.10.1 Grid System..
...1-49
1.10.2 Typography..
1 55
1.10.3 Tables..
.
.1-56
1.10.4 Images..
....1- 57
1.10.5 Button..
. . . 1 - 59

1.10.6 Form...

Part II:JavaScript
. . 1 64
1.11 Java Script Synta
.... 1 - 67

1.12 Java Script Inbuilt Objects


. . 1 67
* * * * * * .

1.12.1 Math Objects.. .... 1 - 68

1.12.2 Number Objects.


l - 69
..
1.12.3 Date Objects...
. . . 1 - 71

1.12.4 Boolean Objects.


..1-72
1.12.5 String Objects...
..1-75

1.12.6 Object Creation and Modificatior


1 -
77
1.13 DOM..
* * * * * * o.o.*
. .

*******

.1-77
1.13.1 Definition of DOM. * * *

***"
.1-77
1.13.2 DOM Tree..
1.13.3 Using DOM Methods.. . . 1 78
*************************.

1.13.3.1 Accessing Elements 1 - 79


using DOM *********************r *************'''*******"
. . . .

(vi)
1.13.3.2 Modifying Elements using DOM. ************************ ...1 80

.1-85
1.14 Event Handling..
1.14.1 Handling Events from the Body Elements. ... 1 -90

1.15 Error Handling. 1-91

1 - 95
1.16 Validators...
. . 1-105
1.17 Asynchronous Programming.
1.17.1 Introduction to AJAX.. .
. . 1 105

.1-105
1.17.2 Architecture..
. 1-107
1.17.3 XMLHttpRequest Object.
( 2 - 1 )to (2 - 18)
Chapter2 Introduction to Angular JS
2.1 Basics of Angular JS. ***
... 2-2

.2 2
2.2 Features..

2.3 Advantages and Disadvantages. ...2 -2


.2 3
2.4 Application Structure.
...2-5
2.5 MVC with Angular JS.
2.6 Basics of Routes and Navigation. .2 -6

2.7 Expression.... .2-7

2-9
2.8 Controller . .

. 2 -

15
2.9 Scope..

2.10 Services.. . . 2 16

Chapter - 3 Angular JS in Details 3- 1) to (3 26)


... 3 - 2
3.1 Directives.
... 3-6
3.2 Modules..
... 3 - 8
3.3 Routes . .
.... 3 - 13
3.4 Angular JS Forms and Validations..
. . 3 19
3.5 Data Binding ***.

3 - 23
3.6 Creating Single Page Website using Angular JS

(vii)
Chapter 4
Introduction to Node JS
(4 1) to (4 12)
Environment
JS
. .

4.1 Setup Node . 4-2


4.2 Package Manager...
4-4
4.3 Features..
4 -7
4.4 Console Object.
** .4 8
4.5 Concept of Callbacks..
. . 4 10

Node JS in Details
Chapter-5 (5- 1) to (5 66)
5.1 Events and Event Loop..
5 -2
5.1.1 Introduction to Events..
5 -2
5.1.2 Concept of Event Loop..
54
5.2 Timers.
6
5.3 Error Handling...
5 - 100

5.4 Buffers, Streams, Work with File System...


10
5.4.1 What is Buffer ?.
5 10
5.4.2 Concept of Stream.. . .. 12
5.4.3 File System.. 5 15

5.5 Networking with Node.. ... 5-20


5.6 Web Module ... ..5-29

5.7 Debugging. ... 5-33

5.8 Express in NodeJS. .. 5-36

5.9 Node JS REST .5-39


API..
5.10Sessions and Cookies. ... 5 - 50

5.10.1 Sessions ***


. . 5 50D
-

. . . 5 - 54
5.10.2 Cookie.
5 59
5.11 Design Patterns... ***
. . . . .
-

..5-64
5.12 Caching
and Scalability.....

(viii)
Chapter 6 Database Programming with Node JS and MongoDB

(6-1) to (6 -34)
6.1 Basics of MongoDB.... .... 6 2

6.2 Data Types. ** ..6-4

6.3 MongoDB Installation... 6 -4

6.4 Database Commands... . . 6 12

. . . 6 - 22
6.5 Connect Node IS with MongoDB...

6.6 Operations on Data using Node JS. .. 6 23

Solved Model Question Paper (M - 1) to (M - 2)

(ix)
Notes

(x)
1 Refreshing Java Script
and CSS

Syllabus
CSS syntax, benefits, Responsive design, Bootstrap introduction, Java script syntax, Java script
inbuilt objects, Error handling and event handling, DOM, Asynchronous Programming

Contents
Part 1: CSS and Bootstrap

1.1 Introduction to CSS

1.2 CSS Syntax and Structure

1.3 Location of Styles


1.4 Selectors
1.5 Background
1.6 Color and Color Properties
1.7 Manipulating Texts and Fonts
1.8 Lists
1.9 Responsive Design
1.10 Bootstrap Introduction

Part I: JavaScript
1.11 Java Script Syntax
1.12 Java Script Inbuilt Objects
1.13 DOM
1.14 Event Handling
1.15 Error Handling
1.16 Validators
1.17 Asynchronous Programming

(1-1)
Advanced Web Programming
1-2 Refreshing Java Script and CSS

Part:CSS and Bootstrap

1.1 Introduction to CSS


The CSS stands for Cascading Style Sheet.
.The Cascading Style Sheet is a markup language used in the web document for
presentation purpose.
to separate out the web content from the weh
The primary intension of CSS
was

presentation.
.Various elements such as text, font and color are used in CSS for presentation
can be applied to bring the styles in the web
purpose. Thus CSS specification
document.

1.1.1 Benefits of CSS


Following are important benefits of CSS:
(1) Improved Control Over Formatting : The web page developer (called as web

author) have better control over formatting of web contents.


(2) Improved Site Maintainability : It becomes easy to maintain the site because the

formatting is centralized into one CSS file.


(3) Improved Accessibility: The CSS driven sites are more accessible and give the
user significantdly enriched experience of accessibility of the web page.
(4) Improved Download Speed: As all the formatting is centralized into one CSS

file, all presentation will be quicker to download.


(5) Output Flexibility: CSS can be used to -adopt a page for different output media.
This approach to CSS page design is often referred to as responsive design.

Review Question
1. What is CSS? Enlist the benefitsof CSS.

1.2 CSS Syntax and Structure


The style specification is specified differently for each diferent level. For instance
For inline cascading style sheets the style appears in side the tag for defining tne
value.
<p style="font-size: 30pt font-family:Script>

TECHNICAL PUBLICATIONS-An up thrust for knowledge


1-3 Refreshing Java Script and CSS
Advanced WebProgramming
For the document cascading style sheet the style specification appear as the content
of a style element within the header of a document.
<style type="text/css'>
h1 Selector

font-family:Arial;
tolor:green
</style>
Value
Property
The type attribute tells the browser that what it is reading is text which is affected by
the Cascading Style Sheet. The type specification is necessary because there is one more
specification used in JavaScript.
The External style sheet makes use of style specification in the same manner as in
document cascading style sheet.
The most commonly used CSS properties are enlisted in the following table -

Property 1ype Property


Fonts font

font-family
font-size

font-style
font-weight
@font-face
Text
letter-spaang
line-height
text-align
text-decoration
text-indent
Colorand background background
background-color
background-image
background-position
background-repeat
color

TECHNICAL PUBLICATIONS-An up thrust for knowledge


1-4
Advanced Web Programming
Refreshing Java Script and
Borders border CSs
border-color

border-width

border-style
border-top
border-top-color
border-top-width
Spacing padding
padding-bottom, padding-left, padding-
right,

padding-top
margin
margin-bottom, margin-left, margin-
right,
margin-top
Sizing height
max-height
max-width

min-height
min-width

width

Layout bottom, left, right, top


lear

display
float

overflow

position
visibility
Z-index

TECHNICAL PUBLICATIONS- An up thrust for knowledge


Advanced WebProgramming
-
1-5 Refreshing Java Script and CSS

Lists list-style
list-style-image
list-style-type

1.3 Location of Styles


There are three levels of cascading style sheets-
Inline style sheet
Document level style sheet
External level style sheet

1.3.1 Inline Style Sheet


The inline cascading style sheet is a kind of style sheet in which the styles can be
applied to HTMLtags.This tag can be applied using following rule-
Tag

property: value

For example:
<p style="font-family: Arial;color.red">
Here for the tag p two properties are used such as font-family and color and those are
associated with the values such Arial and red
as
respectively.
Note that if we want to use more than one property then have to
we use separator
such as semicolon. In the following HTML document we have used cascading style
sheet-

HTML Document [InlineStyle.html


<IDOCTYPE html >
<html>
<head>
<title>Inline Cascading Style Sheet</title>
</head
<body>
<p>This is simple text </p>
sp style="ont-size: 30pt font-family:Script">This text is different </p>
p style-"font-size: 40pt;color:#f0000">This text is colored. </p>
</body>
</html>

TECHNICAL PUBLICATIONS-An up thrust for knowledge


Advanced Web Programming
1-6 Refreshing Java Script and
CSs
Script Explanation
sheets created.
body section the style
are

1) In this document, in the


sentence This is simplat
first of all we have displayed simple le text.
a
2) In this section
There is no style for this sentence.
is set to the size
3) In the next line, applied style in which font-size
we have oa
30
name "Script"
point and font-family is set by the font
4) Then colored text will be displayed by color:#ffo000". The first two digitss ff
4)
denote the red color, there is no green and blue color as the values next to ff are

00. Hence the text will be displayed in red.


This can be very well illustrated in output.

Output
Sheet Windows Internet Explorer
Inline Cascading Stye
e DHTMLExamplesunlineStyle.htmi - | x | | ToggieEN Cust
Favortes S Suggested Sites ej Get More Add-ons
Inline Casading Style Sheet 5 Page Safety

This is simple text

Jhis art i dierend

This text is colored.


Computer | Protected Mode oH
100%

1.3.2 Document Level Style Sheet


.This type style sheet appears only in the head section and in the body section newly
defined Selector tags are used with the actual contents.

.For example : In the following HIML script we have defined


h1, h2, h3 and p
selectors. For each of these selectors difterent
property and values are set. Such
setting will help us to represent our web page in some decorative form.

T h e most important thing while writing document level style sheet is that we
hald mention the style type="textucss in the head section.
By this the browser
will come to know that the program is
making use of
cascading style sheetet.

TECHNICAL PUBLICATIONS-An up thrust for knowiedge


Advanced Web Programming 1-7 Refreshing Java Script and CSS

HTML Document [DocLevelCSS.html]


<IDOCTYPE html>
<html>
<head>

<title>Document Level style sheet </title>


<style type="text/css">
h1

font-familyArial;
color:green

h2

font-family:Arial;
color:red;
left:20px

h3

font-family:arial;
color:blue;

font-size:14pt;
font-family:verdana

</style
</head>
<hody>
<h1>
center>
This page is created using Document
Level Style Sheet
/center>
</h1>
<h2>
This line is aligned left and red colored.
</h2>
p>
The embedded style sheet is the most
commonly used style sheet.
This paragraph is written in Verdana font
with font size of 14.
</p>
<h3>
This is blue <a
a
href="colorname.html">colored</a> line.

TECHNICAL PUBLICATIONS An up thrust for knowledge


1 -8 Refreshing Java
Advanced Web Programming Script and CS
CSS
</h3
</body>
</html>
Output
inet tye znee Windws Internet ploe
eOocument
e DHTML Eamples DoclnetSS Mm PTapoes Cunts P
Grt Mcre Add-os
#Document Level style thee L Page Safety

This page is created using Document Level


Style Sheet

This line is aligned left and red colored.

The embedded style sheet Is the most commonly used style sheet. Thls
is written in Verdana font with font size of 14.
paragraph
This Is a blue colored line.

AComputer | Protected Mode Of


4100%

Script Explanation
1) In above program, we have defined all the selectors in the head sections onl.
y
And these HTML elements are then used along with the web page contents.
2) The setting defined in the selectors will affect the web page contents. For

example we have defined the selector h2 as


h2 Selector

Aont-family:Arial;
color:red;
Property left:20px

Value

and then in the body section we have written-


ch2> This line is aligned left and red colored. </h2>
or
3) Now as h2 defines font to be "Arial" with color as "red" having left alignment
will be
20 pixels, the sentence "This line is aligned left and red colored."
displayed in Arial font, which is red colored and aligned from left by 20 pxes
Surely we can see this effect on our web browser.

1.3.3 External Stylesheet


ents i
Sometimes we need to
apply particular style to more than one web
such cases external style sheets can be used.

TECHNICAL PUBLICATIONs-An up thrust for knowledge


Advanced Web Programming 1-9
Refreshing Java Script and CSS
The central idea in this type of style sheet is that the desired style is stored in one
css file. And the name of that file has to be mentioned in our web pages.
Then the styles defined in .css file will be applied to all these web pages.
Here is a sample program in which external style sheet is used.
Step 1: Create an HTML document
HTML Document[ExtcSS.htmi]
<IDOCTYPE html>
<html>
<head>
<link rel="stylesheet type="text/css' href='ex1.css' />
</head>

<body
<h1 class="special"> <center> This page is created using External Style
Sheet </center> </h1>
<h2>
This line is aligned left and red colored.
</h2>
<p>
The External style sheet is the compact representation of Cascading Style Sheets.
This paragraph is written in Monotype Corsiva font with font size of 14.
</p>
<h3>
This is a blue <a href="colorname.html">colored</a line.
</h3
</body
s/html>
Step 2 Create a css file which contains the styles that can be applied to different HTML
elements present in the above HTML document.
The cascading style sheet ex1.css can be
<l- The file name ex1.css and can be opened in notepad.-> Output
DXHTMLEampleslErCSShtml -Windows Ihernet Esplorer x
h1
e ouHTMEamplesEeSbtmi x P To99ie5NCust P -
Favortes eSuggested Sites e Get More Add-ans
font-family:Arial DHTM_ bxamplesiExtCSS.htrnl Page Sefety

h2 This page is created using External Style Sheet

This line is aligned left and red colored.

font-family:times new roman; This par-graph


Etemalstyle shest is tha compact reprasentation of Cascading Style Sheets
is
Ike
wntten tn Monotype Corsmufont uiuh font size of 14.
color:red:
left:20px This is a blue colored line.

h3
Computer | Protected Mode: 0ff a 100

TECHNICAL PUBLICATIONS-An up thrust for knowledge


Advanced Web Programming 1 10 Refreshing Java Script and
CSs

font-family:arial;
colorblue;

font-size:14pt;
font-family:Monotype Corsiva

Script Explanation
When we want to link the external style sheet then we have to use <link>
tag which is
to be written in the head section.

link tells the browser some file must be linked to the page.

rel=stylesheet tells the browser that this linked thing a style sheet.
href=" "denotes the path name of style sheet file.

type="text/css" tells the browser that what it is reading is text which is affected by
the cascading style sheet.

1.4 Selectors
1.4.1 Simple Selector Form
The simple selector form is a single element to which the property and value is
applied.
We can also apply
property and value to group of elements.
Following is an illustration for simple selector form.

HTML Document[SimpleSel.html]
<IDOCTYPE html>
<html
<head>
<title> Simple Selector Form</title>
style type="text/css"'>
h1

font-family:Arial;
color:green;

TECHNICAL PUBLICATIONS-An up thrust for knowledge


Advanced Web Programming 1-11 Refreshing Java Script and CSS
h2,h3
We can apply style to
more than one selector
font-family:Monotype Corsiva;
color:red;
font-size: 28pt

</style>
</head>
<hody>
<h1>India is My Country</h1>
<h2> All the Indians my brothers and sisters </h33>
are

<h3>I love my country</h3>


</body>
</html>

Output
Simple Selector Form - Windows Internet Explorer

e D:XHTML_ExamplesSimpleselhtni
x P agieEN Cu
Favortes eSuggested Sitez e t MereAdd-ons
Simple Selector Fom Pe Satey
India is My Country

All the Indians are my brothers and sisters


I love my countr
Done RComputer | Protected Mode Of 100%

Similarly the style can also be applied to the elements at specific positions.

For example
body bp (font-size:18pt:)
Note that there are more than one element to which the style is applied and these
elements are
separated by the white spaces.
1.4.2 Class Selectors
Using class selector we can assign different styles to the same element.
These different styles appear on different occurrences of that element.

TECHNICAL PUBLICATIONS- An up thrust for knowledge


Advanced Web Programming 1- 12 Refreshing Java Script and CSs
For example
HTML Document[ClassSel.htm]
<IDOCTYPE html>
shtml>

<head
stitle>Class Selector Form</title>
style type="text/css'>
h1.RedText

font-family:Monotype Corsiva;
color:red;
font-size: 14pt;

h1.BlueText

font-family:Arial;
color:blue;
font-size: 10pt;

s/style>
</head>
<body>
<h1 class ="RedText">India is My Country</h1>
ch1 class="BlueText"> All the Indians are my brothers and sisters </h1
<h3>I love my country</h3>
</body
/html>

Output
éClass Selector Form- Windows Internet Explorer

E DUHTMLEamples ClassSel.html xToggieEN Cust


sFavorites e Suggested Sitese Get More Add-ons
é Class Selector Form
Page Safety
India is My Country
All the Indians are my brothers and sisters

I love my country

Computer |Protected Mode Off 100%

TECHNICAL PUBLICATIONS- An up thrust for knowledge


Advanced Web Programming 1- 13 Refreshing Java Script and CSS

Script Explanation
Note that in above given script we have used two different classes for the element h1.
One class selector is for displaying the string in red color and another is for displaying the
string in blue color. This definition is given in the head section. In the body section these
class names appear in double quotes inside the h1 tag.
Example 1.4.1 Create a HTML document tht displays a table of basketball scores at nationa
games in which the team names have their respective team colors. The score of the
leading/wining team should appear larger and in different font than the losing team. Use
CSS.

Solution: Football.html
<IDOCTYPE html>

<html
<head>

<style type="text/css">
tr.one

background-color:pink;
color:blue;
Output
tr.two Mozills Firefax
Eile Edit iew Higtory Bookmarks Iools Help
font-family:cursive; File//d:/kakinada_..nology/Football.htmt
background-color:black; file////1 AVG P
color:yellow;
Video
font-size:50px;
Team Score

ABC
tr.three

background-color:green;
color:white;
KYZ10|
POR
s/style>
</head>
body>
<table border="3">
<th>Team</th>
<th> Score</th>
<tr class="one"> <td>ABC</td> <td>7</td>
</tr>
Str class="'two"> <td>XYZ</td> <td>10</td>

An up thrust for knowledge


TECHNICAL PUBLICATIONS
Advanced Web Programming
1- 14 Refreshing Java Script and Cs

</tr>
/td><td>5</td>
<tr class="three"><td>POR<
</tr>

</body>
s/html>

1.4.3 Generic Selectors


fornm.
We define the class in generalised
I n the sense. that particular class can be applied to any tag.

Here is the HTML doument


which makes use of such generic selector.
HTML Document [ClassSel1.htm]
<IDOCTYPE html>
<html>

<head
stitle>Generic Class Selector Form</title>

style type ="text/css">

RedText
{
font-family.Monotype Corsiva;
colorred:

</style>

</head>
<body
<center
<h1> Tongue Twister</h1>
</center>
<h2 class="RedText'>
She sells sea shells on the sea shore.
</h2>
<h3 class="RedText'>
The shells she sells are sea shells, Im sure
</h3>
<h4 class"RedText">
And if she sells sea shells on the sea shore,
</h4>
p class="RedText">
Then I'm sure she sells seashore shells.
</p>
</body>
/html>

TECHNICAL PUBLICATIONS-An up thrust for knowledge


Advanced Web Programming 1-15 Refreshing Java Script and CSS

Output
Generc Cless Selector Form Windows Intermet Explorer

Fvortes eSggeited Sitese Gt More Ad-ons


Generie Cies Selector Fom

Tongue Twister

She sells sea shells on the sea shore

The skells shs sells are ses shalls, I'm sru

Anl if she sull sa shalla n the sos hore.

Then im rur she selia soashore hels

100%
Comptr Potected Mede O
Note that the class selector must be preceded by a dot operator.

1.4.4 Id Selectors
only difference between the
T h e id selector is similar to the class selector but the
two isthat class selector can be applied to more than one elements where as using
the id selector the style can be aPplied to the one specitic element.
.Thesyntax of using id selector is as follows
#name_of id {property:value ist:}
makes of id selector
Following HTML document use

HTML Document[ldSel.htm!]
IDOCTYPE htm>

<html>
<head>
<title>id Selector</title>

style type ="text/css" >

#top

font-family:Monotype Corsiva;

color:blue;
font-size:16pt:

</style>
</head
<body>

TECHNICAL PUBLICATIONS
-An up thrust for knowledge
1-16 Refreshing Java Script and CSS
Advanced Web Programming

<div id="top">
educated mind to be able to
It is the mark of an
it.
entertain a thought without accepting
</div>
<p>
-Aristotle
</p>
</body>
</html>

Output

i d Selector Windows Internet Eplorer

E D:HTML_EamplesUdsel.html 4 x|ToggleEN Cust


suggested Sites e Get More Add-ons
favorites
é d Selector Page Safety
It is the mark of an ediucated mind to be able to entertaina thought
without accepting 1t.

-Aristote

Computer | Protected Mode Of a 100%

1.4.5 Universal Selectors


This selector is denoted by * (asterisk). This selector can be applied to all the elements

in the document.

HTML Document[UniverSel.htm]
<IDOCTYPE html>
<html>
head>
<title>Universal Selector</title>
style type="text/css'>

color:green;

</style>
s/head
<body>
<h2> Famous Proverbs </h2>

TECHNICAL PUBLICATIONS-An up thrust for knowledge


Advanced Web Programming 1- 17 Refreshing Java Script and CSS

<hr/>
<ul type="'disc">
<li>A friend in need is a friend indeed</li>
<li>Cleanliness is next to Godliness </lí>

<li> All is fair in love and war</li>


<li>An apple a day keeps the doctor away</li>
<li>God helps them who help themselves</li>

<br/><br/>
<em>
-From My Collection.

</em>
</body>
</html>
Output
Universal Selector - Windows Internet Explorer

e D:XHTML_ExamplesUniverSel.html , xTogge£N Cust P

Favorites e Suggested Sites e Get More Add-ons


Universal Selector - Page Safety

Famous Proverbs

A friend in need is a friend indeed


Cleanliness is nextto Godliness
All is fair in love and war
An apple a day keeps the doctor away
God heps them who hep themselves

From My Collection.

Computer | Protected Mode Off 100%

As we have defined the universal selector that sets the green color. Hence the text that
is appearing on the above web page is in green color.

1.4.6 Attribute Selector


CSS allows authors to specify rules that match elements which have certain
attributes defined in the source document.
The syntax is
latt Match when the element sets the "att' attribute, whatever the value ofthe attribute.
att=val]- Match when the element's "att' attribute value is exactly 'val"

TECHNICAL PUBLICATIONs-An up thrust for knowledge


Advanced Web Programming
1- 18 Refreshing Java Script and CSss
In the following example al the <a> elements get selected with
get
Example :
a
target
attribute.
<IDOCTYPE html>
<html>
<head>

<style>
altarget) {
background-color: red;

</style>
</head>
<body>
a RED background: </p>
sp>The links with a target attribute gets
href="https://www.google.com'>Google</a>
</h1>
<h1> <a
target="_blank'>Facebook</a> </h2>
<h2><a href="http://www.facebook.com"

</body>
s/html>

Output

/d:/test.htm x+
)> C file:///d:/test.html . »E

The links with a target attribute gets a RED background:

Google
Facebook

1.4.7 Contextual Selector


for different parts
"Contextual selectors" in CSS allow you to specify different styles
of your document.
dent
You can assign styles directly to specific HTML tags, or you can create indepenue

classes and assign them to tags in the HTML.

TECHNICAL PUBLICATIONS®- An up thrust tor knowledgo


Advanced Web Programming 1-19 Refreshing Java Script and CSS
For example -

<IDOCTYPE html>
<html>
<head>
style
pb{
font-family:Times, serif;/* Font family/
font-weight: bold; /' heavy faced type"/
color: blue; /* blue colour of the text "/

</style>
</head>
<body>
<div> <b>This line is in bold face font </b> </div>
<p> <b>This line is in bold face with the color of the text blue </b> </p>
<p> Good Bye</p>
</body>
</html>

Output

/d:/test.html + x
C O file:///d:/test.html . » E
This line is in bold face font

This line is in bold face with the color of the tert - blue

Good Bye

1.5 Background
Using background-image property an image can be set as background.

HTML Document[Backimg.htm/
<IDOCTYPE html>
<html>
<head>

TECHNICAL PUBLICATIONS-An up thrust for knowledge


Advanced Web Programming
1-20 Refreshing Java Script and CSs
<title>Background Image </title>
<style type="text/css'>
body {background-image:url(victoriafalls.jpg);

background-repeat:no-repeat; }
P

font-family:Arial;
font-size:20px

</style
</head
<body>
<center
<h2>Wonder of the World </h2>

</center>
<p
The Vicorial waterfall is one of the greatest waterfalls in the world.
It ies on the Zimbezi river which is between the border of Zambia and Zimbabwe.
The Victoria fall can be seen from 25 to 40 miles away.
The roaring of the water can be heard from a long distance.
The native people call it as "mosi-oa-tunya", that means "smoke thatthunders"
Victona falls was discovered by David Livingstone in 1855.
The falls were named in honor of Queen Victoria.
</p>
</body>
s/html>
Output
Faxkground n g Windows Interret Esplorer

e D0TL EanplerBackimg htm


4xPregg n¬u Cu P

e 93prstrs Sst e Ge More Add-ons


achgrcund nuge -Page Ssfcty

Wonder of the World


ha Vicorialwaterfall is one of the greatest waterfalls l i.d. It
es or ulE 4imbezi river which is between the border of nd
we The Victorna fall can be seen from 25 to 40 mles away. The
of the water can be heard from a long distance The nath
alit as mosi-oa-tunya, that means "smoke that thunders".
falis was discovered by David Livingstone in 1855. The fails
medin honor of Queen Victoria

Done Canpute | Pratected Mode Off


100%

TECHNICAL PUBLICATIONS- An up thrust for knowiedge


Advanced Web Programming 1-21 Refreshing Java Script and CSS

It is expected that the foreground text over the image should be visible. That means the
color of the background image must not be the same as the color of the text written over
it.

Background-repeat property
The background-image property sets the background image with repetition. If
we want to control the repetition of the image then we must set the background-
repeat property. The values of this property could be no-repeat, repeat-x, repeat-
y or repeat(default). The repeat-x means the background image gets repeated
over the x-axis(horizontally) and repeat-y means the background image gets
repeated over the y-axis(vertically).

Background-position property
Various values for back-ground position property could be top, bottom, left and
right
Example 1.5.1 Write a CSS rule that places a background image halfway down the page, tilting
it horizontally. The image should remain in place when the use scrolls up or down.
Solution
<IDOCTYPE html>
<html>
<head>
<style type="text/css'>
P

font-size:40px;
color:magenta;

body

background-image:url(baby jpg):
background-repeat.repeat-x;
background-attachment:fixed;

/style>
</head>
<body>
<p>
Twinkle, tuwinkle, little star, How I wonder what you are.Up above the world so high, Like a diamond
in the sky.Twinkle, twinkle, little star, How I wonder what you arel

TECHNICAL PUBLICATIONSAn up thrust for knowledge


1-22 Refreshing Java Scnpt and CSs
Advanced Web Programming
When the blazing is gone, When there's nothing
sun
he shines upon,Then you show your little lin.t.
Twinkle, twinkle, through the night.
are!
HowI wonder what you
Twinkle, twinkle, little star, For you never close your eyes
curtains often peep
In the dark blue sky so deep Through my

Til the morning sun does rise


are Twinkle, twinkle, little star How I nder
wonde
I wonder what you
Twinkle, twinkle, little star How
what you are

/p>
</body
/html
1.6 Color and Color Properties
Different browsers have different ability
to deal with the colors. In
the next subsequent
sections we will discuss how to use
colors using CSS.

1.6.1 Color Groups


three groups of colors. Those given below
-

are as
There are

This is the smallest group of colors. In this group there are 16 colors. These are
1
named colors. The colors in this group are enlisted as follows -

Sr.No. Color Name Hexadecimal Value

black 000000

red FFOO00

lime 00FFO0

blue 0000FF

5 yellow FFFFO0

b fuchsia FFOOFF

aqua 0OFFFF

8 white FFFFFF

9 silver COCOCO

10 8ray 808080
11 maroon 800000
12
purple 800080

TECHNICAL PUBLICATIONS An up thrust


for knowledge
Advanced Web Programming 1-23 Refreshing Java Script and CSS

13 green 008000

olive 808000

15 navy 000080

16 teal 008080

These colors get displayed as it is on the web browsers. And all the web browsers
support these colors.

2. There is a set of 216 colors which is called web palette. The elements of such
colors are red, green and blue. The values of these elements can be 00, 33, 66, 99,
CC and FF.

3. There are 16 millions colors. These are 24-bit colors.


Syntax: Color: colorname:

1.6.2 Color Properties


Using color property we can set the foreground color and using background-color the
background color can be set. The use of these properties is shown in XHTML document.

HTML Document[colorProperties.htmi]
<IDOCTYPE html>
<html>
<head>
<title>Color Properties</titlee>
style type="text/css">
h1

font-family: Arial;
color:green;
background-color:yellow;

</style>
/head>
<body>
center>
sh1>This is a green text with yellow background</h1>
</center>
</body>
</html>

TECHNICAL PUBLICATIONS An up thrust for knowledge


1-24 freshing Java ript and
Advanced Web Programming CSS
Output
Explorer
Cokor Properties Windows Intemet
oHTM_Ehamples\color |X ToggieEN Cush
e

e uggested stes
Get More Add-ons
favortes
Page
éColor Properbes

This is a green text with


yellow background

Protected Mode Off


100%
Computer |

1.7 Manipulating Texts and Fonts


The font properties can be setting
different types of fonts, styles and sizes.

1.7.1 Font Families


The font-family denotes different types of fonts such as Arial, Times New Roman
of generic fonts
Script, monospace and so on. Following are some examples

Generic Font Name Example

sans-serif Arial, Helvetica, Futura

Cursive
Zapf-chancery

fantasy Critter, Cottonwood

monospace Courier, Prestige

serif Times New Roman, Garamond

Let us see
usage of font-family property in HTML document.

HTML Document[FontFamily.html]
<IDOCTYPE html>
<html>
<head
stitle>Font Family Demo </title>
style type="text/css'>
h1

TECHNICAL PUBLICATIONS-An up thrust for


knowledge
Advanced Web Programming 1-25 Refreshing Java Script and CSS

Output
Font Fam.ly Demo - Wirdows Internet Expior
font-family:Arial;
e D HTM_Ermples Fortf amily Htm!

Fwortes Gt
More Add-ons
h2
Fot Family Demo

font-family:script;
This text is in Arial
h3

This text is in Tmes New Roman


font-family:'Times New Roman';
T R i in fereeg

h4 Tbis text is in Garamosd

font-family:fantasy; Computer | Protected Mede Off 100%

h5

font-family:Garamond;

</style
</head>
<body>
<h1>This text is in Arial </h1>
<h2>This text is in script </h2>
<h3>This text is in Times New Roman</h3>
<h4> This text is in antasy</h4>
<h5> This text is in Garamond </h5>
</body>
</html>
If the font name has more than one word then the name should be enclosed by the
single quotes. Although quotes are not mandatory, it is a good practice to use quotes for
specifying the font name.

1.7.2 Font Sizes


This property is used to specify the size of the font. One can specify the font size in
ponts (pts), pixels (px) or in percentage (%). We can also specify the font size using the
relative values such as small, medium, large. Use of font size in such a way is relative.
And the disadvantage of using such relative sizes is that one cannot have the strict control
over the font-size. Different browsers may have different font size values.

In the following HTML document we will use the font-size property.

TECHNICAL PUBLICATIONS An up thrust for knowledge


Advanced Web Programming
1- 26
Refreshing Java Script and Cs
HTML Document[FontSize.htmi]

<IDOCTYPE html>

<html
head>
Output
<title>Font-Size Demo</title>
D HTM Lemples otsa m

style type="text/css Favoenes E Mcre Ldo-om

h1 Font See Deme

font-size:10pt, Programming the Web

h2 Programmingthe Web

font-size:20px;
Programming the Web
h3

font-size:Xx-large;

h4

font-size:250%,

</style>
</head>
<body
<h1>Programming the Web</h1>
ch2>Programming the Web</h2>
<h3>Programming the Web</h3>
<h4>Programming the Web</h4>
</body>
</html

1.7.3 Font Variants


The font variation can be achieved by making setting the font in upper case or inlower

case.

We use font-variant property for this


purpose.
Value
Meaning
normal The font can be displaved in normal form.

small-caps The font can be displayed in small capital letters.

TECHNICAL PUBLICATIONS An up thrust for knowiedge


Advanced Web Programming 1-27 Refreshing Java Script and CSS

HTML Document[FontVariant.html
IDOCTYPE html>
<html>
<head>
<title>Font-Variant Demo </title>
<style type="text/css"'>
h1

font-variant:small-caps;

</style>
</head>

<body>
<h1>Programming the Web</h1>
</body>
</html>

Output
Font-Variant Demo - Windows Internet Explorer

eDxHTML_EvamplesFontVariant.html x TggieEv Cust: P


Favorites e SuggestedStes e Get More Add-ons
Font-Variant Demo C Page Safety

PROGRAMMING THE WEB

Computer | Protected Mode Off A 100%

1.7.4 Font Styles


Various font styles are-
normal
italic

oblique
The illustration is as given below.
HTML Document[FontSt.html]
<IDOCTYPE html>
<html
<head>

TECHNICAL PUBLICATIONS"- An up thrust for knowledge


Advanced Web Programming 1-28 Refreshing Java Script and
stitle>Font-Style Demo</title>
CS
style type="text/css'>

h3.normal { font-style:normal;}
h3.italic { font-style:italic;}
h3.oblicque{ font-style oblique:)
</style>
</head>
<body>
<h3 class="nomal">Programming the Web</h3>
<h3 class="italic">Programming the Web</h3>
<h3 class="oblique'>Programming the Web</h3>

</body>
</html>
Output
Font-Styie Demo - Windows Intenet Explorer

DXHTML ExamplesFontSt.htm X Togg eEN Cuit P


Favortes Get More Add-ons
Font-Styie Demo Page Safety

Programming the Web

Programming the Web

Programming the Web

Computer | Protected Mode Of 100%

1.7.5 Font Weights


Various font styles are
Normal (by default)
Bold
Bolder
Lighter
The illustration is as
given below-
HTML Document[FontWt.html]
<IDOCTYPE html>
<html>
head>
<title>Font-Weight Demo</title>»
style type="text/css">

TECHNICAL PUBLICATIONS An up thrust for


knowledge
Advanced Web Programming 1-29 Refreshing Java Script and CSS
p.normal { font-weight:normal}
p.bold { font-weight:bold.}
p.bolder { font-weight:bolder;}
p.lighter (font-weight:lighter:)
</style>
</head>
<body>
the Web</p>
<p class="normal">Programming
the Web</p>
<p class="bold"> Programming
the Web</p>
<p class="lighter'>Programning
the Web</p>
<p class="bolder">Programming
</body>
</html>

Output

Font Weight Demo Windows Internet Explorer


e D XHTML_Examples Fontwt.htmi x og eiN Cusb
Favorites e Suggesteo Sae e Get More Add-ons

Font-Weight Demo Page Safety

Programming the Web

Programming the Web

Programming the Web

Programming the Web

100%
4Computer | Protected Mode Off

1.7.6 Font Shorthands


list
We can specify more than one font properties in a
For example

HTML Document[Fontshrthnd.html]
IDOCTYPE html>
<html>

<head
<title>Font Properties </title>
style type="text/css">
p.myfont {font-family:Courier New;
font-style:italic;
font-weight:bold;
font-size:28pt:

TECHNICAL PUBLICATIONS-An up thrust for knowledge


1 - 30
Advanced Web Programming
Refreshing Java Script and
o
</style>
</head>

<body
p class= "myfont">I Love my Country!!</p>>
/body>
</html>

Output

Font Properties Windows Internet Explorer

G eDXHTMi _Examples fontshrthnd.htm Togg eEN Cust P


Favontes eGet More Add-ons
Font Properties Page Safety

I Love my Country!!!

Computer | Protected Mode Off 100%

1.7.7 Text Decoration


Using text decoration property we can include special features in the text. Various
properties of text decoration are

underline
overline

line-through
HTML Document[TxtDecor.htm]
<IDOCTYPE html>
html>

<head>
title>Text Decoration</title>
<style type ="text/css'>
p linethrough {text-decoration:line-through,
p.underline {text-decoration.underline:}
p.overline {text-decoration overline;)
p.normal {text-decor ation
nonmal;}

TECHNICAL PUBLICATIONS An up thrust for knowledge


Advanced Web Programming 1-31 Refreshing Java Script and CSS
</style>
</head>
<body>
<p class="linethrough"> This text is having linethrough </p>
<p class= "overline"> This text is having overline </p>
<p class="underline"> This text is having underline </p>
<p class="normal"> This text is a normal text </p>

</body>
</html>

Output
Text Decoration Windows Internet Explorer

e
DiXHTMLExamples TtDecor html oggie Cust P
Favorites
eSuggestedSte Get More Add-onss
Text Decoration Page Safety

Pais-test is-hasing tinethreugh


This text is having overline

This text is having underlhne


This text is a normal text

Computer | Protected Mode Off 100

1.7.8 Alignment of Text


Using cascading style sheets we can align the text. This alignment can be done using
following properties such as -

Property Value Meaning

text-align left Aligning the text to the left.

text-align right Aligning the text to the right

text-align center Alignment of text at the


centre.

text-indent value in inches Desired indentation of the text


can be applied.

TECHNICAL PUBLICATIONS- An up thrust for knowledge


1-32 Refreshing Java.Script
Advanced Web Programming
andCs
various text alignment properties.
Following is script which uses
HTML Document[TextAlignCSS.htm!l]

<IDOCTYPE html>
<html>
<head>
stitle>Text Alignment Demo</title>

<style type= "text/css">

h1

font-family:Arial;
font-size: 15px;
text-align:left;

h2

font-family:Arial;
font-size:15px
text-align:right;

h3

font-family:Arial;
font-size:15px;
text-align:center;

/style>
</head>

<body>
<h1>This line is aligned at left </h1>
<h2>This line is aligned at right</h2>
<h3>This line is aligned at center</h3>
</body>
/html>

TECHNICAL PUBLICATIONS- An up thrust for knowledge


Advanced Web Programming 1 33 Refreshing Java Script and CSS

Output

Text Alignment Demo Windows Internet Explorer

e,D:XHTM_Examples\ TertAlignC SS htmi P


a3 5% CuitP
Favorites e Suggested Sates e Get More Add-ons
Tet Alignment Demo Page Safety

This line is aligned at left


This line is aligned at right

This line is aligned at center

100%
Computer | Protected Mode Off

1.8 Listss
unordered list and ordered lists. The unordered lists
are
There two types of lists
-

are

of various types such as square and circde disk.


given by bullets. These bullets are
the lists we use list-style-type property. For unordered list we can use
For displaying
values such as
property
Circle
Disk

Square
.None

Let us see their illustration in the HTML document.

HTML Document [list1.htm!]


<IDOCTYPE html>
<html>
head
<title>Unordered List Demo</title>

<style type="text/css">
ul flist-style-type:square}
</style>
</head
<body>
h2>Following are the useful vegetables... </h2
<ul>
<i>Carrot</li>
<li>Cucumber </li>
<li>Spinach</li>
</ul>

An up thrust for knowledge


TECHNICAL PUBLICATIONS
1 34
Refreshing Java Script and CSS
Advanced Web Programming

</body>
</html>
Output

Unordered List Demo WindowsInternet Explorer


eD:XHTML_Examples Listl .html
TsseEN Cust
Add-ons
e Get More
Favorites .cd S.te
Page Safety
Unordered List Demo

Following are the useful vegetables..

Carot
Cucumber
Spinach

Protected Mode: Off 100%


Computer

There is another way of representing the unordered list. It is illustrated by following


HTML document.

HTML Document[list2. html]


<IDOCTYPE html>
<html >
<head>
<title> Unordered List Demo</title>
<style type="text/css'>
li.disk {list-style-type. disk}
li.circle {list-style-type.circle)
</style>
</head>
<body>
<h3> Significance of Vegetables </h3>
<ul>
l i class="disk">Carrot
<ul>
<li class="circle">t improves appeaance of skin,hair and nail. </li>
<li class="circle"> It improves eyesight. </i>
<li class="circle">It regulates blood sugar. </li>
</ul>
</li>

TECHNICAL PUBLICATIONS-An up thrust for knowledge


Advanced Web Programing 1 35
Refreshing Java Script and CSS
</ul>
<ul>
<li class="disk'> Cucumber
<ul>

<li class="circle"> It is useful in liver diseases. </li>


<li class"circle"> It controls diabetes. </i>
</ul>

</li>
</ul>
<ul>
<li class="disk">Spinach
<ul>
<li class="circle">It anti-cancer agent. </li>
serves as an
<li class= "circle">It is anti-aging vegetable. </li>
<li class="circle">It is a rich source of Vitamin A and C. </i>
</ul>
</li>
</ul>
</body>
</html>

Output
eUnordered List Demo - Windows Internet Explorer

e D:XHTML_Examples list2.html
ToggirEN Cus
Favorites e Suggested Sites e Get More Add-ons
e Unordered List Demo
Page Safety

Signiflcance of Vegetables

Carot
t mproves appearance of skin,hair and nal
It innproves eyesight.
I t regulates blood sugar

Cucumber
I t is useful in iver diseases.
I t controls diabetes.

Spinach
l t serves as an ant-cancer agent
Itis
antd-agng vegetable
lt is a rich source of Vitamin A and C

Do
Computer | ProtectedMode: Off 100

TECHNICAL PUBLICATIONS-An up thrustfor knowiledge


1-36
Advanced Web Programnming Refreshing Java Scripript and CSSs
the list item bullet. For exanmnlo
We can also display small images as
HTML Document[list3.html]
IDOCTYPE html>

<htmi>
<head>
<title>Unordered List Demo</title>

style type="text/css'>
gif}
i image {list-style-image:url(people
</style
</head>

<body>
<h2>Indian Idols</h2>

<ul>
<i class='image">Naranyan Murthy</i>
<i class=image"> Lata Mangeshkar</li>
<li class='image"> Abhinav Bindra </li>
<i class=image'> Sachin Tendulkar</li>
<h class="image'> A.R.Rehman </i>

</ul>
</body
</html>

Output

Unordered List Demo - Windows Intenet Explorer

e D:XHTML_Exampleslist3.html x P ToggieEN Cust


Favortes
e uggested Sites e Get More Add-ons
éUnordered List Demo Page Safety

Indian Idols
8 Naranyan Murthy
8 Lata Mangeshkar
Abhinav Bindra
Sachin Tenchlkar
&ARRehman

Do Computer Protected Mode Off 100%

TECHNICAL PUBLICATIONS- An up thrust for knowledge


Advanced Web Programming 1-37 Refreshing Java Script and CSS

Let us now make use of ordered list.


For an ordered list various property values are enlisted below.

Property Value Sample preview

decimal 1,2,3,4

upper-alpha A,B,C,D

lower-alpha a,b,c.d

upper-roman LILITIL,IV

lower-roman Iii,ii,iv

HTML Document[list4.html]
<IDOCTYPE html>
<html>
<head>
<title>ordered List Demo </title>
style type="text/css">
ol {list-style-type:decimal;}
ol ol (list-style-type:upper-alpha; }
ol ol ol flist-style-type:lower-roman:}
</style
</head>

<body>
<h2>Vitamins in Fruits and Vegetables </h2>
<ol>
<li>Fruit
<ol>
<li> Apple
<ol>
<li>Vitamin A</li>
<i>Vitamin C</li>
s/ol>
</li>
<li>Banana
<ol>
<li>Vitamin A</li>
<li>Vitamin B1</li>
<i>Vitamin C</i>

TECHNICAL PUBLICATIONS-An up thrust for knowledge


Advanced Web Programming 1-38 Refreshing Java
Script and CSs
</ol>
</>
<li>Mango
<ol>
<h>Vitamin A</i>
<i>Vitamin E </i>

</ol>
<>
</ol>
<li>
<i>Vegetable
<ol>
<i>Cabbage
<ol>
<li>Vitamin A</li>
<li>Vitamin B1</i>
<i>Vitamin B2</i>
<li>Vitamin C</li>
</ol>
</i>
<i>Caulifower
<ol>
<>Vitamin A </li>
<i>Vitamin B1</i>
<i>Vitamn C</i>
</ol>
<i
<li>Potato
ol>

<li>Vitamin A </li>
<li>Vitamin E<i>
</ol>
<Ai>
</ol>
<1>

</ol>
< /body>

<html>

TECHNICAL PUBLICATIONS An up thrust for knowledge


Advanced Web Programming 1-39 Refreshing Java Script and CSS

Output
ordered List Demo Windows Internet Explorer Te
GUe, D0TMLEvamples listd htmi
s Favortes e Get More Add-cn:
e ordered List Demo Psge Safety

Vitamins in Fruits and Vegetables

Frut
A. Apple
i Vitamin A
i Vitamin C
B. Banana
i Vitamin A
i. Vitamin Bl
itamin C
C. Mango
i Vitamin A
Vitamin E
2Vegetable
A Cabbage
i VitaminA
Vitamn BI
Vitamin B2
Vitamin C
B. Caulower
i Vitamin A
i Vitamin Bi
Vitann C
C. Potato
i Vitamn A
Vit amin F
Done Compute| Protected Mode Cff 100%

1.9 Responsive Design


Definition: "Responsive design" refers to the idea that your website should
display equally well in everything from widescreen monitors to mobile phones.
I t is called responsive web design because you can resize, hide, shrink, enlarge, or
move the contents of the web page to make it look good on any screen.
The responsive web design makes use of HTML and CSS only. It is neither a
program nor a JavaScript.
Using the responsive design approach the web developer can give the best
experience for all the user. For example -

TECHNICAL PUBLICATIONS- An up thrust for knowledge


Advanced Web Programming 1 40 Refreshing Java Script and Css

Desktop Mobile phone

Tablet

Fig. 1.9.1 Responsive Layout for Different Devices

There are four key components that make responsive design work -

o Liquid Layouts
Scaling Images to the viewport size.
Setting viewports via <meta> tag.
o Customizing the CSS for different viewports using media queries.
.Making the use of liquid layouts means specifying the widths in percentage. This is
the most obvious of any responsive web design approach.
part Scaling images t
the viewport size means you have to specify following rule:
img
Width:100%;

I t only shrinks or expands the visual display of the image to fit the size of the
browser window, never expanding beyond its actual dimensions.

1.9.1 Setting Viewports


Viewport means user's visible area of web page
The viewport varies from mobile phone to desktop computers.
HTML5 allows the web developer to take control over the viewport using <meta

tag

TECHNICAL PUBLICATIONS An up thrust for knowledge


Advanced Web Programming
1-41 Refreshing Java Script and CSS

Following line must be included in your HTML document to set the viewport
name =
"viewport" content =
"width"=device-width, intial-scale = 1.0">
<meta

Sets the initial zoom


Gives browser the
Sets width of page as per level when the page is
instruction to control
device screen first loaded by the
dimension of web page
browser

Fig. 1.9.2

document structure will be :


The HTML
<html>
<head>
<meta charset="utf-8">

initial-scale=1">
<meta name="vievwport" content="width=device-width,
<style>

</style>
</head>

<body>

</body>
</html>

.By setting the viewport in above manner, the page is telling the browser that no
scaling is needed, and to make the viewport as many pixels wide as the device
screen width.

.This means that if the device has a screen that is 320 px wide, the viewport width
will be 320 px; if the screen is 480 px then the viewport width will be 480 px.

1.9.2 Media Queries


Another key component of responsive web design is media queries. Media queries
is for different style rules for different sizedevices such as mobiles, desktops ands
on.

I t uses the @media rule to lude a block of CSS properties only if a certain
condition is true.
F o r example - Following HTML document makes use of media queries for different

types of devices(such as mobile phones, tablets and desktops)

HTML Document
<IDOCTYPE html>
html>

TECHNICAL PUBLICATIONS- An up thrust for knowledge


- 42 Refreshng Java S
Advanced Web Pngramng ald Advanced Web Programming
1-43 RefreshingJava Scriptand CSS
<head> =device-width, initial scale=1.0" Review Questions
contet='width
<meta name='viewport
Responsme design in HTML
Writea short note on -

style> 1
with illustrative example, how to set viewport?
body 2. Lxplain
baCkgTOund coio. Ted,
3 What is media queries? Erplan its use with the help of example

/"Rules for Phones"/ 1 . 1 0 Bootstrap Introduction


and (max-wdth: 480px)
media ely sereen
It is used for designing web
source, front end web tramework.
.Bootstrap is open
bodyi bacKJrOUnd-color. green;
site and web applications.

.Bootstrap helps the developer to create responsive designs. Responsive web design
'Rules for Tablets"/ on all
means creating the web site which automatically adjusts itself to look good
@media only screen and (min-width: 481px)
devices range from small phones to large desktops
screens.
and (max-width: 768px) the devices. These
based design templates which
includes HTML, CSS and JavaScript
Bootstrap
boay { background-color: blue; } modals and so on.
includes forms, buttons, tables, navigation,
Rules for Desktops "/
Features of Bootstrap
@media only sCreen and (min-width: 769px)
Setting up Environment

bodyi background-color: yellow; } There are two ways to use Bootstrap in a webpage.
Content Delivery Using bootstrap Network.
The first way is to use a CDN
or

,style>
1) files in our server
download and store the bootstrap
CDN means that we will not
head the bootstrap CSS and JavaScript
links on
<body orlocal machine. We will just include
<h2>Resize the browser window and our page.
observe the change in color. </h2> files in our web
The second way is downloading and storing a copy Bootstrap
<body 2)
server or local machine. We can download the Bootstrap from
</himi>
https://getbootstrap.com/
Output downloaded my Bootstrap in this
I have created a folder named bootstrap-3.3.7 and
fonts and js
d.test.htrm folder. After downloadedI can see three folders in
it namely css,
x getting
follows
Bootstrap CSS as
-

C fle:!/d:/te the CDN then we will include


If we want to use

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.csS
|Resize the browser window and then we will use

observe the change in color. I t we want to use our own downloaded copy
ink rel="stylesheet
href-"bootstrap-3.3.7/css/bootstrap.min.css

Similarly the jquery can be used as


p t s t c = " h t t p s : / / a j a x .g o o g l e a p i s . c o m / a j a x / l i b s / j q u e r y / 3 . 0 . 0 / j q u e r y . m i n . j s > < / s c r i p t >

Or

tipt src="jquery-3.0.0.min.js"> </script>

TECHNICAL PUBLICATIONS- An TECHNICAL


PUBLICATIONS-An up thrust for knowledge
up thrust for
knowledge
Advanced Web Programming
1-44
Refreshing Java Script
and C Advanced Web Programming 1 45
Refreshing Java Script and CSS
Components of Bootstrap
write first Bootstrap Code 7
HTML elements and CSS propertiec How to
1. HTML5: TheBootstrap uses the properties, henee t
within the <doctvpe>, step 1: Open a Notepad and type the following code. Save it using the filename
code is contained extension .html
<IDOCTYPE html>
<html lang="en"> BootstrapDemo.html

<head> IDOCTYPE html>


meta charset= "utf-8'>
<html lang="en">

<head>
Script declarations <title>Bootstrap Example </title>
ead> <meta charset="utf-8">

<body> <meta name="viewport'


content="width=device-width, initial-scale=1'>

<link rel="stylesheet'
href-"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css>>

</body <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'> </script>


/atml <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>

2. The mobile-first Bootstrap 3 is designed to be </head>


responsive to mobile devices
Mobile-first styles are part of the core framework. <body>
<div class="container' style="background-color:grey>

For proper rendering the <meta> <h1 >Enjoying Web Page Design with Bootstrap</h1>
tag inside the <head> section is specified. It is
is here and it provides fixed width container</p>
specified as follows -
<p>The.container class
name=viewport content='width=device-width, initial-scale =1">
meta </div>
</body>
The width-device-width
part sets the width of page which is based on the screen /html>
width of the device.
Output
The initial-scale=1 sets the
part initial zoom level when the page is loaded
browser.
on
the
Bootstrap Example
3. Container The container element is for COfile:///D/BootstrapDemo.htmi
wrapping the site conternts. There are
two classes for the container -
i) container: It
provides a responsive fixed width container. Enjoying Web Page Design with Bootstrap
ii) container-fluid: It provides full width The containerolass is here and it providesfixed width container
the viewport.
container occupying the entire width o'
For example

container-fluid we will get the


Container Demo <div> element class to
Container-fluid Demo Similarly if we change the the
content to be occupied the entire web page.
It can be demonstrated by modifying

above script as follows


BootstrapDemo.html
SIDOCTYPE html>
shtml lang='en">
Shead
TECHNICAL PUBLICATIONS" An up thrust for PUBLICATIONS-An up thrust forknowledge
knowledge TECHNICAL
1 46 Refreshing Java Script
Advanced Web Programming and CSs 1-47
Advanced VWeb Programming Refreshing Java Scriptand CSS
</title >
<title> Bootstrap Example
<meta charset= "utf-8'> There are four classes of Bootstrap's Grid system and those are-
content="'width=device-width, initial-scale=1">
name="viewport" Class
<meta
Purpose
<link rel= "stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> XS It is used for phones
Sm It is used for tablet screen.
<script sro="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"'> </script>
script src="https://nmaxcdn bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </scripts md It is used for small laptops.
</head>
Ig It is for laptops and desktops.
<body>
be combined to create more dynamic and flexible display.
The above classes
can
<div class="container-fluid' style="background-color:grey;">
<h1 >Enjoying Web Page Design with Bootstrap </h1>
p>The .container class is here and it provides fixed width container</p> Structure of Bootstrap Grid
Grid is follows-
typical structure ofBootstrap
as
</div> The
<div class="row">

/body> <div class=""col-"*"> </div>

s/html> <div class="col-."></div>

</div>
<div class= "row"
Output <div class="col-*-*"> </div>

e -

OX <div class="col-*-*"></divV>

EocuspExample <div class="col-**"> </div>


C O'eu/. D Boctstrac Demo.html </div>

Enjoying Web Page Design with Bootstrap


**

In above structure we adding the row by


The contaner cass s here and t provdes fxed woth contaner <div c l a s s = " r o w " >

And then adding the column for that row using


<div class='col- </div>
md or so on. The second* indicates the
Here first
*
indicates the class as xs or sm or

number of columns. We can add at the most 12 columns.

Let understand how to use Grid system with a simple example


1.10.1 Grid System us

In Bootstrap there are 12 columns across the page. It is not GridDemo.html


have 12 columns we can always necessary to <IDOCTYPE html>
group the columns and wider columns can be created. html lang="en">
The Bootstrap's Grid
system is responsive. That means as we resize the browser <head>
window, the columns stitle> Bootstrap Example </title>
arrangement gets changed as per the screen size.
meta charset="utf-8"> initial-scale=1'>
content="width=device-width,

eta name="viewport"
link rel="stylesheet"
hre
h t t p s : / / m a x c d n . b o o t s t r a p c d n . c o m / b o o t s t r a p / 3 . 3 . 7 / c s s / b o o t s t r a p . m i n . c s s

TECHNICAL
PUBLICATIONS An up thrust for
knowledge TECHNICAL
PUBLICATIONS- An up thrust for knowledgee
A

AA A A A
50 Refreshing Java Script and Cs
vanced Web Programming
anced Web Programming 1-51 Refreshing Java Script and CSS
Output
X Output
Bootstrap +
BootstrapE
F O fle:///d:/Head1ng
E
Ofile:/l/d/Headingo

This line is of 36px This line is of 36px


This line is of 30px
This line is of 30px
This line is of 24px
The mark element
This line is of 18px
The smark element can be used to highlight the important text present in the line.
This line is of 14px
illustration
This ine is of 12px Here is the simple

MarkDemo.html

<IDOCTYPE html>
The small element
<html lang='en">
The <small> element is used to create the small light text in heading. For example <head>
<title>Bootstrap Example</title>
HeadingDemo.html <meta charset="utf-8">

<IDOCTYPE html> <meta name="viewport" content="width=device-width, initial-scale =1">


<html lang="en"> <link rel="stylesheet"
head> href "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css>

<title> Bootstrap Example</title>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'> </script>
meta charset='utf-8'>
Script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>
meta name="viewport" content="width=device-width, initial-scale=1'>
<link rel="stylesheet
/head>
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css> <body>
Script src="https://ajax.googleapis.com/ajax/ibs/jquery/3.2.1/jquery.min.js"> </script»
<div class="container">
SCript src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script
p > This line is an <mark>important </mark> nessage </p>
</div>
/head
</body>
<body>
</html>
<div class="container">
<h1> This line is of
<h2> This line is of
<small> 36px</small> </h1>
<small> 30px</small>
s/div> </h2>
Jbody
s/html>

TECHNICAL TECHNICAL
PUBLICATIONS-An up thrust
for knowledge
PUBLICATIONS An up thrust for
knowledge
Advanced Web Programming 1-53
Advanced Web Programming
Refreshing Java Script and CSS
Output
Output
Bootstrap Example
Bootstrap +
file:///d/PreDemo.h
file://d:/MarkDem
Humty Dumty
This line iS an impotant message sot on a
woll.
Jack and Jill
went up the
hill.
Twinkle Twi nkle
little stor
How I wonder
What you are!!!

The cpre> element

displaying the text multiple lines we can use <pre> tag. Here is the simr
For on
mple
example of this tag Colors and Background

, There are some contextual classes using which specific meaning can be represented
PreDemo.html
through the colors. The classes for text colors are -

<IDOCTYPE html>
<html lang="en'>
text-muted, .text-primary,.text-success,.text-info, .text-warming, .text-danger
<head> and
<title> Bootstrap Example</title> .Similarly we can align the text to left, right or center using text-left, text-right
<meta charset= 'utf-8"> text-center.
<meta name ='viewport' content= "width=device-width, initial-scale = 1">
. These are called contextual classes which provides the meaning through text.
<link rel="stylesheet"

href="https.//maxcdn bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css> .Let us use these classes in following demo application

TextDemo.html
sCcript
Script
sre-hrtps://ajax.googleapiscom/ajax/libs/jquery/3.2.1/jquery.minjs"> </script.>
srC="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min js"> </script> <IDOCTYPE html>

<html lang="en">
s/head <head>
body> <title>Bootstrap Example </title>
meta charset ="utf-8">
<div clasS="container> content="width=device-width, initial-scale=1">
meta name="viewport"
pre> link rel="stylesheet'
Humty Dumty hrefs"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css>

sat on a wall

Jack and Jill SCript src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

went up the hill. S C r i p t s r c = " h t t p s : / / m a x c d n . b o o t s t r a p c d n . c o m / b o o t s t r a p / 3 . 3 . 7 / j s / b o o t s t r a p . m i n . j s " > < / s c r i p t >

Twinkle Twinkle
</head>
little star
sbody>
HowI wonder Kdiv class="container>
What you are!
p class="text-left">This line is left aligned</p>
S/pre>
</div> p class="text-right">This line is right aligned </p>
D class="text-center">This line is at center </p>
</body> Sp class="text-muted">This line is using muted class</p
/html>
class</p>
p class="text-primary">This line is using primary

TECHNICAL PUBLICATIONS- An up thrust for PUBLICATIONS-An up thrust for knowledge


TECHNICAL
knowledge
- 54 Refreshi lava Script and 55 Refreshing Java Script and CSS
Advanced Web Programming Css Advanced Web Programming
success class </p>
line is using
<p class="text-success"> This <p class="bg-info">This
using info class </p>
line is
class="text-info">This line is using info class </p> line is using warning class</p>
<p class </p> <p class="bg-warning>This
line is using waming line is using danger class </p>
<p class="text-warming"> This class </p> <p
class="'bg-danger>This
class="text-danger">This
line is using danger
<p
</div>

</div </body>

</body> </html>

</html> Output
Output
This line is using primary class
This line is using success class
Bootstrap Example
This line is using info class
file:///d:/extDemc

using warning class


This line is left aligned This line is
This line is right aligned class
This line is using danger
This line Is at center

This ntS USng nuleg C1ass

Ihs ine S using pnmary Class 1.10.3 Tables


<td> tag is
The <tr tag is used for rows and
This ine IS uSing sUCCess class
The stable> is used to create the table.
tag
denoted within <thead><th> </th>
in the table can be
used for columns. The heading
This ine is Using nto class
in <tbody> tag.
contents of the table are specified
Itas n s ISing warning class
</thead> tag while remaining
demonstrates the use of table tag
This line iS USing danger class
The following example

TableDemo1.html
Similarly wecan set background color for these classes as follows: <IDOCTYPE html>
chtml lang="en">
TextBGDemo.html <head>
<IDOCTYPE html> title>Bootstrap Example </title>
<html lang="'en"> meta charset = "utf-8">
content="width=device-width,
initial-scale=1>
<head> meta name="'viewport"
title>Bootstrap Example</title> link rel="'stylesheet"
href-"https://maxodn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
meta charset="utf-8">
meta name="viewport" content="width=device-width, initial-scale= SCript src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'> </script>
<link rel="stylesheet" 1">
p t src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'> </script>
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
</head>
BCTipt src"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script <body>
SCript src= div class="container">
"https://nmaxcdn.bootstr apcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></sCTPl table class="table">
s/head>
<thead </tr>
<body <tr> <th> Name </th> <th> City </th>
<div class="container">
</thead>
p
p
class"bg-primary">This line is using primary class </p>
<tbody>
class="bg-success">This line is using success class</p> tr

TECHNICAL
PUBLICATIONS"-An up thnust for knowledgo
TECHNICAL PUBLICATIONS"- An up thrust for knowledge
Refreshing Java Script
Advanced Web Programming
1-56 and CSs Advanced Web Programming
1-57 Refreshing Java Script and CSS
<td>AAA std>
I m g D e m o . h t m l

std>Pune</td>

IDOCTYPE html>

</u>
<htmllang="en"
Str>
<td>BBB/td> he
<itle>Bootstrap Example</title>
<td>Mumbai</td>

< m e t a charset="utf-8'>
</tr> eta name="viewport" content"width=device-width, initial-scale-1'>
<link r e l = ' s t y l e s h e e t "
<td>CCC/td>
td>Chennai</td>

<Script
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'
"https://ajax.googleay
>
leapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</tr>
</tbody>
int SIC="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.minjs> </script>
</head>
</div>
</body> <body
/html <imgSrc "booklmg.jpg class "img-rounded">
=

"img-circle">
<img src = "bookimg.jPg class
=

Output class= "img-thumbnail">


<img src ="bookimg-jpg
</body>
atstrap Eam, X
</html>
0 file//a/TableDemo1.htn C

Output
AAA Pune
Bootstrap Example
BB8 Mumbai
file//d://mgDemo.html C Search
cCc Chennai

For having the grids to the table, we simply change the


<table class= table'>
to

Stable class="table table-bordered">

1.10.4 Images
For
displaying the images the cimg src""> tag is used. You have to specify the image
file name within the double 1.10.5 Button
quotes.
There are n Bootstrap we can create the buttons of different styles. Various button dasses are
three classes that are used to display the image. These classes are used as follows
1.
imgrounded: The image is displayed in border-circle of radius 6px.
a
2
imgcircle: The image is displayed in cirde of radius Dn,,btn-default, .btn-primary, btn-success, .btn-info, btn-warning, btn-danger, .btn-
link
3. 500px
img-ihumbnail
border.
The image is
:
displayed in a rectangle having padding and
g
Here is illustrative
example of displaying images

TECHNICAL PUBLICATIONS-An
up thrust for knowledge TECHNICAL PUBLICATIONS-An up thrust for knowledge
Refreshing Java Script
1 58 and Advanced Web Programming 1 59
Advanced Web Programming Refreshing Java Script and CSS
< h e a d >

follows-
The example code
is as <title>Bootstrap Example </title>
charset =
"utf-8">
<meta

ButtonDemo.html
<me
me='viewport" content="width=device-width, initial-scale=1'>
clink rel="stylesheet"
<IDOCTYPE html>
<html lang="en> href- tns://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<head>
Example</title
>
sCTP arc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min js'> </script>
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'> </script>
<title> Bootstrap initial-scale =1">
meta charset utf-8> content="width=device-width,
</head>

href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
meta name=viewport'
<link rel="stylesheet
<body>
huitton type="button" class="btn btn-success'>Success</button>
script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'> </scrint
"></script> <button pe="button" class=" btn-success active'> Active</button>
Scriptsrc=https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/1s/bootstrap.min.is utton type="button' class="btn btn-success disabled">Disabled</button>
</body>

</head>
</html>
<body> "btn'>Basic </button>
button type=
"button" ciass
=

b t n - d e f a u l t " > D e f a u l t < / b u t t o n >


Output
<button type="button" class="btn b t n - p r i m a r y ' > P r i m a r y < / b u t t o n >

class= "btn
<button type="button' </button>
b t n - s u c c e s s " > Success
ciass="btn
<button type="button' </button>
<button type="button" class="btn
btn-info">Info
"btn btn-warning'>Warning </button>
filell/d:/Buttor 5
<button type= button' class= btn-danger>Danger</button>
class="btn Success Active
<button type= "button" Disabled
btn-link'>Link</button>
class= "btn
<button type="button"

</body>
</html>
Output

Bootstrap Example +
x
file://d:/Button Demc C a Search C» 1.10.6 Form
Basic Defaut Primary Success Info Warning0 Danger Link In Bootstrap there are three types of form layouts.

Vertical Form 2. Horizontal Form 3. Inline Form

For the form must add the <div> element as <div class="form-group">. The
using we
this
<select>, <textarea> and so on can be added within
required controls such as sinput>,
<div class.
We can also create active of forms-
or disabled buttons using active and disabled clas5. The Let us discuss and learn how to create the above mentioned types
illustrationis as follows-
1. Vertical or Basic Form
ButtonDemo1.html To create the vertical or basic form use following steps-
<IDOCTYPE html>
html lang='en"> Step 1: Add a role to form element as-
sform role-"form">

TECHNICAL TECHNICAL
PUBLICATIONS-An up thrust for knowledge
PUBLICATIONS- An up thrust for knowledge
1--60 Refreshing Java Script nd ing
A d v a n c e d W e bP r o g r a m m i n d 1-61
Refreshing Java Script and CSS
Advanced Web Programming C
the controls o n type = "submit' class = "btn btn-default">Submit </button>
class="from-group"> Wrap all
Step 2: Inside the <div and <select
textual control such
as <text>, <textarea> and <select> add the
Step 3: While adding any </form>

class "form-control" < / b o d y >

</html>

Here is example code-


Output
FormDemo1.html
IDOCTYPE htmi> Bootstrap Example
<html lang =""en'> a Seareh
file//ld/FormC
<head </utle> User Name
title> Bootstrap Example
meta charset = 'utf-8>
content=
"width=device-width, initial-scale =1'>
meta name= "viewport
<link rel="stylesbeet
com/b0otstrap/3.3.7/css/bootstrap. min.css'> Password
href="https//maxodn bootstrapcdn

sCipt src= "https//ajax


googleapis.com/ajax/libs/jquery/3 2.1/jquery.min js'></scnipt>
src= https://maxcdn bootstrapcdn com/bootstrap/3.3.7/js/bootstrap.mn
js'> </scnpt > Show Me Aways
<script
Submit
</head>
<body>
<form role = form'>

2. Horizontal Form

basic form following steps


-

use
<dv class To create the vertical or
=
form-group
role to form element as -

Step 1: Add a
class="form-horizontal"
<label for = "name'>User Name < /label>
form role="form"> and form
labels and controls
Step 2: Inside the <div class="from-group"> wrap the
all
input type = text class = form-control"' id = name

control such <text, <textarea> and <select>add the


Step 3: While adding any textual
as
</div
class "form-control"

<div class= "form-group> Step4: Add a class of "control-label" to the labels.


Here is example code
label for =
"pwd'> Password </abel>
FormDemo2.html
nput type =
password class =
fom-contro!' id =
"pwd'> <IDOCTYPE html>
html lang="en'>
<head>
dv class =
"checkbox> title>Bootstrap Example</title>
meta charset="utf-8>
jabel> <

nput type
initial-scale=1>
=

'checkbox'> Show Me content="width=device-width,


Always </label> eta name="viewport"
link rel='stylesheet
ttps://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css

TECHNICAL PUBLICATIONS-An up thrust for knowledge


PUBLICA TIONS- An up thrust for knowledge TECHNICAL
Refreshing Java Scrip Advanced Web Programming 1 63
1-62 and C freshing Java Script and CSS
dvanced Web Programming
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </e.

script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">e.-/script>
Inside the <div class="from-group> wrap all the controls
S t e p2 : I n s i d e

.minjs"></script S t e9
p 3 ;
While adding any textua control such as <text>, <textarea> and <select> add the
class "form-control"
</head
example code
-

cbody ="form-horizontal" role = "formm> Here is


form class
<div class = 'form-group"> Name </label> FormDemo3.html
"'name"> User
col-sm-4" for
=

class="control-label
label <IDOCTYPE h t m l >
d i v class='control-label col-sm-8'>
<html lang="en">
"form-control" id = "name">
"text' class
=
=

Kinput type <head>

</div>
<title>Bootstrap Example </title>
<meta charset="utf-8"'>

</div>
<div class = "form-group> emeta name="viewport"' content=-width=device-width, initial-scale= 1">
col-sm-4' for = "pwd'>Password </label> <link rel="stylesheet"
label class="control-label

col-sm-8'> href-"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<div class="control-label
"password" class
= "form-control" id =
"pwd">
input type
=

/div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'> </script>


s/div>
cscript src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'> </acript>
<div class="form-group">
</head>
<div class="col-sm-offset-4 col-sm-8">
<body>
<div class= "checkbox'> role = "form">
<form class="form-inline"
<label> <input type = "checkbox'> Show Me Always<Aabel> <div class = "form-group">

</div> <label for = "name">User Name <label>

</div> <input type =


"text" class =
"form-control" id =
"name">

s/div> </div>
<div class="form-group>
<div class="col-sm-offset-4 col-sm-8">
<div class = "form-group">
<button type "submit' class =
"btn btn-default">Submit <</button> <label for = pwd"'>Password</label>
/div>
<input type = "password" class = "form-control" id = "pwd'>
/div>
S/form> </div>

</body> <div class = "checkbox">


/html>
<label> <input type = "checkbox'> Show Me Always</label>

3. Inline Form </div>

In an inline form, all of the elements button type = "submit" class = "btn btn-default"> Submit </button>
alongside.
are inline, left-aligned, and the labels are

To create the inline /form>


form
Step 1: Add a
use
following steps -

<Abody>
role to form element as -
s/html>
sform role="form">
And the class as
"form-inline" to the <form>
element

TECHNICAL PUBLICATIONS
An up thrust for knowledge TECHNICAL PUBLICATIONS-An up thrust for knowiedge
1 64
Refreshing Java Script and ( 1- 65
Advanced Web Programming
Advanced Web Programming
Refreshing Java Script and CSS
<script type="text/javascript">
Output the First JavaScript"/
"This is
document.write(" Welcome to First Page of Javascript");
</script>
Bootstrap Example +
</center>
Seoreh
file:///d/Form Demo3.htm
Oshow Me Aways Submit </body>
Password
s e r Name html>

Output

My First Javascript- Windows Internet Explorer


e D:UavaScript EnFirstPg. htm x ToggieEN Cust P
Favorites
e Suggested Sites Get More Add-ons
M y First Javascript Page
PartII:JavaScript Wecome First
to Page of Javascript
1.11 Java Script Syntax
JavaScript is a cient side seripting language.

.JavaScript was developed by Netscape in 1995. At that time its name


was Computer | Protected Mode O 100%
LiveScript. Later on Sun Microsystems joined the Netscape and then they
developed LiveScript. And later on its name is changed to JavaScript.
Script Explanation:
The JavaScript can be directly embedded within the HTML
document or it can be In above script
stored as external file.
(1) We have embedded the javaScript within
Directly embedded JavaScript <sCript type="text/javascript'>
The syntax of
directly embedding the JavaScript in the HTML is
<script type="text/javascript">> /script>
(2) A comment statement using and "/. Note that this type of comment will be
.

recognized only within the <script> tag. Because, JavaScript supports this kind of
s/script> comment statement and not the XHTML document.
G) Then we have written document.write statement, using which we can display
Example 1.11.1 Write a
JavaScript to display Weloome message in the desired message on the web browser.
Solution: JavaScript
IDOCTYPE html> Indirectly Embedding JavaScript
<html >
If we want to embed the JavaScript indirectly, that means if the script is written in
<head>
SOme another file and we want to embed that script in the HTML document then we must
<title> My First
</head Javascript </title> write the script tag as follows -
<body> Script type="text/javascript" src="MyPagejs">
Scenter in
Javascript is which is to be embedded is
| the file MyPage js
TECHNICAL PUBLICATIONS
An up thrust
for
knowledge
TECHNICAL PUBLICATIONS- An up thrust for knowledge
Ireshing Java Script and C A d v a n c e d W e bP r o g r a m m i n g
1-67 Refreshing Java Script and CSS
1 66 S
Inbuilt Objects
Advanced Web Programming Script
1.12Java
object is a collection of properties. These properties are nothing but the
In JavaScript objec
classes from Java or C++. For instance in JavaScript the object Date() is -

JavaScript file. the


s/script the external members of member of the class inJ
happens to the
to use

follow the following steps which


We will follows- ed
document as
XHTML
Create an 1.12.1Math Objects
Step 1:
athematical computations there are some useful methods
the mat)
XHTML D o c u m e n t [ F i r s t P g . h t m l ]
For performing
<IDOCTYPE html> availablefrom math object.
<html> if we want to find out minimum of two numbers then we can write -

Eor example
<head Javascript </title> document.write(math.min(4.5,7.8);
sitle> My First
various useful methods
statement will result in 4.5. Thus using we can
</head>
Tho above
<body> mathematical computations.
<center >

srC= my_script.js"> perform many


commonly used methods from math object.
= text/javascnpt'
SCnipt type
. Here are some
</script is is an externa
</center >
Method
Meaning
javascript file.it can
</body> be specified with the
root of
This method finds the square
num.
</html> attribute sre sqrt(num)

of
This method returns absolute value
num.

Step 2: abs(num)
11.
This method returns the ceil value of num. For example ceil(10.3) will return
JavaScript my_script.js] ceil(num)
/This is the First JavaScript"/ return 10.
This method returns the floor value of num. For example floor(10.3) will
document.write(" Weloome to First Page of Javascript") floor(num)
will
This method returns the natural logarithmic value of num. For example log(7.9)
Step 3: Open the HTML document in Internet Explorer and same above mentioned output can be log(num)
obtained. return 2.

will return 32.


Advantages of indirectly embedding of JavaScript
pow(a,b) This method will compute the ab. For example pow(2,5)
1. Script can be hidden from the browser user. and b.
min(a,b) Returns the minimum value of a

2 The layout and presentation of web document can be separated out from the
max(a,b) Returns the maximum value of a and b.
user interaction through the
JavaScript.
sin(num) Returns the sine of num.
Disadvantages of indirectly embedding of JavaScript
1.f small amount of Cos(num) Returns the cosine of num.
JavaScript code has to be embedded in XHTML document
then making a Reurns the tangent of num.
separate JavaScript file is tan(num)
2If meaningles.
the JavaScript code has to be embedded at several exp(num) Returns the exponential value i.e. enum.

then it is places in XHTML document


complicated to make separate JavaScript file and each
code for it from the
XHTML
tne time invoking JavaScript Program[MathDemo.htmi
document.
IDOCTYPE html>
html
<head>
title>Math Demo</title>
TECHNICAL PUBUICATIONS An up thrust for
for knowledge
-

up thrust
knowledge TECHNICAL
PUBLICATIONS-An
Refreshing Java Script and A d v a n c e d VWebP r o g r a m m i 1 69
1-68 Co. Refreshing Java Script and CSS
AdvancedWeb Programming

</title>
< h e a d s

Object Demo
ctitle>Number
</head
<body </head>

<center </h3>
<body>

root of 100 is center>

<h3>Square <script type="text/javascript'>

script type="text/javascript'>

nt.write(Number.NEGATIVE_INFINITY);
var num-100:
document.write'<h3>"+Math.sqrt(num)+'</h3>");
</script>

</center>

</script>
</body>

</center S / h t m l >

</body>
Output
<html>
Output
Demo -
Windows Internet Explorer
Number Object
DUavaScript ExNumberDemo.htm x P ToggieEN Cush P
tnplore
Windows I n t e e t
Math Demo
e olavascrptEx\MathDermo.htmi
x P ToygiriN Cust
Ge More Add-ons
Favonkes 99oted ue
P a g e Safety Favorites
eSuggested Sites Get More Add-ons
M a t h Dene
Number Object Demo Page Safety
root of 100 Is
Square

10 -Infinity

Computer | Protected Mode Off 100% 100%


Protected Mode: Off
Computer|

1.12.2 Number Objects


Various properties ofnumber object are 1.12.3 Date Objects
the date and time.
Property Meaning This object is used for obtaining time) or it can
local time (system's
value is based on computer's
.This date and time
MAX VALUE Largest possible number gets displayed.
GMT(Greenwich Mean Time).
be based on Co-ordinated Time. This
MIN_VALUE Smallest possible number gets displayed. UTC ie. Universal
NaN When not Nowadays this GMT is also known as
a number then NaN is displayed.
is basically a world time standard.
PI The value of Pl gets
displayed. Date object.
used methods of
POSITIVE INFINITY The Following are the commonly
positive infinity gets displayed. Meaning
Method
NEGATIVE INFINITY The negative infinity gets displayed. milliseconds. This value is the
difference
number of
Using Number.property_name It returns the January 1970.
uses the
we can
display the property value. Following Java>i getTime0 time and the
time value from
1st
property of negative infinity. between the
current

local time.
computers
JavaScript[NumberDemo.htmi]
<IDOCTYPE html> getDate0
Returns the current
date based on

from UTC.
date obtained
html> Returns the c u r r e n t
getUTCDate)
for knowledge
PUBLICATIONS-An up thrust
TECHNICAL
TECHNICAL PUBLICATIONs-An up thrust for knowledge
1- 70
Refreshing JavaSc and
C. Advanced
Web Programming 1-71
Advanced Web Programming Refreshing Java ScriptaandCSS
The day
number is from
trom 0O to 66 i
1.e.
Date();
Returns the current day. from var my
date=new
write("The date is: "+my_date.toString()+"<br>");
getDay)
Sunday to Saturday. dooun arite("Today's date is+my date.get Date()+"<br>"):
docunt.rite("This is the month of "*my_date.getMonth()+"<br>");
current day bascd on U i c . The day number :
Retums the
getUTCDay()
to Saturday. document.
write("The current year
is"+my_date.getFullYear()+"<br>>;
to 6 i.e. from Sunday Hour ="+m
"+my_date.getHours()+"<br>
Write("Now,
document.
Returns the hour
value rangng
from to 23, based on local.
time. do write("Minutes "+my_date.getMinutes()+"<br>");
nt rite("'Seconds
docul = "+my_date.getSeconds() +"<br>");
getHours(0
value ranging trom U based UTC
t0 23, on

getUTCHours)
Retums the hour
timing </script>

zone. </body>

ranging from 0 to 999, based


Returns the milliseconds value
</html>

on
getMilliseconds() Output
local time.

Intemet Explorer
Returns the milliseconds value ranging from 0 to 999, based on Windows

getUTCMilliseconds() e Date
Demo
-
|
UTC timing zone.
e] D:UavaScript_Ex\DateDemo.htm x | P ToggieEN Cust P

e Suggested Sites e Get More Add-ons


Returns the minute value ranging from 0 to 59, based local time
Favorites

on
getMinutes() 6 Page Safety
Date Demo
getUTCMinutes() Returns the minute value ranging from 0 to 59, based on UTC
18 16:0S:32 UTC+0530 2009
timing zone. The date
is: Tue Aug
is l 8
Today's date
of 7
month
Returns the second value ranging from 0 to 59, based on local time. This is t h e
getSeconds() cureent year
is 2 0 0 9
The
165
Now, Hour
=

getUTCSeconds() Returns the second value ranging from 0 to 59, based on UTC
Minutes 5
Seconds = 32
timing zone.

setDate( value) This function helps to set the desired date using local timing or 100%
Mode: Off
Computer | Protected
UTC timing zone.
setHour(hr, minute, second, ms) This function helps to set the desired time local
using or UTC
iming zone. The parameters that can be passed to this function are
Script Explanation: instance my_date of the object
Date().
created an
1. In the above script w e have
hour,minute,seconds and milliseconds. Only hour parameter is we can display the current date along with
method
2. Then using my_date.toString)
compulsory and rest all are the optional parameters.
In the the time. we are displaying
following web document we are
making of Date() like getDate(), getMonth(),
getFullYear()
methods ofit.
use
object and some usern 3. Then using the functions
the date, month and year separately. w e can
and getSeconds)
JavaScript[Date Demo.html] 4Similarly using the
functions getHours(),
getMinutes()
<IDOCTYPE html> seconds separately.
minute and
<html> display the current hour,
<head>
title> Date Demo</title> 1.12.4 Boolean Objects especially
when we want to

s/head> which is used


of object
n i s object is the simplest kind
body>
<script type="text/javascript"> represent true and false values

PUBLICATIONS
-
An up thrust for knowledge
TECHNICAL TECHNICAL

PUBLICATIONS An up thrust for


knowledge
1-72 Refreshing Java Script 1-73
Advanced Web Programming A d v a n c e d VWeb P r o g r a m m i n g

Refreshing Java Script and CSS


variable is used.
in which the Boolean type
Here is asimplejavascript Method Meaning
Javascript Program
This method concatenates the two strings. For example sl.concat(s2) will
c o n c a t ( s t r )

html> resultin concatenation ofstrings1 with s2


cbody>
charAt(index_val) This method will return the character specified by value index _val.
BCript typ6="text/javascript'>

var temp n e w
Boolean(false): ethod returns the substring specified by
substring(begin,end) This method
begin and end character.
boolean vahue is: );
document.writel'<b>"+The

This function is used to convert all the uppercase letters to lower case.
document.write(temp.toString(); toLowerCase()

s/script Thisfunction isused to convertallthe lowercase letters to upper case


toUpperCase()

</body This method returns the value of the string


</html>
valueOf)
Output important property
of ring object and that is length. For example
There is
one

D: Javascript_ExamplesibooleanDemo.htmi-Microsoft. Ox v a rm y _ s t r = " H e l l o " ;


Length of the string "Hello" will be
Favorites Tools Help var len; stored in the variable len
File Edit View
len=my str.length;

Berk * Search Favortes Here is sample program


in which some methods of string object are used.
Address :avascript_ExemplesibooleanDemo. htrml Go Links
JavaScript[StringDemo.html
<IDOCTYPE html>

The boole an value is: false <html>


<head
and Methods Demo </title>
<title>String Properties
/head>

<body>
<strong
SCript type="text/javascript'>

Done I ORComputer var s1="Hello"


var s2="Parthl"
1.12.5 String Objects document, write("First string is: "+s1+"<br>");
"+s2+"<br>");
String is a collection of characters. document, write("Second string is: "+s1.concat(s2)+"<br>");
write("Concatenating two strings:
I n JavaScript using string object many useful string related functionalities can e document, "+s2.length+"<br>";
document,write("Finding length of Second
string:
+s1.charAt(0)+"<br>");
exposed off.
oment.Write("The character at Oth position of First string is:
case as: "+s1.toUpperCase()
Some be converted to upper
commonly used methods of string object are concatenating wo strug" ment,write("The First string can

converting the string to upper case or lower case, en </script>


finding the substring of a gv
string and so on. S/strong>
Here is a s/body>
listing of some methods of string. S/html>

TECHNICAL PUBLICATIONs-An
up thrust for PUBLICATIONS-An up thrust forknowledge
knowledge TECHNICAL
1-74 Refreshing Java Script 1-75
Advanced Web Programming andr.
A d v a n c e d W e bP r o g r a m m i n

Refreshing Java Script and C


Output

Methods DeiO
Windows nternet Explorer Mozilla Firefox
Popertes
and
String9

E DUavaScrpt_tx\StrngOeno htm
-|4,x oggirFN ( usti P -| Yiew Higtory Rookmarks Iools Help
e Get More Add-ons
Eile Edit
Favontes
gestrd Sites
Page Safety
C r i l e / / / d / / r e v e r s e . h t m l

and Met.. 6
String Properties
First string is: Helo
Second string is: Parth!
file/llt://reverse.htm!
C 3-Google P
Helo Parth!
two strings:
Comcatemating
Finding length of Second s n g 0
:H
of First string is
The character at Oth position case as
: HELLO strag is
The original
coaverted to p p e r
be
The First string can

in javascript
I ike writing
Computer | Protected Mode Of 100% striag is
reversed
The
writing ike I
javascript in

Example 1.12.1 Write a script that inputsa line of text, tokenizes it uwith String metihod split
and displays the tokens in reverse order.

Solution:
<html>

<body>
script type="text/javascript'>
var str=new String(1 like writing in javascript"); and Modification
var a=new Aray): 1.12.6 Object Creation and can set its properties as per his
.The web designer can create an object
ast.splt( ");
document.write('< strong> The original string is requirements.
</strong>"+"<br/>");
for(i=0:i<a.length:i+) expression.
object can be created using
new
The
statements
document.writela[i)+"); no properties can
be set using following
document.write('<br/>"); Initially the object with
Myobj-new Object(l:
document.write( <strong>The reversed string is </strong>"+"<br/>"); the properties for that object.
can set
for(i=a.length-1;i> =0;i-) Then using dot operator we
document.write(alij+ *); T h e object can then be modified by assigning the
values to this object.
s/script>
/body JavaScript[ObjectDemo.html]
s/htmi>
<IDOCTYPE html>
<html>

<head
title>Object Creation Demo</title>
s/head>

<body>

TECHNICAL PUBLICATIONS An up thrust up


thrust
for knowledge
for knowledge
PUBLICATIONS-An

TECHNICAL
1- 76 Refreshing Lava Scrpt A d v a n c e dW e bProgrammin
1-77
Refreshing Java Script and CSS
ldvanced Web Programming and C
ent.write(The
ID is "+Myobj.id +<br/>");
document. Name is "+ Myobj.name);
cument.write("The
<strong>
can be deleted using an
<script type= text/javascript>
o f created object expression delete. Normally the
hiect is deleted in order to free the allocated memory so that this memory
var Myobj:
propertyofa
other
process.

reused by
var n. can
be

//creating an object 1.13DOM

Myobj=new Object();
Definition
of DOM
created object
//setting the
propertis for newly 1.13.1
The Document Object.Modeling (DOM) is for defining the standard for accessing
Myobj.id= 10; and manipulating HTML (ML and other seripting languages
documents.
Myobj.name="Anuradha";

I t is the
W3C recommendation
tor handling the structured
ID is '+Myobj.id
+"<br/>");
structured information is provided in XML, HTML and many other
document.Write( The
ormally the
Name is+Myobj.name);
document.WTite(The documents.

interfaces for working with


.Hence DOM provides
the standard set of programmin
</script>
XHTML and JavaScript.
</strong> XML and

What is DOM?
</body>
and language neutral Application
set of platfom independent
Model (DOM) is a
</html> Document Object the information storedin
access and manipulate
Output Interface (API) which describes how to
Programming
documents.
Demo Windows Internet Explorer XMLHTML and
JavaScript
eObject Creation
eD:UavaScript_ExObjectDemo.html x| ToggieEN CUEt P

Favortes E 9ested Sites e Get More Add-ons 1.13.2 DOM Tree


defines the
Interface (APD that
E Object Creation Demo Page Safety DOM is an Application Programming
Basically That means, suppose
document and application program.
The ID is 10 interface between HTML wants to access the
The Name is Anuradha written in Java and this Java program
application program is a set of Application
document then it is possible by
using
elements of HTML web
which belongs to the DOM.
Programming Interfaces (API) document tree node type.
These
interfaces for the
The DOM contains the set of properties
interfaces. They have objects,
or C++
interfaces are similar to the Java
web document.
node type of the
and methods which are useful
for respected
in which every
like structure
Computer | Protected Mode Off a tree
100%
documents in DOM represented using
Ihe are
referred as DOM
tree structure is also
as a node. Hence the
Alternative method of cement is represented
creating an
object and modifying the properties is as given
below- tree.
XHTML document.
var Myobj={name:'Anuradha",id:10}
For example: Consider following
Then <html>
using document.write statement we can
display the property values as
foio <head>

TECHNICAL up thrust for knowledge


PUBLICATIONS- An up thrust for knowledge TECHNICAL
PUBLICATIONS-An
1-78 Refreshing Java 79 Refreshing Java Script and CSS
sCrpt and :
dvanced Web Programming

Advanced Web Programming


Useful for creating a text node.
Web Page </title> create
TextNode

title> This is My Useful for creating attribute.


</head createAttribute

<body> For adding a new child to specified node, this method is used.
<h1>Hello Friends </h1> appendChild

ch2>How are you?</h2> For removing a child node of a specific node, this method is used.
removeChild

</h3> See you</h3>


This method is useful for retuming the specified attribute value
</body g e t A t t r i b u t e

</html> This method is useful for setting or changing the specified atribute to the
setAttribute

specified value.
T h e DOM tree will be

Document

Properties

Meaning
Property
the attribute nodes of the node.
<body This property is used to get
head a t t r i b u t e s

the parent node of the specific node.


p a r e n t N o d e
This DOM property is useful for obtaining
node.
This DOM property
is useful for obtaining the child nodes of the specific
<h3> childNodes
ctide? <h1> <h2 the text value of a node.
innerHTML
It is useful for getting

This is My Web Page" "Hello Friends "How are you?" "See you' Elements using DOM
Fig. 1.13.1 DOM structure for simple web document 1.13.3.1 Accessing which we can access the elements ofthe web
document.

.There are
several ways by web
We can describe somebasic terminologies used in DOM tree as follows
these methods of accessing we will consider one simple
.To understand
1. Every element in the DOM tree is called node. document as follows.
2. The topmost single node in the DOM tree is called the root.
<html
3. Every child node must have a parent node. <head>
</title>
4. The bottommost nodes that have no children are called leaf nodes. <title>This is My Web Page

5. The nodes that have the /head


common parent are called siblings. <body>
Kform name="form1">
1.13.3 Using DOM Methods input type="text"
name="myinput"/

We can access or change the contents of document by using various methods. Some
</form
commonly used properties and methods of DOM are as follows /body>
/html>
address is
Methods address. This
Method 1 associated with some

element is
Method XHTML document
Meaning Very
refer the text
w e can
getElementByld This method is used to obtain the speific element which is called DOM address. elements.
Hence

id within the
specified by collection of forms
and
some
script. The Ocument has the

createElement This method is used to create an element box element as


node.
forms|01.elements|0
var Dom Obj=document for knowledge
thrust
P U B L I C A T I O N S - A n
up
TECHNICAL PUBLICATIONS- An up thrust
TECHNICAL

for knowledge
80 Refreshing Java Script Advance W e bP r o g r a m m i n g 1-81
Refreshing Java Script and CS
Advanced Web Programming and CSs
the elements. Because if
But this is not the suitable
method of addressing u

change < d i vi d = ' d i v 1 " >

1">The first sentenceiin HTML doCument. </p>


the above script as < pi d = " p 1 " >

second s e n t e n c e in HTML document. </p>


id="
p2">The
<p

<form name="form1"> </div>

name= "mybutton"/>
Kinput type="button"
< s c r i p t >

<input type="text" name="myinput"/> ument.createElement('p");


=
docun
pnode ent.createTextNode("This is newly added sentence in HTML document.);
var
docu
</form> var
node
=

pnode.appendChild(node);

t.getElementById "'div1";
**

Hence another approach of accessing the elemons document.

gets changed.
element

then index reference nts element.appendChild(pnode);


V a r

is developed.
/sCript
</body>
Method 2
</html>

We can access the desired element from the web document using JavaScript method
The element access can be made as follows
-

getElementByld. file:///d:/test.html
X+
var Dom Obj=document.getElementByld("myinput")%
.But if the element is in particular group, that means if there are certain elements on Ofile///d:/test.html C QSearch
the form such as radio buttons or check boxes then they normally appear in the
these elements we make use of its index. Consider the in HTML document.
groups. Hence to access
The first sentence

following code sample


sentence in HTML document.
<form id="Food"> The second
<input type="checkbox" name="vegetables" value="Spinach" />Spinach
sentence in HTML document.
cinput type= "checkbox" name="vegetables" value= "FenuGreek" />FenuGreek This is newly added
<input type= "checkbox" name="vegetables" value="Cabbage" />Cabbage
</fom>
For getting the values of these checkboxes we can write following code.
varDom_obj=document.getElementByld("Food");
forli 0;i < Dom_Obj.vegetables. length; it+) DOM
Inserting an element Using and insertBefore

document.write(Dom_Objvegetablesli] +"<br/>"); We can insert a node in between the


nodes by using appendChild
1.13.3.2 Moditying Elements using DOM method. For example
<IDOCTYPE html>
Appending an element Using DOM
html>
We can add new node in the HTML document
using the DOM method appendChild <body>
method

Following example illustrates the idea div id="div1>


<IDOCTYPE html> sp id="p1'>First Sentence </p>
<html>
Sp id=p2> Second Sentence s/p>
<body>
TIONS- An up
thrust forknowledge
PUBLICA
TECHNICAL
TECHNICAL PUBLICATIONS-An up thrust for knowledge
Advanced Web Programming
1 82 Refreshing Java Scnt tr
ogramminy
AdVvancedWebPro 1-83
Third Sentence </p>
Refreshing Java Script and CSS
idiv p ip
d o

<Jdiv>

Kseript>
var pnode= document.cresteElement('p').
<Bripts

rentnode document.getElement Byid( div'")


Node( Newly Added Sentence!")
v a rp a
document.getEle entByid('p2");
var node document cTreate Text v an
r ode

pnode.appendChild(node), arentnoderemove
Child(node);
document getElementByld('div1').
varelement =
ecript

VRr Dextnode = document get ElementByld('p2). < f b o d y >

h t m l >

element insert Before(pnode,nextnode) Output


/script
X
file///d/test.htm
<body
</html>
file/I/d:/test.htmi C Search
Output

x First Sentence
fle d test html +
Third Sentence
file:///d:/test.html C aSearch

Furst Sentence

Newty Added Sentence!

Second Sentence

Example 1.13.1 Write a JavaScript to display


sum of ruwo elements. Make use of appropriate
DOM method.

Removing an element Using DOM Solution


We can remove or delete <IDoctype html>
particular from HTML document using DOM's removeChild <html>
method.
head>
Here is the illustration SCript type="text/javascript'>
<IDOCTYPE btml> function getSum()
chtml>
body 1).value
var n u m b e r l = d o c u m e n t . g e t E l e m e n t B y l d ( ' n u m b e r
var number2=document.getElementByld('number2"),value;
<div id="div1'>
var numi=Number(number1)
<p id=p1'>First
Sentence </p> var num2-Number(number2)
sp id="p2"> Second Sentence </p>
alert(num1+num2)
up thrust for knowedge
TECHNICAL PUBLICATIONS An up thrust for knowedge TECHNICAL
PUBLICATIONS-An
- 84
Refreshing Java Script 1 - 85
Refreshing Java Script and CSS
A d v a n c e dW o bP r o g r a m m i n g

AdvancedWeb Programming and C

< / s o r i p t >

</script
/head
</head
cbody>
<body>
<form> i d = " n u m b e r 1 " / > < b r / >
<br/> rm>
lame: <input type="text" name="user" /> <br/> <br/>
type="text" EnterN
Enter Num1:<input id= 'number2"/>
<br/>
De="button" value ="Greet" onclick="display(0/>
type="text"
Enter Num2:<input 'SUM°
onclick="getSum()'/>
<input

"button' value=
cinput type= </form
</body>
/form
</body> </html>

</html> Output
Output
Dx
/d:/DomDemo.html
x+
X
/d:/DomDemo.html x+
file/l/d/DomDemo C a Search E
fle//d:/DomDemo C Q Search
Enter Name Chitra
Enter Numl:10
Greet Welcome Chitra
Enter Num2:20 30
SUM
OK
OK

1.14 Event Handling


Example 1.13.2 Write a JavaScript to welcome the user by his/her name when he enters his/her
name in textbox. Make use of
Definition of Event: Event is an activity that represents a change in the
appropriate DOM method. environment. For example mouse cicks, pressing a particular key of keyboard
Solution
IDoctype html> represent the events. Such events are called intrinsic events.
<html> Definition of Event Handler: Event handler is a script that gets executed in
head response to these events. Thus event handler enables the web document to respond
Script type="text/javascript'>
function display() the user activities through the browser window.
and
Javascript support this special type of programming in which events may occur
var name=document.getElementsByName('user): handlers. This type of
these events
get responded by executing the event
alert("Welcome "+name[0].value);
programming is called event-driven programming.

TECHNICAL PUBLICATIONS An up thrust TECHNICAL PUBLICATIONS- An up thrust for knowledge


for knowledge
Advanced Web Programming
1 86 Refreshing Java Script ancd 1 d v a n c e d
W e bP r o g r a
mming
m n

-87
SS
in lowercase letters
and these are case-sensitive. Refreshing Java Script and CSS
Events are specified
event handler to an event Form elements
Registration: The process of connecting is called When such
onkeypress user
.Event presses the key. as

event registration. The event handler registration can be done ing two nm
using methods keypress

input,button,text, textarea
and so on.
attributes
When user clicks the left
o Assigning the tag mouse Form elements such
mousedown
onmousedown

onm button. as

o Assigning the handler


address to object properties. input,button,text, textarea
and so on.
When user releases the left
Internet Programming mouse Form elements such as
be assigned with some onmouseup button.
the tag attribute must user
On occuence of events

to execute certain action on occurrence


define
of particular et.
m o u s e u p

input,button,
and so on.
text,textarea
functionalities. This will help
attributes are enlisted in the following table Form elements such
Commonly used events and tag m o u s e m o v e o n m o u s e m o v e

When user moves the


mouse.
as

Events Intrinsic event Meaning Associated tags input,button,text,textarea


and so on.
attribute
When the user moves the mouse
form elements such
<button onmouseout away from some element.
as

sinput>
mouseout
input,button,
and so on.
text,textarea
onblur Losing the focus. a>
When the
blur user moves the mouse Form elements such as
<textarea> away over some element.
mouseover
onmouseover

inputbutton, text, textarea


<select and so on.

cinput> After getting the document


<body>
onload
onchange On occurrence of some change. textarea> load loaded.
change
select When the reset button is clicked.
reset
onreset <form>
When user clicks the mouse Ka>
When the submit button is
click onclick cform>
button. onsubmit
sinpus submit clicked.
When user double clicks the a>
On selection. <inpu>
dblclick mouse button. onselect
ondblclick input select <textarea>
<button>
unload onunload
When user exits the document. <body>
<a>

input> The use of these tag attributes for handling the events is illustrated by following code
focus onfocus When user acquires the input <select
sample
focus. textarea
Sinput type ="button" name="My_button"
onclick="My_fun();
When user releases the key from Form elements such as

keyup onkeyup the keyboard. inputbutton,text, textarea


and so on.

Form elements such as Tag attribute Event handler

keydown onkeydown When user presses the key down input,button,text,textarea


and so on.

TECHNICAL PUBLICATIONS- An up thrust for knowledge PUBLICATIONS- An up thrust for knowledge


TECHNICAL
1-88 Refreshing Java Scripla 1-89
Refreshing Java Script and CSS
a n c e d W e b P r o g r a m m i n g

han.
Advanced Web Programming

clicks the
button then as a n event
andler a
User
when the
user
function user rites
the
writes tho lef
this
instrucliong a
means
That
called. Basically in Item= e.currentTarget; Registering the mouse event
function My_fun) gets event. with
click parselnt(Item.style. left); the
the button help
need to be
e x e c u t e d on
events associated with DOM addEventListener function.
with an
. . . . . v a rp o s X

tonl

ofmouse
parseint(ltem.style.

Discuss the properties posY


=

Example 1.14.1 var posX;


-

e.clientX

eample. associated with DOM2 are cl. x offset= - posY;


events
offsete.clientY

Solution: Various types of


mouse
Y addEventListener('mousemove"', Move_function, truel:
mouseover.
document.addEventListener("mousen Drop_function, true):
mouseout and
mouseup,
Intrinsic event Meaning Associated tags e.stopPropagation();

Events
e.preventDefault();
attribute
When user clicks the left Form elements such as
mousedoWn onmousedoWn
mouse button. input,button, text, textarea and soO an
on.
function Move_functionfe)

When user releases the Form elements such as


(e.cientx -X_offset) + "px
mouseup onmouseup left mouse button. input,button,text, textarea and so on
Item.style.left=
= (e.cientY
-

Y_offset) + "px
Item.style.top
When user moves the Form elements such as e . s t o p P r o p a g a t i o n ( ) ;

mousemove onmousemove
mouse. input,button,text,textarea and so on
function Drop_functionfe)
When the user moves the form elements such as

mouseout onmouseout mouse away from some input,button,text, textarea and so on.
document.removeEventListener(mouseup", Drop_function, true);
element document.removeEventListener('mousemove, Move_function, true);
When the user moves the Form elements such as e.stopPropagation();

mouseover onmouseover mouse away over some input,button,text, textarea and so on.
element </script>
</head>
When user cicks the <a>
click onclick <body>
mouse button.
input <h3>
Click on image below-drag it, move it and then drop anywhere!!!
When user double clicks <a>

dbldick ondblclickk the mouse button. cbr/> <br/>


input>
<img src="lamp1.jpg
<button> style ="position: absolute;
Following is an example in which image can be dragged and dropped anywhere in the top: 100px;
HTML document. left: 100px
Accordingly the co-ordinates will be displayed. border:2px solid;"
html>
onmousedown = "Catch_function(event):"/>
<head>
title> Drag and Drop Demo</title> </h3
<script type </body>
=
"text/javascript"> </html>
var
X_offset, Y_offset, Item;
function Catch_function(e)

TECHNICAL PUBLICATIONS An
up thrust for knowledge TECHNICAL
PUBLICATIONS-An for knowledge
up thrust
c e dW e bP r o g r a m m i n g
91 Refreshing Java Script and CSS
90
Refreshing Java Schio A d v a n c e W e b

Output
A d v a n c e d W e bP r o g r a m m i n g

Output Demo of onload Tag Attibute - Windows Internet b x p e

Firefon

y
Dop
Dem
M a r i l a

nokmarks Jeos e

DvATG_Ei
DgDvopCnol\
G e D-Uavascript ErO xToggieEN CustP
g t e
fe

Vinted
Geting Serted
a
Ltet
Heedines

and
then drop
anjwhere!!! Favorites eSuggestedSites e Get MoreAdd-ons
Mot move"

drag i ,
Click on
image
belon
Demo of onload Tag Att...

Message from webp

Wekome

Events from the Body Elements


1.14.1 Handling let us put some Form compon.
events works in Javascript onents o OK
To understand how the web page gets loado
activated as soon as
the JavaSript.
The onload event gets inth
With its output illustrate the load t
onlas.

browser's window.
Following script along Mode Off 100%
Computer | Protected
attribute
JavaScripttonloadDemo.htm/]

-//w3C/DTD XHTML 1.0 Transitional//EN


<DOCTYPE html PUBLIC 1.15Eror Handling

that handles the runtime errors


htp://www.w.org/TR/xhtml1/DTD/xhtml11.dtd'
so
is a mechanism
handling
<html xmins ="http://www.w3org/1999/xhtml'>
Definition: Exception
can be maintained.
normal flow of the application
head that the of the program. It is
title>Demo of onload Tag Attibute </title>
an exception is an
event that disrupts the normal flow
KScnpt type="text/ javascript'> .Basically
runtime.
which is thrown at
function my_run() an object
in JavaScript can be performed with the help offollowing
The exception handling
/This message will be displayed on page loading
types ofstatements-
code for
lets you test a block of
errors.

1. The try statement


The catch statemernt lets you handle the error.
2.
aler(Welcome): statement lets you create custom errors.
3. The throw of the
When web document gets execute code, after try and catch, regardless
s/script> loaded on the browser window 4. The finally statement lets you
</head> then my_fun() will be called result.
<body onload ="my_fun0"> is
s/body> Basic syntax of try-catch block
K/html> try {
Block of code to try

catch(err) {
Block of code to handle errors

TECHNICAL PUBLICATIONS- An up thnust for knowedge


PUBLICATIONS- An up thrust for knowledge TECHNICAL
1 93
Advanced Web Programming 92
Refreshing Java Script and n c e dW e b P r o g r a m m i n g

Refreshing Java Script and CSS


When error occurs, JavaScript will normally throw an exception so that Output
that aprrOpriate
error message can be displayed and it will avoid a crash of a program. M o z i l a Firefox

Following example illustrates the exception handling mechanisnm in JavaSes


Eile Edit YView Higtory ookmarks Jools Help
<IDOCTYPE html> Id//ExceptionDemo1.htmi X +
<html>
<body> ) C file:///d://Exce »
<p>Enter Some Number:< /p>
Enter Some Number:

sinput id="demo" type=text>


button type="button onclick="GetPositiveNumber(">Click</button> Click
p id-"myiD"> </p>
Input is Negative
SCTpt
functionGetPositiveNumber()
var message, num

message =
document.getElementByld('myD"):
message.innerHTML = ";

num = document.getElementByid('demo").value;

try Mozilla Firefox


f ( u m = = ")

throw empty Eile Edit View History Bookmarks Jools Help


ifisNaN(num)) Id://ExceptionDemo 1.htm
throw 'not a
number"
... »
C file//d/xce
um = Number(num);

if(num < 0)
throw 'Negative":
if(num == 0) Enter Some Number
throw "Zero":

catch er) {
Cick
message.innerHTML = "Input is " + err;
Input is Zero

/sCript>
body>
</html>

hanulng
Example 1.15 to handle divide by zero error using exception
t e JavaScript
a

mechanism.

TECHNICAL PUBLICATIONS- An up thrust for knowledge PUBLICATIONS-An up thrust forknowiledge


ECHNICAL
1-94 Refreshing Java Script c e dW e b P r O g / a m m i n g 1 95
Refreshing Java Script and CSS
Advanced WebProgramming and C AOVa

Output
Solution:
<IDOCTYPE html> Mozilla Firefox
chtml> EileEdit View Higtory Bookmarks Jools Help
<body>
<p>Enter Some Number: </p> /d://ExceptionDemo1.html x
<input id='numerator type="text>
input id="denominator type="text'>

<button type= "button'


onclick= "divide()'>Click</button>
E C file/d// .. »
<p id="myD"> </p>
Enter Some Number:
<script>
function divide() { 0
10
var n,result, message, num;
message = document.getElementByld('myID"):

message.innerHTML = " Eror: Divide By Zero!!!


d document getElementByld('denominator").value;
try
ifd=")
throw 'empty';
ifisNaN(d))
throw 'not a number:
num = Number(d);
Mozilla Firefox x
f(num ==0)
throw 'Divide By Zero!l"; File Edit View Hi_tory Bookmarks Iools Help
else
/d://ExceptionDemo1.htm x
+
n = document.getElementByld("'numerator).value;//obtaining numerator

n=Number(n);//converting text string to number


C file//d://t
ans=n/num;//performing division
message.innerHTML = "+ans;
Enter Some Number:

catch(er)
10 2 Click
nessage.innerHTML = "Error:" + e r

/script>
<body>
</html>

1.16 Validators
are callea
control objects
OuS control objects are placed on the form. These

widgets.
TECHNICAL PUBLICATIONS An up thrust for An up thrust for knowledge
knowledge TECHNICAL
PUBLICATIONS-
Advanced Web Programming
1-96 efreshing Java Script ang AdvancedW e b Programming
1-97
used in JavaScript are Textbox, Push button, Radi bultun, password Refreshing Java Script and CSS
These widgets abel>
Enter your

Checkbox and so on. pe="password value" id="pwd" />


<inpui

In JavaScript task.
the validation of these widgets is an important </labels

elements with the help of examnla < b r / >< b r / >

Let us understand the validation of form les- Re-Enter the


password
<label>
Example 1.16.1 Write a JaraScript for passuword verification <input type=p
password" value="
id=re_pwd' onblur="my fun();'/>
</Nlabel> < b r / >

Solution: < i n p u t t y p e = ' s u b r


itl yalue "Submit' name="submit'
<IDOCTYPE htmi> <input type="reset" vaue="Reset" name="reset'/> <br/> onsubmit='my fun()}"/>
<html>
S / f o r m >

shead < / c e n t e r >

<title> Demo of onlclick Tag Attibute </title>


/body>

Script type="text/javascript">
/html
function my_fun()

Output(Run1)
var mypwd=document.getElementByld('pwd");
( A Demo of onlclick Tag Attibute - Windows Internet Explorer
var
my re pwd=document.getElementByld('te_pwd'
if(mypwd.value= =") efile///D:/JavaScript Ex/TetDemol.htmli? XP ToggleEN Custh P
File Edit View Favonites Tools Help

alert You have not entered the password') Favorites eSuggested Stes e Get MoreAdd-ons

mypwd.focus(): Demo of onlclick Tag Atibute Page Satety


retum false;
Enter your password eeseeeseesee

if(mypwd.valuel =my_re_pwd.value) Re-Enter the password 00ee


Submit Reset
alert('Password is not verified, Re-enter both the passwords");
mypwd.focus();
mypwd.select(); Message from webpage
retum false;

Password is not verified, Re-enter both the passwords


else Compute

OK
alert('Congratulations!!l")
return true

/script
</head>

<body
Scenter>
<form id="form1">

up thrust forknowileoge
TECHNICAL PUBLICATIONS An up thrust for knowledge ECHNICAL
P U B L I C A T I O N S - A n
Refreshing Java Scripta AdvancedW e bP r o g r a m m i n - 99

Refreshing Java Script and CSS


1-98 and Css
Advanced Web Programming
f u n c t i o n v a l i d a t e ( )

OutputRun2)

3
Internet
Explorer

Cust
Windows

X Pioggie¬N
Attbute-

of onklick Tag
Demo
ele///aasciptTetDemol.htm

Favontes Toos Help


Add-ons var 1
File Gt More
Sites e Page
Frvortes
sSug9ested Sefety ar name str=document.my_form.name:

Demo of onlclick
Tag
Attibute

phonelD=document.my_ form.ph txt:


ar
Enter your password
var ph str=document.my_form.ph_txt.valu

Re-Enter the password eeeee var str=document.nmy_torm.Email txt.value


S u b m iReset
if(name_str.value==null)||(namestr.value= =")

Message from webpage


alert(Enter some name") Validating Name
You have not entered the password retum false

Computer P
if(document.my_torm.Age txt.value==")//validating
age

Some Age")
alert( Enter
return false

Output(Run3)

Demo of onlclick Tag Attibute Windows Internet Explorer if(document.my_form.Age txt.value<'5")&8&(document.my_form.Age_txt.value> "21'))
P
G
file//DlavaScript,Eu/TetDemol.htm7||x|l|P Toggie£N Cust
Fle tn_ Ve Favontes oolsHelp
alert("Invalid Age")
Fvortes e Suggested Stes Get More Add-ons
Demo of onlclick Tag Atibute 6 Page Safety retun false

Enter your password * * * * * e * *

Re-Ente the password e °° 9*

SubmitReset if(ph_str.length<1 ||ph_str.length>11)

L
Message from webpage

alert("Invalid length of Phone Number) Validating Phone Number


Congretulations!!!
return false
Computer |Pro 100%

OK for(i 0; i< ph_str.length; i+ +)

Example 1.16.2 Write JavaScript to validate afor consisting of Name, Age, Address, Emau
var ch ph_str.charAt(i);
hobby (check box), Genderradio box), country(Drop down menu). if(ch<0) | (ch > "9")»
Solution: ApplicationForm.htm
alert("Invalid Phone Number)
<html>

<head>

<title> The Student Registration Form /title> phoneID.focus()


return false
<Script type=text/javascript>

TECHNICAL PUBLICATIONS An up thrust for


PUBLICATIONS-An up
thrust forknowledge
knowledge TECHNICAL
Advanced Web Programming 1-100 Refreshing Java Script: Advancea
ced Web Proo
Web Programmin9
1-101
return false; Refreshing Java Script and CSS
return true
var index_at=str.indexOf"@)
var len=str.length
var index_dot=str.indexOf(".)
var emaillD=document.my_form.Email_txt
< / s c r i p t >

if ((emailD.value==null)||(emaillD.value= ="))
< / h e a d >

Validating Email ID c b o d y b g c o l o r = a q u a >

<center> <h3>4 >Application </h3></center>


alert('Please Enter your Email ID') <form name=my_form onsubmit=validate()>
<strong> Name: </strong>
emaillD.focus()
name=name> <br/>
return false cinput type=text

<strong> Age: </strong>


if (str.indexOf"@")==-1)
<input type=text name=Age_txt>
<br/>
{ <strong>Phone No:</strong>
alert("Invalid E-mail ID") name =ph_txt> <br/>
<input type=text
return false
<strong>Email: </strong>
<input type=text name=Email_txt> <br/> <br/>
if(str.indexOf(":")==-1 || str.indexO".")= =0 <strong> Sex: </strong>
I str.indexofr")= =index_at)
<input type='racio" name="group1" value="Male'>Male
alert("Invalid E-mail ID)
<input type-"radio" name="group1' value="Female">Female<br/> <br/>
<br/>
<strong>Hoby: </strong>
retum false
Validating Email ID <input type="checkbox" name ="option1" value="Singing'>
Singing<br/>
<input type="checkbox" name ="'option1"
value="Reading"> Reading<br/>
if(str.indexOf"®.(index_at +1) =-1)
<input type="checkbox' name="'option1" value="T.V.">Watching T.V<br/>
<br/> <br/>

alert('Invalid E-mail ID")


<strong> Country:</strong>
<select name= "My_Menu'>
returm false
<option vaue= "India">India</option>
<option value="China'>China</option>
if(str.indexo("")=-1) soption value="Shrilanka"> Shrilanka</option>
s/select>
alert("Invalid E-mail ID") <center >
retum false
<input type=submit
value=Submit> </br>
</center>
f (document.my_form.group1[0].checked &&
ldocument.my_form.group1|0].checkea) </body>
alert("Please Select Sex" s/html>
retum false

aocument.my_form.group10).checked && ldocument.my_form.group1|0].checKea


slert(Please Select Sex')

TECHNICAL PUBLICATIONS- An up thrust for knowledge TECHNICAL PUBLICATIONS-An up thrust for knowledge
Advanced Web Programming
1-102 Refreshing Java Script 9 dWeb PrOgrammin9
1-103
and
SCss Advancea

Refreshing Java Script and CSS


alert("Valid u s e r n a m e " ) ;
Output

Explorer
The Student Registration Fom-Windows intenet
P eysieENCust P - |
O le 0ApplicationFom.htm
a s s . v a l u e = = p a s s w o r d " )

S Favonts The Student Registratio Page alert("Valid password");

Application Form
else
alert("Invalid u s e m a m e / p a s s w o r d " )
Name:
10
Age:
Phone No: 01011111111
Emai: abc@pa com </script>

/ h e a d >

ex Male Female
<body>

id="formi name
1ormi onsubmit=validate()>
cfom
Hoby: Smging Message from wetbpage width="510 border="0 align="center
Reading ctable
<tr> <td>Username:</td>

Waching TV
Enter some namee <td> <input type="text name=usemame"/></td
County China </tr>
<tr> <td>Password </td>
Subm OK <td> <input type="password" name="password'/> </td>
Computer | Protected Mode Off
</tr>
Example 1.16.3 Designa HTML form for validation the users with fields user name and <tr>
<td>&nbsp;</td>
password and ok button which should receive the input from the user and responses as
<td> <input type'submit name="button" value ="0K" /></td>
authorized or invalid user name or invalid password. </tr>
Solution: s/table>

</form>
head </body>
stitle>HTML PORM</title>
S/html>
<script type=text/javascript
function validate()
Example 1.16.4 Write a Javascript to validate radio button, operatorfield and check box.
var user=document.form1.usermame; Solution:
var pass=document.form1.password; JavaScript Program
html>
if(user.vaue==null)||(user.value==") head>
alert("Enter some user name") Script LANGUAGE="JavaScript'>

ction ValidateForm(form)
if(pass.value==null)||(pass.value==")) Validating Radio Button

alert(Enter some password"); "


false ))
(form.gender[0].checked
1alert ("Please choose your Gender: Male or Female"
=
false) &&(1
(form.gender[1].checked
==

returm false;
iffuser.value=="admin")
TECHNICAL PUBLICATIONS-An up ECHNICAL
PUBLICATIONS-An up thrust for knowedg9
thrust for knowledge
104
Refreshing Java Script c e dW e b P r o g r a m m i n g g
1-1105
Refreshing Java Script and CSS
ar
Advanced Web P o g r a m n g
Asynchroon
ronous Programmin

Validaling Checkbox
Introduction
AX
to AJAX

17.1
checked
= =

false ))
Yis a
Asynchronous Java Script and XMI.
fom status|1]
false )&& (
status|01.checked ==
f (form choice. AC o non AC
youi Here
Please choose
i alert ( nchronous means, the execution of script does not disturb the user s work.
retum false
Validating Oplion o
because, it makes useof Javascripting to do the actual work
selectedIndex
=0) lavaScript
1f( form oourse XML ecause along with Script the XML is also supported to perform the given
alertFlease select Some Course
Tetun falise task in AJAX
nof a new programming language but it is a kind of web document which
Tetun trie It is
adopts certain standards.

/sCTpt AJA.
allows the develo to exchange the data with the server and updates the
head>
document without reloading the web page.
<body> part of web
bt 1.17.2 A r c h i t e c t u r e

<form>
name='gender' value ="Male"> Male for the
Your Gender: <input type= "radio .When user makes a request, the browser creates a object HttpRequest and a

input type='radio name= "gender' value=


"Female"> Female internet.
request is made to the server over an

<bI
Choice <nput type= checkbox name ="status >AC . The Server processes this request and sends the required data to the browser.
inpui type= "checkbox' "status'> Non AC
browser side the returned data is processed using JavaScript and the web
name=
At the
document gets updated accordingly by sending the appropriate response
Course.
<Select name= cOurse >> Following Fig. 1.17.1 illustrates this working.
<option value=">Select an Option.</option>
<option vaue="Computer >Computer</option>
Koption valhue="Mechanical' >Mechanical </option> Web browser
Koption value="E&Tc > E&Te</option> Server
1) User makes a request
/seiect> Request 4) Processes the Http request.
br/><bI/> 2) XMLHttp request object Intermet
<nput type= "button' name="SubmitButton' value="Submit" is created 5) Create a response and send
onCick="ValidateF om(this form)> 3) Sends Http Response data to browser
input type="reset value = "Reset">
request Intemet
</form 6) Processes the returned data.
</body> 7) Update web document.
</html>

Fig. 1.17.1 Working of AJAX

TECHNICAL PUBLICATIONS- An up thrust tor


knowledge
TECHNICAL PUBLICATIONS An up thrust for knowledge
1-107
Refreshing Java Script
Web Programming
Advanced
WebProa

Advanced Web Programming 1-106


and Css Client Refreshing Java Script and
HTTP request Server CSS
Similarities and Differences
Ajax Based Web Application
GUI HTML +CSS
Data
Server
side
Sr.No. Traditional Web Application Architecture proce ssing
Architecture HTTP response

1 The web applications architectures are based on Hl request response protocol Fig. 1.17.21
Traditional web application
col. architectur
cture

At the client side the browser Client


2. At the client side the browser client has client
user interface and AJAX has Server
one component and that is Engine due to
user -

only
interface. which the client gets quick GUI
the server.
response fromm

HTML
The architecture is based on client server communication.
3. Javascrip
call
css Server
side
Data
processing
4 t makes use of synchronous By adding a new
layer of AJAX Engine at
communication. The client has to wait to the client side, it eliminates the HTTPrequest
start-stop- AJAX
XML Data
get the response from the server then start-stop nature of communication and engine
only client can make the request to the makes the communication asynchronous.
server. It is start-stop-start-stop kind of HTTP response
communication.
Fig. 1.17.3 AJAX web application architecture

5. With traditional web application With AJAX architecture user gets rich
Merits of AJAX
architecture user cannot get rich user user interface experience.
1. Response time
is faster, hence increases performance and speed.
interface experience.
call asynchronous requestHTTP to the Server for
2. XMLHttpRequest object as a

to the non-Ajax pages.


6. It is less responsive. It is more responsive.
transferring data both side. It's used for making requests
3. It is used in form validation.
Building web application is simple, The development time is more while
from database and storing of data into database
designing the Ajax based web application. 4. It performs fetching of data
CSS and
without reloading page.
Extensive use of JavaScript,
8. Limited use of JavaScript, CSS and XML
XML
technologies. In fact Most user actions Demerits of AJAX
in the interface trigger an HTTP request i)standards-based presentation using
1. It has browsing compatibility issues.
back to a web server. XHTML and CSS;

ii) Dynamic display and interaction using tis impossible to bookmark AJAX updated pagecontents. Engines
the Document Object Model(DOM): content. Hence, Search
Search engine would not craw AJAX generated
iii) Data interchange and manipulation
like Google cannot index AJAX pages.
using XML and XSLT
I) Asynchronous data
retrieval using
XMLHttpRequest;
1173 XMLHttpRequest Object
e

v)JavaScript binding everything togethe


element other
AMLHttpRequest object is an important JavaScript,
VBScript
and some

used by
AMLHttpRequest is an API which is
sCripting languages.
PUBLICATIONS.
An up thrustforknowleug
ECHNICAL
TECHNICAL PUBLICATIONSAn up thrust for krnowledge
1 108 Refreshing Java 1- 109
Advanced Web Programming
are used in Aata
transferring data
Scrip and Cs
bet.
W e b P r o g r a m m i n g

A O V a n c e dW e b

Refreshing Java Scnpt airu


T h e methods of XMLHttpRequest
browser and a web server.
between Weh a
Returns the status number.
returned by the status property
Following i the
meaning of various numbers
status

It is because of XMLHtpRequest object, to update parts Neb npage withou


of weh
200: "OK"

reloading the whole page. 403: "Forbidden"

Syntax 404: "Not Found"


Variable new XMLHttpRequest(0:
Returns the status text as "OK", or "Forbidden"
Various Methods of XMLHttpRequest object statusText

derstand how AJAX


works with the help of
Method Purpose
Let ur programming example
<html>

new XMLHttpRequest0 Creates new XMLHtpRequest object. <head>


<SCript t y p e = t e x t / j a v a s c r i p t " >

Open(method, URL, asyncuser,pwd) To make request this method is used.


function MyFun()

method: The request can be GET or POST


if (window.XMLHttpRequest)
URL: The location of file

async: true(for asynchronous) and


false(synchronous) req-new XMLHttpRequest(0:

user: user name(optional)

else
pwd:password(optional)
send) sends the request to the server. req=new ActiveXObject("Microsoft.req):

send(string) sends the request to the server.


req.onreadystatechange=function()
setRequestHeader0 Adds the label- value pair to the header.
if(req.readyState==4 && req.status==200)
Various Properties of XMLHttpRequest object
document.getElementByld('my1D").innerHTML =req.responseText;
Property Description
readyState Speifies the ready state of XMLHttpRequest reg.open(GET "newdata.txt',true);
req.send()
0: request not initialized

1: server connection established s/script>


(
2: request received s/head
3: processing request
body>
div
wld="myID">This text can be changed</div?
4: request finished and response is
ready
onreadystatechange When readystate property changes the ill
pebutton" onclick="MyFun(">Change</button
s/body>
be automatically invoked onreadystatechange event istente ntml>
responseText Returns the response data as a
string

TECHNICAL PUBLICATIONS-An
up thrust
for knowledge forknowleoge
PUBLICATIONS-An up thrust
ECHNICAL
1-111
freshing Java Script AdvancedW e bP r o a
c e dW e b P r o g r a m m i n g

Advanced Web Programming


1-110 Refreshing JavaScript and CSS
and (. sA method sends the request to the server.
explained here)
5 . T h e s e n d ) ,

Script Explanation (Above


numbered steps are
Output
In abovescript, we have written some text which can be ced by
replaced by some.
some
on button click.
another te
/d/AjarDeme X Id/AjaDerm x + X
1. On button click a function MyFun is invoked. Thus cdient triggers the ent. C
fie://d/AjaxDemo.h

2. XMLHtpRequest object is used to exchange data with


a server. This
obiect. file:////Aja«Demo.ht
the user to change/update the parts of the web page without reloading it fultallows
moden web browsers such as IE7+, FireFox,Chrome have h
iully. AJAXDEMO
AJAX DEMO
built
XMLHttpRequest but old web browsers make use of ActiveXObject.
Welcome Ajax simply loads the required data
3. When a request to a server is sent, thenonreadystatechange event is triggered without loading the entire Web
page
Change
The readyState property holds the status of the XMLHttpRequest. The
readystates Change
means request is finished and response is ready. The status 200 means "OK" =

The DOM is modified and response is modified using the statement

document.getElement Byid(myID").innerHTML=req.responseText;
4. The request can be sent to the server by using two functions open() and send(.
reg.open'GET,'newdata.txt',true); Write AJAX script to obtain the student information stored in XML
amgle 1.17.1
Location document. The information should be displayed
on clicking the button. It should be displayed in
GET or POST of file on true means asynchronous
method server false means asynchronous tabular form.
Solution:
Asynchronous communication allows fast processing of the data.
the student information. The XML file is as follows
The newdata.bxt file contains some updating text using which our web page can be Step 1: Create an XML file for storing
updated Student.xml
newdata.txt Student
<student_data>
newdata Notepad X <Name> AAA</Name>
<Marks>45</Marks>>
Eile Edit Format View Help S/student_data>
ch3>Ajax simply loads the required student_data>
data without loading the entire Web <Name>BBB</Name>
page/h3 <Marks> 55</Marks>
S/student_data>
student_data>
<Name>CcC</Name>
Marks>67</Marks
/student data>
student data>
<Name>DDD</Name>
Marks>84</Marks>
TECHNICAL PUBLICATIONS- An up thrust for knowledge An up
thrust forknowed9
PUBLICATIONS
ECHNICAL
Advanced Web Programing
1- 112
Refreshing Java Script AdVanCed
W e bP r o g r a m m i n g
W e bP r o g r a n

1-113
a
Refreshing Java Script and CSS
</student_ data>
<Reripts
</Student>
as follows -

A]AN sript
</pody>

Create a
Step 2: <htmls
browser and
web bro
the w e b the output will be
AjaxXMLDemo.html
step3:
Open as
follows-
IDOCTYP html>

<html d/AjaXMLDemo.htm
<body>
<h1>STUDENT INFORMATION</h1> file:///d/Aja C Search
<button type= "button oncick= "MyFun() >Cick</button
>>

<br> <br >

<table border = "1' 1d-"demo></table>


KSCnpt >

function MyFun()
STUDENT INFORMATION
Clidk
var xhttp =
new
XMLHttpRequest()
xhttp onreadyststechange = function()

f (this.readyState = =4 && this.status == 200)

Load_XML_File(this);
button will get
On clicking the we

xhttp.open("GET, "Student xml', true);


xhttp.send(); Id/Ajax0MLDemo.htmi x +
function Load_XML_File(xml) file://d:/Ajax C Search

var 1

var XmlDoc =

XmlIresponseXML;
STUDENT INFORMATION
var table='<tr> <th>Name </th>
<th> Marks </th> </tr>";
var z
xmIDoc.getElementsByTagName ("student_data'); Cick
=

for (i =

0 <x.length;
i
it+)

table Name Marks


+=
'<tr> <td>"+
AAA 415
x{il.getElementsByTagName("Name")10].childNodes|
</td> <td>' +
0].nodeValue + BBB 55
z{il.getElementsByTagName(Marks")10].childNodes|0].nodeValue+
'</td> </tr>;
CCC 67
DDD 84
document.getElementByld('demo"). innerHTML =table;

TECHNICAL PUBLICATIONS An up thrust for knowledge TECHNICAL


PUBLICATIONS- thrust for knowledge
An up
1-114 Refreshing Java Script
and çe
Advanced Web Programming

R e v i e wQ u e s t i o n s

the merits
and
demerits
ofusing AJAx
Explain andmethods
What is AJAX? with its properties
1. object along
Explain
XMLHIpRequest

in detail. Introduction to Angular JS


2.
2 architecture

AJAX
Explain

Syllabus

senhax of Angular J5, keatures, Advantages, Application Structure, Basics of


Basics a n d Syntax
MVC
V with Angular JS, Services.
navigation,
and
routes

Contents

Js

2.1
Basics ofAngular
22 Features

Disadvantages
and
Advantages
2.3
24 Application Structure

Angular JJS
MVC with
25
and Navigation
Basics of Routes
26

2.7 Expression

28 Controller

29 Scope
2.10 Services

(2-1)
TECHNICAL PUBLICATIONSAn up thrust for knowledge
Advanced Web Programming 2-2 2-3
Introduction to AngularJS
n c e d W e bP r o g r a m m i n g

A d v a n c e d W e bP

ts It is more
ntuitive
intui as it makes use of
Introduction to Angular JS
2.1 Basics of Angular JS Intuitive-

it is less brittle for HTML as a


Moreover.

reorganizing. declarative language.


Angular JS is a powerful JavaScript framework. Comprehensive
Angular]S is a
comprehensive
I t is an open source front-end enabled web application framework. 4. evelopment. Itdoes
do not need any other solution for
plugins or rap
rapid front-end
ride range of
Therei frameworks.
It is licensed under Apache license version 2.0.
5. Rich
features: features
supported by Angular ]S such
I t extends HTML DOM with additional attributes. It is more binding, endency injection, enterprise level as
responsiva Data
The AngularJS code is unit
testing and so on.
o
actions. testable.
6. Unit testing:
2.2 Features ble code: Angular JS support for using the reusable
support for less code and more components.
There are core features Angular JS that are widely used by web developers. Thesa 6. Less
code: It functionality.
1. Data are
binding : It allows the automatic
synchronization between model and Disadvantages

components.
vio
view JS is based on Javascript framework, it is not secure.
1. As Angular
2. There are multiple ways to do the same thing with AngularjS. Sometin
Scope: There are some objects from model that can be correlated
view.
to controller and to which way is better for
hard for novices say a task.
3. Controller: These are
basically JavaScript functions that are bound to particular Review Question
scope
4. Directives: The directives is 1. Explain different advantages
and disadvantages of Angular JS.
designed to give HTML new functionality.
5. Filters: This feature allows to
select subset from array 2.4 Application Structure
6. Routing: This feature allows to
of items.
switch between multiple ews. I n Angular JS, the capacity of HTML is extended using the ng-directives.
7. Services: There is a
support for many built in services for Angular JS. The directives are specified with ng prefix.
8.
Dependency injection: It is software design pattern
a
that helps the The three commonly used ng-directives are
develop and understand the application easily. developer to
1. ng-app : This directive defines an Angular]S application.
Review Question directive binds the value of HTML controls
to application data
2. ng-model This
input, select, textarea and so
on.
These controls can be
1. Enlist the features of angular JS.
to HTML view.
3. ng-bind: This directive binds application data
2.3 Advantages and Disadvantages Ler us now learn and understand how develop Angular JS application.
to
extension
Save it using the
Advantages p Create an Angular JS code as follows in a Notepad.

Following are the advantages of Angular JS .htm or .html


1. Built by Google
engineers: The Angular JS is maintained by dedicated Googe AngularJS Document[FirstApp.htm]
Engineers. That means there is huge community for development and <html>
enhancement. shead>
2. MVC 8/a]ax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.minjs
ude My First AngularJS Application </title s/scg
support - It is based model view controller
on
(MVC) architecture
vhich
Ws
script src
provides separation of model, view and controller
=
"https://ajax.o
components. </head>

TECHNICAL up thrust for knowledge


PUBLICATIONS-An up thrust for knowledge ECHNICAL
PUBLICATIONS-An
1W e bP
Prro
oggr
raam
mm i n g 2-5
tntroduction to Angular Js
AdancedeD

2-4 Introducton to Angular JS


Advanced Web Programming Wecanbind the value
np-bind:
entered in the
<body Defining textbox with
<h1>AngularJS Application</h1>
n p - b i n dd i r e c t i v e .

name using
n > W e l c o m es p a nn g - b i n d = "name'> </span> </p>
<div ng-app = ">
= "name'> </p>
ng-model
p>Enter your Name: <input
type "text' =
see on
the output screenshot, that
'name"> </span> </p> Hence we
can
whatever name
Sp>Welcome <span ng-bind
with the
Welcom message. entered user
s/div> nd
be viewed
by opening any
output can
</body> The
above

JRL of corresponding Angular|S script


popular web browser
and by
</html> entering
t h eU R I
Output
Angular Js
with
OX MVC
My First Angulr X+ 25
ConceptofMVc
File:/d:/FirstApp.htm for
stands for Model, view and controller. It is a
pattern for the architectural
TheMVC

framework.
It consists of three parts-
AngularJS Application 1. Model: This part of the architecture is responsible for managing the application
ata, This module responds to the request made from view. The model eives
data.
Enter your Name: Mr.XYZ instructions to controller
to update when the response is made.
,View: This part takes care of the presentation of data. The data is presented in
Welcome MrXYZ
desired format with the help of view. This is a script based system using JSP, ASP,

PHP and so on.

3. Controller: The controller receives input, validates it, and then performsbusiness
that modify the state of the data model. The controller basically
operations
responds to user request and performs interaction with model. Refer Fig. 2.5.1.
Script Explanation Event
1. The AngularjS script is written within <html>
tags. The Angualar|S is based on
JavaScript framework. The framework for Angular]S is loaded using the <scripb
Controller
tag. It is as follows -

script sre =

"https://ajax.googleapis.com/ajax/ibs/angularjs/1.3.14/angular.minjs"> s/script
2. Defining np-app directive: The np-app directive is defined in above script as View Model
follows
Fig. 2.5.1 MVC archltecture
<div ng-app
MVC in
Angular JS
apPPlication
serve as containers
to help you organize your
/div guarjS
into logical units.
3. Defining np-model directive: The textbox control is modeled using nodel

directive
np-i Modules tellAngular}S how an application is configured.
directive cng-app>
and module
sp Enter your Name: <input type =
"text' ng-model ='name'>
In an angular JS the Module are represented using the
</p>
name.

TECHNICAL PUBLICATIONS An up thrust


for knowledge ECHNICAL PUBLICA
TIONS®- An up thrust forknoweage
2-7
Introduction to Angula
A d v a n cW
e e bP o g r a m m i n g

Advanced Web Programming 2-6


controller. 7 Expression
Introduction to Angular JS
T h e scope object binds the view with
I n Angular]S it is possible to have multiple views for single page applicatiom ,In Angular/S the
xpressiorns are written within
| }. For
the concept
The ng-view and ng-template and ng-route directives support the
concept view
of
( 2 4 3 / ) i s e x p r e s s i o n .

example
is to control the flow of data. The
he no..
ng-controller binds data to HTML using Expressions.
The use
of controller in Angular]S A n g u l a r S

directive is used for this purpose. Refer Fig. 2.5.2. solves the expressio and return the
A n g u l a r
result of evaluatio
ressions in Angu lar]S are just similar to
Module
<html ng-app= "module_name"> The expression conta ontains literals, variables and operators. JavaScript expressions. The

Document[Expression
ionDemo.htm]
A n g u l a r J s

pOCTYPE h t m l >

Config
chtml>
STC="https://ajax.googleapis.com/ajax/libs/anm js'> </script>

Routes cbody>

<div n g - a p p =

ch4>Expression Demo</h4>

n> Addition of 10 and


20= {{ 10+20}}</p>
Views Scope Controller K/div

</body>
Directive Services
/html
Fig. 2.5.2 MVC with angular JS Output

Review Question X

1. Explain the concept of MVC. How the MVC architecture is applicable in Angular J$?
/d:/ExpressionDe X+
2.6 Basics of Routes and Navigation file:///d:/ExpressionDem
Routing and navigation is one of the core feature in Angular]S.
Expression Demo
The #route is used for deep linking of URLs to controllers and views
W e have to download angular-route.js script that contains the ngRoute modu
Addition of 10 and 20 30
from Angular|S official website to use the routing feature. Alternatively we canals
use the CDN in our application to include this file. The CDN can be
htps://ajax.googleapis.com/ajax/libs/angularis/1.2.28/angular-route.min.js
Then load the ngRoute module in the
Angular]S application by addingitas
dependent module as shown below.
angular.module('appName. ('ngRoute ])
Then using ngView directive we can display the contents at specific routes
We will discuss the
implementation of routes and navigation in the next chapte

TECHNICAL PUBLICATIONS- An up thrust for knowledge


thrust for knowledge
ECHNICAL PUBLICATIONS®- An up
aming 2-9
Introduction to Angula
a n c e dW e b P r o g r a m m n

Advanced Web Programming 2-8


qular Js Output Introduction to Angular JS
ng-app directive then the expressiion won'tbe
Now from above code if we remove

evaluated. Forinstance-
I:/ + v
instance

<body file:///d:/Express C
<div Expression Demo
<h4>Expression Demo </h4>
}}</p>
Expression Demo
{{ 10+20
sp> Addition of 10 and 20 Addition of 10 and 20
{{10+2011
=

/div>
</body>
s/htmi> First Two names are: AAA , BBB
assign the values to variables and then evaluate an
We can
For
expression. This
initialization of variable can be using ng-init. example -

<IDOCTYPE html>

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min js'></scripts
<body>
2 8 Controller
<div ng-app=" ng-init ="a=10;:b=20">
<h4>Expression Demo</h4> .Controllers are basically the JavaScript objects These objects contain the application
<p> Addition = {{ a+b }}</p>
p > Multiplication = {{ a*b }}</p>
logic.
/div>
, The controller are normally deined as a
part of angular module. The angular
</body> module is created as follows -

s/html> var app angular.module("Test".0);


Output Here the parameter Test refers to an HTML element in which the application will
The output will be displayed as 30 and 200
run.
Similarly we can assign strings to variables and can display them. For example
We can add the controller to this angular module. This controller can be referred
AngularJS Document[ExpressionDemo1.html] using ng-controller directive.
<html>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<IDOCTYPE html>

<body> html>
<h1>Expression Demo</h1>
head>
d i v ng-app = " ng-init = "names = {first AAA',second 'BBB',third:'CCC}">
tpt
<p>First Two names are: {{names.first+""+ names.second}}</p
srC"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angularmin.jg' </scnp
s/div> SCript type ="text/javascript'> created
The Test module is
s/body ar app angular.module("Test'.1)
</html> controller is
Inside the module, the
is
9p.controller('student", function() Created.

student
The n a m e of
the controller

TECHNICAL PUBLICATIONS- An up thrust for knovwledge ECHNICAL


PUBLICATIONS- An up thrust for knowledge
Advanced Web Programming 2-10
Introduction to Angqui ancodW e bP O g r a m m i n g
2-11
this.Name ="Chitra'
ngular s This
p a r tshow that the controller has modelled. It is Introduction to Angular JS
Only one member of the controller. View
pp "Test" ng-controll oller="student as s'> as
given below
This member has a name as Name e b o dn
yg - a p p

W e l c o m e1 t s . N a m e } }

</script>
</head> /pody
oller with properties, methods and
external files.
Controller with Properties

body ng-app =
"Test ng-controller="student as s'> dofined wi
is defined with properties. Ihese
The
controller
properties are then
assigrned with
Welcome f{s.Name}} It is illustrated by following example
The controller is
refered by
controller.
s o m e

An instance
</body> s is named rJS Document[ControllerDemo.htm

created for reterring the


the controller.
members of
</html> DOCTYPEhtml>

leiax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.minjs'> </script>
<html>

Displaying the value represented(modeled) by the controller on web browser


<hody>

Output pp="MyApp" ontroller="MyControllerr>


cdiv ng-app

Ox ng-model=user"> <br/> <br/>


controllerDemo.html User: <inputtype="text ng-model="city"> <br/>
City: <inputtype= "text
oFile Champp/htdocs/angula. br/>

User{(user +}lives
in city {{ city + "I!l"}}
Welcome Chitra
</div>

KSCript>
varapp angular.module(MyApp, O;
app.controller(MyController, function($scope)
Program Explanation: The comments given at the each important coding statement Sscope.user = "AAA";
provides the detailed
insight of the controller. But you Sscope.city = "Pune Properties
can map the analogy 0
MVC(Model View Controller) here as follows
Model and Controller: The controller can be considered as a collection of meme lt /script>
s/body>
is given as follows - S html>

app.controller('student', function()(
this.Name = "Chitra"; Controller

Modelling the member

TECHNICAL
PUBLICATIONS An up thrust for
knowledge PUBLICATIONS-An up thrust forknowledge
ECHNICAL
Advanced Web Programming 2-12 2-13
ntroduction to Angu'a
o n c e d W e bP r o g r a m m i n g

Address:(faddress_function011
Output Introduction to Angular JS
/div

<script>

I);
angular.module (MyApp,
-
apPerCMyController, function($scope) {
file/Id/Contre C
Sscope.user "AAA Properties
Sscope.city= Pune
User: AAA
.address function=function()t
lives
Method definition
return
$ s c o p e . u s e r

incity+Sscope.city:
City: Pune
User AAA lives in city Pune!! < / s c r i p t >

</body>

/htm
Output

Script Explanation: DX
In above script,
x +
1. we have used two directives div-app and div-controller which file:/n/Contro C
are defined wi
some suitable attribute name. In above case div-app attribute is "MyApp" and User: AAA
div-controller attribute is "MyController".
2. The MyController function is basically a JavaScript function and Angular|S wil City:Pune
invoke the controller using Sscope object.
3. The controller creates two Address: AAA lives in city Pune
properties namely 'user and 'city'. Using Sscopeobjet
these properties are assigned with values 'AAA' and Pune'
4. The ng-model binds these the input fields to the controller properties.
Controller with Method
ScriptExplanation:
In above script the controller have two properties. But we can define a method for the In above script
controller. Following example illustrates how to use controller method. method named
defined. Along with them,
a
ne two properties user and city are
AngularJS Document{ControllerMethodDemo.htm Address_function) is invoked.
IDOCTYPE htmi>
has function returns the string containing
values to the properties.
chtml>
This function is then bounded to HTML
sCript stc="http://ajax.googleapis.com/ajax/ibs/angularjs/1.3.14/angular.minjs'> </scTpt
File
<body Controller with extermal
be then
file. This file
can
cdiv
ng-app="MyApp ng-controller="MyController We can write and controller in some
external
User: cinput type="text ng-model='user> <br/> <br/> save the
City: input type="text ng-model="city><br/> invoked in the HTML ment. Here is the
illustration.

<br/>

TECHNICAL PUBLICATIONS-An up
thrust
forknowledge
up thrust for knowtedge ECHNICAL
PUBLICATIONS-An
2-114 2-15
Introduction to Angular
Advancod
Web Programming

Advanced Web Programming

Step 1:Create afile in Notepad.


Name it with extension.js. ar JS
2 9S c o p e
Introduction to Angular JS
is an object that binds the HTML
with
External File[MyController.js]
angular.module("MyApp, ).controller(MyController, function($scope)
The
Scope

nds view with controller. The view


part
is
JavaScript. In other words
$scope.user = "AAA controllerparti s tten as Javaacript. normally written in HTML and
Sscope.city = "Pune";
the use of scope object with the
help of illustrative
u n d e r s t a n d

Sscope.address_function=function(){
Letus example
retum $scope.user+""+$scope.city: AngulardsDocument[ScopeDemo.html

<html>

Step 2:Create a HTML document invoking the external js file ted nin ahaue
created <body "MyApp" ng-control =
"MyController>
above step.
<div ng-aPp p=

<p>Message: {{message}} />Color: {{colorname}} </p>


HTML Document[ControllerFileDemo.htm]
<IDOCTYPB html> <div ng-controller= RedController'>
<html>
cp>Message: {{message}} <br/>Color: {{colormame}} </p>
<script src="http://ajax.googleapis.com/ajax/ibs/angularjs/1.3.14/angular.min.js"> </script>
</div>
<body>
<div ng-controller= BlueController"
<div ng-app="MyApp' ng-controller= "MyController">> <p>Message: {{message}} <br/> Color: {{colormame}} </p>

User: cinput type="text' ng-model="user"> <br/> </div>


<br/>
City: <input type="text" ng-model="city"> <br/>
<br/> </div>
Address:({user + "ives in " +city}}

</div <script src =


"https://ajax.googleapis.com/ajax/ibs/angularjs/1.3.14/angular.min.js'> </script>
script src="MyController js"> </script>
</body> <script>
var App =
angular.module("MyApp", [l);
/html>
Output
App.controller ('MyController", function($scope) {
Sscope.message = "In Color Demo controller:
$scope.colorname = "No-Name"
file:///d:/Contrc C

User: A
App.controller ("'RedController", function($scope)t
City:Pune Sscope.message "In Red Color controller
Address: AAA lives in city Pune

Dp.controller("BlueController, function($scope){
SCope.message = "In Blue Color controller
Review Question $Scope.colorname "BLUE":
1. Explain the controller directive in the
Angular JS with suitable example. Also exp
implementation of MVC analogy by means of controller directive. s/script>

TECHNICAL PUBLICATIONS An up thrust for knowledge for knowledge


-

thrust
PUBLICATIONS-An up
TECHNICAL
2- 16
Advanced Web Programming
introduction to Angular Js A d V a n c e dVVeDP r o g r a m n
2-17
Introduction to Angular JS
</body BuitinServices

</html> Output
Letu sunder derstand the useof services with the help of
Service
examples-
Shttp
Dx 1.
The
used service in
d/ScopeDemx+ This is
a comm
the server and the
Angular|S. By using this service, the request
made to
fle:///d:/ScopeDemo.h C
can be application handles the response.
reate a simple web document as follov
Step1.
Message: In Color Demo controller
m s g . h t m l

Well Done!!
Color: No-Name
create a web docun at will make use of
Step
2 :N o w
Shttp service to get the
Message: In Red Color controller message
stored in above html file and to
display the contents.
Color: No-Name
AngularJs Document[Service
viceDemo1.html]
Message: In Blue Color controller IDOCTYPE h t m l >

Color: BLUE
<html>

e="https://ajax.googleapis.com/ajax/ins/angularjs/1.3.14/angular.min.js'></script>
sCript src="7

<body>

Script Explanation:
In above code div ng-app="MyApp" ng-controller="MyController'>

1. we have created three controllers namely MyController, RedController file is... </p>
gi sp>Message obtained from a
BlueControler.
ch1>{(message}}</h1>
2. There are two properties namely message and colorname.
</div>
3. Note that RedController does not have colormame property, hence it inheristhis
value from MyController. <Script>
4. The scope object is used to define that values for these properties. Hencen varApp angular.module(MyApp, Il):
HTML(view) part we can simply invoke the name of the property as message and App.controller(MyController, function($scope, $http) {
colorname inside Il }} and get the values assigned in respective controller.
Shttp.get('msg.html").then(function(response){
5. Thus job of scope object is to bind the controller with view part of Anguap Sscope.message = response.data;
document.

2.10 Services
s/script>
The services are functions objects that are intended to carry out specinc task
or

In Angular]S there are 30 built-in services used to carry out variety ot tasks body>
SAhtmi>

for knowledge
PUBLICATIONS-An up thrust
TECHNICAL
TECHNICAL PUBLICATIONS -An up thrust for knowledge
Advanced Web Programming
2- 1 8
atroduction to Angular te
O u t p u t

O X
Id/ServiceDem X+
C
File:/I/d:/ServiceDemo

from a file is.. 3 Angular JS in Details


Message obtained

Well Done!!! Spllabus


Routes, Angular JS Forms and
odules,
Directives,
Validations, Data binding,
website uSng Angular ]S. Creating single
pge

Contents

31 Directives

32 Modules

Review Question 3.3 Routes

JS Foms and Validations


1. Explain any three built in services used in Angular JS. 34 Angular
3.5 Data Binding

36 Creating Single Page Website using Angular JS

TECHNICAL (3-1)
PUBLICATIONS- An up thrust for
knowledge
5-14
Advanceo vveu riuyramining
Node JS I a n c e dW e D Programming
5- 15 Node JS in Details
ue
pipe operation that means, all the output of one stream can be fed
is no limit on
Example Code There another stream.
to
to input
r e q u i r e ( ' i s " ) ;

input for
is
steps used using the pipe operation in your node.js program-
=
as
var
are the
fs.createReadStream('sample.txt)
vars t r = Following
the fs' module using require.
var rs
=

Is.setEncoding('utf8");
Import
. Create readable stream using createReadStream function.
'data stream using createWriteStream function.
Create writable
event

/handling
stream

rs.on('data'function(chunk){
3:
Use the pipe() function for passing the data from readable stream to writable
str += chunk;
step4: stream.

shows the use of pipe operation -

Eollowing example
/handling
stream
event end
p i p e E x a m p l e . j s

rs.on('end,function(){

var
fs require("fs"):
console.log(str)
v a r r s f s . c r e a t e R e a d S t r e a m ( ' i n p u t . t x t ) ;

s e t E n c o d i n g ( ' u t f 8 " ) ;

am('output.txt);
/handling
stream event
'error
var w s fs.createWriteStre
r s . s e t E n c o d i n g ( ' u t f 8 " ) ;

rs.on(error,function(err){
rs.pipe(ws);
console.log(er.stack),
transfered from input.txt to 'output.txt ");
console.log("Data is
Output
Sample.txt
This ine is written to myfile
Command Prompt
Output Execution of
pipeExample. js program
D: NodeJSExamples>node
from "input. t x t to 'output. txt
Command Prompt Data is trans fered
input. txt Display of input. txt
D:WodeJSExamples> type
Hello friends,
p:Node 1SExamples>node readstreamExample. js
This line is written to myfile
Node.js is really amazing.
Really enjoying it.
p: Wode)SExamples»

p:MlodeJSExamples>type output. txt Display of output.txt


p:Node JSExamp les» Hello friends,
Node.js is really amazing&
Really enjoying it.
D:NodeJSExamples>

5.4.3 File System


File system fs is implemented in the
nodejs using require function
L Pipe Operation var fs require(fs');
module are-
ne common operations used with the file system
The
pipe operation is a kind of
operation in which ream
a c t s as
an

4. Delete file
input of another stream. output of one
1. Read file 2. Create file 3. Update file

TECHNICAL PUBLICATIONS- An up thrust for knowledge


TECHNICAL PUBLICATIONS- An up thrust for knowledge
Advanced Web Programming 5-16
Node 5-17
Node JS in Details
ancedW e bP r o g r a m m i n g

JS in
1. Read Operation
Det Operation
File
operation can be performed synchronously or a s y n c .
The read file

For reading the file synchronously we use readFileSync method


asynchronously
And for
2.Create
can create
a n empty file using the command open)

file synchronously readFile


reading the 5yntax

using asynhronou form we use callback


o p e n ( p a t h ,
f l a g s , . m o d e ] . c a l l b a c k )

the file
Normally while reading
the last parameter to the readFile function. The form of this callback fundi functio where

is, the path of the filename.


functionerr, data) path:It is
flag:
I tindicates, the behaviour on
opening a file. That means "" is open file for
/function body reading is for writing, "rs' is for synchronous mode, "r" or "w+" means open a file
write purpose and so
for both read and on.

Example code
mode: it indicates readable or writable mode.
var isrequire(is
sreedPile(input.tr function(err,data){ Callback: It is basically a function which has two
arguments(err,data)
ferr)
Example Code
console loger); varfs=require(fs");
consolelog(data.toString0x is.open(myfile.txt, w' function(er,fle){
iferr)
console.log(err)
inputtxt
Hello friends, console.log(File createdi!');
Node js is really amazing.
Really enjoying it 3.Update/Write File Operation
Output
Forwriting to the file two operations are used most commonly-
Command Prompt
1.appendFile0 and 2. writeFile0

p:Wode)SExamples>node
Hello friends, readFileExample.js The appendFile0 method is used to write the contents at the end of the
specified file.
Node.js is really amazing.
Really enjoying it. Example Code
var fs
require( fs
p:ModeJSExamples> str
This line is written to the file';
s.appendFle(myfle.txt, str,function(er){
ifferr)
console.log(err)
Similarly we can read the file console.log(Fle appendedi!'):
synchronously using following command-
readFileExample.js
var fs=require(is");
var data= fs.readPileSync(input.txt);
console.logldata.toString(0);
TECHNICAL PUBLICATIONS- TECHNICAL
PUBLICATIONS-An up thrust orknowedge
An up thrust for
knowledge
5- 18
Advanced Web Programming 5-19 Node JS in Details
Output
Node JS
In
w a n c e dW e b P r o g r a m m i n g

Deta
unlink(path, callback)
S y n t a x

Command Prompt D
D: \NodeJSExamplesnode appendFileExample.js where

File appended!!! of the file to be deleted.


path:Is a path
a callback unction with the only one argument for 'error.
D:\NodeJSExamples>type myfile. txt callback: <:It is
written to the file
This line is
Example C o d e
D: NodeJSExamples
v a rf s = r e q u i r e ( ' f s " ) ;

fs.unlink(myfle.txt,function(err)

if(err)
throw e n ,

console.log(File is deleted!!l"
The writeFile0 method is used to write the contents to the file
Output
Example Code
Command Prompt.
varfs require("is");
stu = This line is replacing the previous contents";

fs.writeFile(myfle.txt, str,function(err){ D:NodeJSExamples>node deleteFileExample


File is deleted!!!
.
js Deletinga file

ifer)
console.log(err) D: NodeJSExamples>type myfile.txt
The system cannot find the file specified.~ Checking if file gets deleted or not.
console.log(File Writing Done!!!');
D:Node3SExamples>node deleteFileExample.js -

Output D: \NodeJSExamples \deleteFileExample.js:4 Again trying to delete a deleted


throw errs ile, hence exception is thrown.
Command Prompt
Error: ENOENT: no such file or directory, unlink "o:\ModeJSExamples \ayfile.txt']{
errno:[33m-405S8+[39m,
D:NodeJSExamples>node writeFileExample.js
File Writing Done!!!
code:[32m ENOENT'[39m,
syscall: +[32m'unlink'-[39m,
path:[32m'D:\\NodeJSExamples\\myfile.txt'-[39m
p:NodeJSExamples>type
This line is replacing myfile.txt
the
D: Node JSExamples>
previous contents
D:NodeJSExamples>

4. Delete File
Operation
To delete the file, we use
unlink) method.

thrust for knowiedge


PUBLICATIONS An up
TECHNICAL
TECHNICAL
PUBLICATIONS An up thrust for
knowledge
Advanced Web Programming 5-20 ble Aavano Web Programming
5-21
Node JS in Deta
Node JS in
5.5 Networking with Node Details Application Application
program program
Basics of Network Programming
Socket Socket
.Socket is the most commonly used term in network programin
ming. Socket provides
the way by which the computers can communicate using cor
connection less communication.
using connection TCP with
Internet TCP with
streams
oriented or streams
and buffers
and
buffers
A socket is basically an endpoint of a
two-way
programs running on the network. Typically these programs
communication link between
and Client program.
are
two
Server program Fig.5.5.1 Client Senver communication using TCP

Thus socket is OS-controlled interface into which the which has resources and from which the services can be obtained.
applicati. Server is a device
receive messages to and fro from another application. tions can send : there are various types of
servers such as web server which is for
or For example
the printer services
the web pages, there are print servers for managing
or
A socket is bound to a port number so that the TCP/UDP from storing
identify the orresponding application at destination. transport layer can there are database servers which store the databases.

service from
particular server.
Creating TCP server-client communication Application .Clientis a device which wants to get
receive the client connections. The server-
.First of all server starts and gets ready to
.Transmission Control Protocol(TCP) is a
connection-oriented,
which reliable client communications occurs in following steps
supports the transfer of data in continuous streams. protocol Server
.The addressing scheme used in TCP is makes use of ports. On r. No. Client
Creates TCP socket.
communication can be established concurrently separate ports the 1. Creates TCP socket.
by the system. During this Client initiates the Creates another socket for listening client.
communication, the server waits for the client to
get connected to a specific port for communication. i) Accept message from client and
establishing communication. This type of communication is called
repeatedly communicate.
as socket i) Communicate.
programming. Close the connection.
There are some Close the connection.
ports which are reserved forspecific service. These ports are called
as reserved ports. Various
port numbers specifying their services are given in the have two build to One for server and other for client.
We node.js programs
-

following table
Port number TCP Server Program
Service follow the steps as given below
-

To build the TCP server program we have to


21 the
FTP
Step 1: We use "net" module following line at the beginning
by adding ofboth
23 Telnet programs-
25 SMTP varnet recquire('net')% TCP server.
80 Step 2: Now we use the createServer0 method for creating the stream based
HTTP
For that purpose we have to add following code in the program.
110 POP3
User level processes or services varserver net.createServer()
generally use port numbers >=1024 connected to it.
A Socket is bound to a
port number l a y e rc a n Step 3 We use the
event handler on for the server when any client gets
so that the TCP/UDP from handling code we use the socket class. The attributes
identify the corresponding application at destination. transp In this event

TECHNICAL PUBLICATIONS-An up thrust for knowledge


TECHNICAL PUBLICATIONS- An up thrust for knowledge
5-22 5-23 Node JS in Details
Avanced e Pogrsmeng Node JS in
A d v a n c e dW e bP r o g r a m m i

renoteAddress and remotePort will


return the remote
ddress aand
address Detais
to the server. port numb TCP Client P r o g t a m

of the dlient which is connected currently mber lowing is a dient program,


in which we are getting some input from the user
Step4: Then using sodet such
instance we can handle three events such as da
as data,close Follow

and sending that data to the server. For reading the input
and oh command prompt
need to install readline-sync module. For installation of
error. this module,
o For data event, the data received from the cient is displayed on
ovboard we
from of this module is as follows-
using cosole.log method.
the console command prompt. Theinstallation
Op ommand Prompt
X

o For dose event, the connection closing message is displayed to the


client. e1SExanp les \TupAop>nm install
readline-sync
lf any error occurs during establishment of connection, the error evs
tield.
No repository
o mpeckage@l.0.1

and error message is displayed on the console. firei eadline


4 . 2e

added 11 package from 1


dded
contributor end audited 53 packages in 0.963s
found vulnerabilities
Step S: During this entire, dient server communicaion server must be in listenins
mode. This can be done using listen method. To this method, the b:NdeJSExamples \TCPApD
port ber
passed. The same port number
must be used in the client program, so that h
the server and client can communicate on the same
port number.
The complete code for server program using TCP is as given below -

erver.js
ar net require( 'net' To build the TCP client program have to follow the steps as given below-
we

server= net.createServer(: Step 1: We use "net" module by adding following line at the beginning of the client
program.
ver.on 'connection' function(socket){ var net require('net');
var clientAddress socket.remote Address+"" +socket.remotePort: Step2: As is running
our server port number 8082 and the localhost as the host, the
on
consolelogcConnection with the client %s is client must run on the same for establishing the communication betweern server
established!!",clientAddress):
and the client. The instance of socket class is created and it is named as var

socket.on('data"',function(mydata){ client.
console.log\n Data received from client is:
llsever sending data to the client %s'.mydata.toString0): const client = new net.Socket0%

socket.write>l am fne); oep3: Now it is possible to establish a connection with the server using connect
the connection we should pass the same hostname and
method. For establishing
socket.once('close',function(H port number as parameter.
console.logr Connection with %s is write method. Here we are
gettingg
closedil",clientAddress; p 4Client can send the data to the server using the data
socket.on error,tunction(er?){ the data when user enters some data through keyboard. For getting
question method. The
cosole.log(Connection error %s',en.message; from the oconsole, we use the readline-sync
module's

is
required code for this operation
-

var read line = require(readline-sync)


server.listen(8082, function({
console.log( Server is listening to to server:
it
some data for sending
read line.question("Enter
%.server.address()
=

ata
client.write(mydata); those a r e
-

data and end.


the client program
T w o more
events can be handled by

PUBLICATIONS-An up thrust for knowledge


TECHNICAL
TECHNICAL PUBLICATIONS
An up thrust for
knowledge
Advanced Wab Progra1mihng 5.224 5-25
Nodo J' it l
d Web Progamming Node JS in Details
.On the data event, the data received from the server is displayed otsils
the onwle Output

window, using console.log Running server on


a n dPonp
olhent.on('data"function(d) command prompt
Ihody
wde5Ezmles \10P.onode

rver js
serves

wddsk
rver is 1istening
eto (address:"faíly:"19A,,vt 0)
the client :ff14:127.9.0.1:57 is establíshed!1
a i t h the c1
Running cHent On
acknowledge the
L n e c t i o n

O n the end event, the we can server than now client i Hello hon ore you?
1s
command prompt
dareceived from clent is clored!|1
end yinw, t i t h with 4f11:177.9.0.1:9A67

olient.on 'end function() DodeErnples\TCPA

Cmnard Prma
I/body
p:Wde1SEzmoles\TCPkopmae client.j
Cnnectin has been established with server
The complete code for client program using TCP in as given below. Enter vee data for ending it to server: Hello how are you?
received fraa erver ís I fie
Data
Request is ended!1!

cllent.js p:Vode)SExles\TCPkop
Varnet 1ecquire('net'),
VAr read ine= requiro(readline-aynd');

6onstPORT= 0082;
Communication Application
COnst1OWT="localhost Creating UDP server-cllent network whose
WOreate a TCP dient self-contained message sent over the
conat ollent = new net.ooket(), A datagram is an independent,
are not guaranteed.
arrival, arrival time and content network. The
unit associated with a packet-switched
dlient.conneot(PONT,HOST,function( It is a basic transfer send and receive completely
0Onaole.lou('Connection has boen otablished with server'), communicate via datagrams
applications that
/elient sending data to server independent packets of information.
Var mydata read line.question("Enter some data for sending it to sorver: ") server communication,
the first and foremost thing which is
For using UDP client
olent.writo(mydata); module.
required is installation of UDP working
module in the current
screenshot shows how to
install udp
Following
olient.on('data',function(d)( directory.
0Onsole.lou('Data recoived from server ls: %s,d);
ollent.end() Installing UDP Module
x
Administrator Command Prompt
ollent.on('ond',tunction()
conaole.log('Request is endedill"); d: \NodeJSExamples \UDPApp>npm 1install udpfield.
mypackage1.0.1 No repository

in 3.358s
udp@1.0.0 and audited 54 packages
or getting the output, open the two command prompt windows One for exeu dded 1 package from 1
found 0 vulnerabilities
contributor

the nerver and other for first


executing the client program. Execute the server pro gram

and then ellent. The


following output illustrates this application. d: Mode3SExamples \UDPApp

build to node.js programs One for server and other for client.
e have two

knowledge
TECHNICAL PUBLICATIONS An up thrust for

TECHNICAL PUBLICATIONs-An up thrust for knowledge


5-26 Node A d v a n c e dW e b P r o g r a m m i n g 5-27 Node JS in Detai
Advanced Web Programming JS in
Details
UDP Server Program age', function(msg,fnfo){
have to follow the steps as given hol.
To build the
UDP server program
we
elow. serve 1log('Data received from client is: "+msg.tostring()%
line at the beginnine
Step 1: We
use "udp"
module by adding following ming ooff uboth the var
msg=
Hello friend";

d a t a to the
server

programs 1/sending
port, "localhost, function(err){
var udp require('udp'"); server.send(msg.into

use the createSocket method for creating the UDP sockets 1 if(err)
Step 2: Now we
following code in the program
client.close();
have to add
purpose we
else
var server udp.createSocket('udp4"); console.log("Data sent!l');
udp.createSocket(udp4");
var client =

PV4.
we create a UDP socket which will be udp4 for

Step 3: We use the event handler on for the any client gets connecte
server when
o
it.we can harndle three events such as message listening, close and error.
server.on(istening.function(){
o For message event, the data received from the client is displaved
var address server.address();
on the
console using cosole.log method. Similarly we can send the data to the
serer var port address.port,
using send method. var ipaddr address.address;
=

port number and console.log("Server is listening to port: "+port);


o For the listening event, ip address of the server on which console.log(Servers IP Address: "+ipaddr);
it is running is displayed.
}):
o For lose event, the connection closing message is displayed to the client. server.on('close" function(){
o If any error occurs during establishment of connection, the error event is fired,
console.log(Closing the server socket nowl!F);
and error message is displayed on the console.
server.bind(8082);
Step 4: During this entire, client server communication Server must bind to one
particular port number. This can be done using bind method. To this method, Tobuild the UDP client program we have to follow the steps as given below
of the client
the port number is passed. The same port number must be used in the client Step 1: "udp" module by adding following line at the beginning
We use

program, so that both the server and client communicate the program.
can on same port
number. var udp =require(udp");
sockets. For that
The complete
node.js code for UDP server is as given below- otep 2 Now we use the createSocket method for creating the UDP
purpose we have to add following code in the program
server.js varclient =udp.createSocket("udp4')k
var udp require('udp"); Step 3: We use the event handler on for the cliernt when any server gets connected to it

var server= udp.createSocket('udp4"); For that purpose we the message event handler.For message event, the data
var client = received from the server is displayed on the console using cosole.log method.
udp.createSocket('udp4"); Step 4: Similarly we can send the data to the server using client.send method. Note that
server.on(error function(err){ during this entire communication the same port number and host name is used
which was.used tor server program.
console. log("Errorl!l"+er.message);
server.close();

TEGHNICAL PUBLICATIONS An up thrust for knowledge


TECHNICAL PUBLICATIONS An up thrust
for knowledgee
Advanced Web Programming
5-28 Node JS in Iced web Programming
5-29
Node JS in Details
using TCP is as given below- Detan
code for client program 5 . 6W e b M o d u l e
The complete

The
itah module is mainly controlled by a web server that handles the requests and
clientjs
orovides the responses.
var udp require('udp);

=
udp.createSocket ('udp4");
var client
Web
server ?
What is
var mydata
= "Good Morning!l"; Web server is a special type of server to which the web browser submits the request
which is desired by the client.
client.on('message", function(msg.info){ of web page
console.log(Data received
from server: "+msg.toString(): There are some popularly used web servers such as Apache and IIS from Microsoft.

client.send(mydata, 8082,localhost", function(er){ web server


Functions of
ifem) Various functions of web server are
-

client.closel)
1. The web servers accepts the requests from the web browsers.
else
console.log(Data sentll"); 2. The user request is processed by the web server.

3. The web servers respond to the users by providing thee services which they demand
Output
for over the web browsers.
Administrator Command Prompt 4. The web servers serve the web based applications.
Server
Running 5. The DNS translate the domain names into the IP addresses.
d:NodeJSExamples \UDPApp>node server.js
6. Theservers verify given address exists, find necessary files ,run appropriate scripts
Server is listening to port: 8082
Server's IP Address: 0.0.0.0
exchange cookies if necessary and returns back to the browser.
Data received from client is: Good Morning!I1 Client nunning 7. Someservers actively participate in session handling techniques.
Data sentlll
C
Working Principle of Web Server
d: \NodeJSExamples \UDPApp>
When user submits a request for a web page, he/she is actually demanding for a

Command Prompt pagepresent on the web server.


When web browser submits the request for a web page, the web server responds

p: \Node JSExamples \UDPApp>node client.js thisrequest


by back the requested page to the web browser of the cliene's
sending
pata sent!!! machine.
Data received from server: Hello friend Request for
web page
p: \NodeJSExamples \UDPApp Serves the Web server
Web browser
web page

Fig. 5.6.1

IP address of the
Ste web page by providing the
W e b client requests for the desired
website

PUBLICATIONS An up thrustfor knowledge


TECHNICAL

TECHNICAL PUBLICATIONS-An
up thrust for knowledge
Advanced Web Programming
Node JS A d v a n c e dV W e DP r o g r a m m i n

5-31
in Node JS in Details
Step 2: The web server locates
the desired web page on the website
Details
sending back the requested page. If the page doesn't exist, it willPonds bu
appropriate error page.
end back the localhost:8082

renders it C localhost:8082
browser receives the page and as required A,
Step 3: The web
Welcome to this Web Module Application!
Example Code

has built in module named http which allows us to trane


Nodejs a
data over the
Hyper Text Transfer Protocol(HTTP)
In this section we will build a web server using http module.

WebModuleExample.js Script Explanation: In above given Node.js script,


var http =
require('http'"
var server = http.createServer(iunction(request,response) {
1) We have imported http module.
response.writeHoad(200, ('Content:-Type': "text/plain"});
response.end(Welcome to this Web Module Applicationl!I"); 2) The http.create Server) method includes request and response parameters which is

server.listen(8082); supplied by Node.js.


console.log("Server is running on port 8082 port..;
3) To send a response, first it sets the response header using writeHead) method and
Output
then writes a string as a response body using write0 method.
Step 1: First of all open command prompt and type
following command
4) Finally, Node.js web server sends the response using end0 method. But we can
Command Prompt -

node WebModule Exam.. directly write the response body using end method.
5) Using server.listen method the
D: \NodeJSExamples \HttpApp>node WebModuleExample.js we can specify port number on which our web
Server is running on server is running.
8082 port port...
6) Just refer the illustrative
output given above.
Handling various Http Requests
he
Http.request object is used to get information about the current Http request. The
response object is used to send the
response for current HTTP request.
Following Node.js script shows how different HTTP requests are made and how to
respond them using response object of HTTP module.

WebModule Example.js
Step 2: Now var http require("'http"
open some suitable web browser such Mozilla Firefox as or Google Chro
and type the var server http.createServer(function(request,response)1
locahost:8082 as URL. It is illustrated following eensho
by
ifrequest.url="A)
responsewrtbeHead(200,("Content-Type": "text/html')E
TECHNICAL PUBLICATIONSAn up thrust for knowtedge
TECHNICAL
PUBLICATIONS-An up thrust for knowiedge
Advanced Web Programming 5-32
response.write( <html> <body> <h1>Welcome to this Wob Module Node JS in u M a n c o dW e bP r o g r a m m i n g
5-33
Application!l <h1> </body> </html>); Delailn Node JS in Details
open web browser and get the about
a web
page by make the
can
We
response.end(); lhost:8082/About". The illustrative
is as request usin the
output given below
else iffrequest.url == "VAbout"){
localhost8082/About
response.writeHead(20o,(°Content-Type': "text/html"}); C localhost:8082/About
response.write<html> <body> <h2> About Page </h2 > </body> </html
response.end(): About Page

else ifrequest.url = =
"IContact){
response.writeHead(200.{°Content-Type": "text/html"}):
response.write( <html> <body><h2>Contact Information</h2>
response.end();
<body><h

response.end("This is invalid request");


5.7 Debugging
Node.js provides a built in debugging tool. This tool is command driven
graphic tool. and non-
server.listen(8082):
console.log(Server is running Following table shows various commands used in debugging -
on port 8082 port..");
Output Command
Description
I Command Prompt node WebModuleExam.. next(n) It moves on to next line for
debugging.
D: NodeJSExamples \HttpApp>node cont(c) Continues the execution and stops at
port 8082 WebModuleExample.js
Server is 'debugger statement if any.
running on
port... step Steps in the function

out
Steps out of the function

watch Add the


expression or a variable for inspecting its value.
watchers nis allowS us to see the value of the expression or variable that are passed
to watch command.

t exits the
exit debugging mode and returns to the command
promp
TECHNICAL PUBLICATIONS An up thrust
TECHNICAL PUBLICATIONs- for knowledge
An up thrust
for knowledge
5- 34 5 - 35
Advanced Web Programming Node JS in nced Web Programming Node JS in Details
sample Node.js program with the Details ADvG

shot,
Now let us see how to debug
help ot from above een
scre er we can notice >
symbol which indicates the current
example- following 4s
debugging
statement.

can use next to move on the next statement


appendFileExample.js low we

var fs require( is"); Command Prompt- node debug appendFile Examplejs


previous contents;
str This line is replacing the Debugger attached.
var strlen = str.lengthh; Purposely made this
spelling Break on start in appendFileExample.js:1
fs.writeFile(mysle.txt, str.functionfer){
nistake(length),
about this eror
to
get to
know 1 2 var
str
fs require("fs");
=

"This line is replacing the previous contents";


iferr) dunng debugging 3 var strlen = str.lengthh;
process.
console.logler) debug next

console.log(File Writing Done!!): break in appendFileExample.js:2


1 var fs = require("fs");
console.log(The Length of contents of the file is: "+strlen);
2 str = "This line is replacing the previous contents
3 var strlen = str.lengthh;

Output 4 fs.writeFile("'myfile.txt', str,function(err){


debug next
break in appendFileExample. js:3
Command Prompt 12 var fs require(*s")5
str = "This line is replacing the previous contents"

D:ModeSExamples>node appendFileExample . js 3var strlen =str.lengthh;


4 fs.writeFile("myfile.txt
str,function(err){
File Writing Done! !! 5 if(err)
The Length of contents of the file is: undefined debug

D:Node SExamples> We can inspect the values of the variable using watch and watchers command.

Command Prompt node debug appendFileExamplejs

2str
3 var "This
strlen = line
is replacing
str.lengthh;
the previous contents";

Note that the debug next


length of the contents is undefined because of the wrong break in appendFileExample.js:2
this program does not raise spelling. But 1 var fs =
require("fs")
any syntactical error. It retuns simply 'undefined'. So what 2 str-This line is replacing the previous contentss";
went wrong? Yes, in order to find it out we need to debug our code. To 3var strlen=str.lengthh;
application, run the following command debug the above 4 fs.writefile( 'ayfile. txt', str,function (err)
debug> next

Promptbnode debug appendFile Example.js break in appendFileExample. js:3


1 var fs = require("fs");
2 str "This line is replacing the previous contents";
By above command, the
lines -
debugger starts and waits at some line after executing
t
3
4
var strlen = str.lengthh;

fs.writeFile('myfile. txt str,function (err)


-ise
debug
r)----
watch("str")

Command Prompt debug> watchers


node debug appendFileExamplejs 0: str This line is replacing the previous contents

Debugger
For help, listening on debugg
r
see:
ws://127.0.0.1:9229/e7c9ce88-9bfa-43c0-8c15-35807b46a19
https://nodejs.org/en/docs/inspecto Then continue to debugging by using next command. Then again by using watch
Debugger attacbed.
8reak on start in command we can inspect the value of strlen variable
1 var
2 str
fs = appendFileExample.
require("fs"); -
js:1
This line is
var strlen replacing the
previous
debug
=

str.lengthh; contents

TECHNICAL PUBLICATIONS-An up thrust for knowledge


TECHNICAL
PUBLUCATIONS-An up thrust for knowedge
5-37
e d W e b P T O g r a m m i n g

a I c e T e b

Advanced Web Programming


5. 36
Node JS in Node JS in Details
Deteils p s t a l l i n gE x p r e s s

Command Prompt node debug appendFileExamplejs


fs.witeF ile( 'myfile. txt', str,function(err)
Express i s i n s t a l l e d
stalled using Node Package
5 if(err) express is, Manager(npm). The command issued for
nstallingthe
console. log (err)
debug watch("strlen") Prompt:>npm install express
debug watchers
contents
: str Thi line 1 repl acing the previ ous
1: strlen = u e t inuc
npm

debug
jexpressExample>npm in tall express
n- ModeSExasples 1/ fetchMetadata: iresolveithled'odule
. ...
vary1.1.2 checking ins
And here we get to know, that something went wrong in finding the strino
And thus the spelling mistake of length attribute of str variable can be correctod
Then
save your node js file with the appropriate corrections, stop the debugger and ren
above application program. The illustrative output is the
Command Prompt
debug exit
: 'This 1ine is replacing the previous contents
str
D:Node JSExamples >node appendFileExample.js
File kriting Done!!!
The Length of contents of the file is: 44
Collowing is a simple application program that uses Express JS for displaying
welcome message" on the web page.
D: Node5Examples >

app.js
rarexpress require('express);

5.8 Express in NodeJs rar app= express();


appget(, function(req.res) {
Express is web application framework used in node.js. It has rich set of features that res.send("Welcome User!");
help in building flexible web and mobile applications.
Features of Express
arserver app.listen(8082, function()
1) Middleware: Middleware is console.log(Server started!");
a
part of program,that accesses to the database and
respond to client requests.
2) Output
Routing: Express JS provides a routing mechanism so that it is
different web pages using the URLs. possible to
readn Command Prompt node appJS
3) Faster Server Side
Development: It is very convenient to develop serve side
development using Express JS ModeJSExamples \expressExample>node app-Js
Server started
4)
Debugging: ExpressJs makes
mechanism. debugging easier by providing the ue ing

TECHNICAL PUBLICATIONS- An up thrust for


knowledgo PUBLICATIONS- An up thnust
for knowiedge
TECHNICAL
38 Node JS in 5-39
Advanced Web Programming
"localhost:8082"
Delails
ails wanced Web Programming
Node JS in Details
issue the URL
web browser and
Open s o m e app.listen(8082, functiond
varserver=
console.log("Server startedl")
localhost:8082

localhost:8082 Output
C

Welcome User!! X
localhost:8082/about

C loclhost:8082/about

This is about us page

Routing
Routing is a manner by which an application responds to a client's request based on

particular endpoint. The sample endpoints are,


D x
localhost:8082/aboutus
localhost:8082/contact
localhost:8082/contact
C localhost8082/contact
localhost:8082/home
There are various types of requests such as GET, POST, PUT or DELETE. While This is displays contact information
handling these requests in your express application, the request and response parameters
are passed. These parameters can be used along with the send method.

Following application represents how to performing routing using express

app.js

var express require(express); API


var app express0;
5.9 Node JS REST
What is API ?
Interface. APls are a set of functions and
app.get(/, function(req.res) API stands for
Application Programming of
creation ot applications that
access data and features
res.send("Welcome User!"); that allow tor the
procedures
services, or operating systems.
other applications,
with a computer orsystem to retrieve
I/routing to 'about us' page other words,
it you want to interact
In communicate what you want to that
app.get(/about, function(req,res) { a function, an API helps you
information or perform
understand and fulfil the request.
res.send(This is about us page"); svstem so
itcan

I/routing to 'contact page


app.get(/contact, function(req.res){ TECHNICAL PUBLICATIONS An up thrust for knowledge
res.send(This is displays contact information");

TECHNICAL PUBLICATIONS-An up thrust for


knowledge
Advanced Web Programming 5 40
Node JS in AdvancedWebProgramm 5-41
Details Node JS in Details
It is basically a software intermmediary that allows two
anlications
applications to
totalk
tall (2) Methods

other. For example -

When we use facebook, send a check the weath. each


message or
There are
various types of ethods. But the most
mobile phone, we use APL on our commonly used one are as follows -

1) GET 2) POST 3) DELETE


For example -

If we want to buy a movie ticket, we go to the online ticket hocl.:.. 4) PUT 5) PATCH
enter movie name, use credit card information, get the ticket, print it. The
ing Site, These methods are basically used for performing CRUD
interacts with
softwa.
are that operations. Here C-stands for
us to
perform all these task is
nothing but the API. Create, R- stands for Read, U- stands for Update and D-stands for Delete.
some well known
Following
wing screenshots
examples of API.
Method
Purpose
Login with one of these available
social GET For getting the data from the
How you'll pay accounts. server, this request is used. The server looks for the

VISA GitHub data the client has requested and sends it back to the client.

OInstagram POST This method is used when new resource is to be created on the server. When client

Pay with Other fFacebook uses this method and provides the data, then the server creates a new entry in the

database and acknowledges the cient whether the creation is sucoessful or not.
G Coogle
PUT and
in Linkedin These are the two methods that are used when the client wants to update some

PATCH resource. When PUT method is used, then that means dient wants to update entire
What is REST API?
resource. And when PATCH method is used, then that means cient simpy wants
KESI stands for
follow while Representational State Transfer. It is
creating their a set of
to update small part of the resource.
API. rules that developets
Each URL
made by the client is
response. a
request and data sent DELETE Ihis request is used to delete a resource from the server.
back to the client 1s ated as
The
request consists of, tea to select the
some software tools such as Postman, that help the client
ae tool
D Plate method and issue the URL. Following screenshot is of a software
1. End Point
2. Method
Ostman, using which we can select appropriate
3. Headers
(1) Endpoint 4. Data

The
endpoint (or route) is the
URL you
http:/localhost:8082/ request. For example-

TECHNICAL
PUBLICATIONS- An up thrust for TECHNICAL PUBLICATIONS An up thrust for knowledge

knowtedge
- 42 5- 43
Advanced Web Programming Node Jo n
hanced Web Programming
Node JS in Details
U
J s API
http://locaihost.8082,empioyees of Node
Concept
The Nodejs script is popularly used to create REST API. We will write the server
GET The ddatabase is
The created
script
Node.js.
in Node.js. using MongoDB. The client interface is handled
POST of Postman.
In with the help
this URL,
PUT
/employees acts as the
PATCH
endpoint a

A chent can
REST
DELETE select any Request AP
desired method. Client Using MongoDB
COPY Response Node js Database
and Express
HEAD

OPTIONS
LINK Let us understand how to create Node JS REST API with the help of following

UNLINK example

PURGE Example Code


Rest API need following software to be
LOCK Prerequisite: For creating the Node.js we

installed in our machine


1) Postman: This is an API client. This client software ailows us to enter the requestin
(3) Headers GET, POST, UPDATE, DELETE and
JSON format and select the commands such as

Header are used to


provide authentication and other useful So on.
server. The HTTP
headers are information to client and to be installed
property-value pairs separated by Colons(). 4) MongoDB: This is a database package. We need MongoDB compass
For example - The Mongo DB compass is a graphicaB
along with the mongoDB server application.
"Content-Type: application/json" tool for handling database operations.
APl in js tile.
(4) Data NodeJS : This is of course used for creating an

Rest APL. Here


he DATA contains
M a k e a new folder in your current working directory for creating
information
sending the DATA to the server the which the client wants to send to the server. l am creating a folder named RestApiDemo
nle using
used. methods such as POST, P Now open the command prompt window and
create packagejson
or ETEPUT, PATCH are

It is
DEL npm init command. Following screenshot illustrates the
same.

preferred to send the data in At the command prompt simply type the command
JSON format. The format is,
npm init
Property1:value 1, add the values ot vour choice or simply go on

Property2:value2 * nit the enter button. You can

Pressing enter key and accept the detault value

thrust for knoweuge


TECHNICAL PUBLICAFIONSAn up
PUBLICATIONS- An up thrust for knowledge TECHNICAL
5 - 45
c e d W e bP r o g r a m m i n g g
Node JS in Details
Advanced Web Programming 5-44 Node JS in
Details C o m i n a n d Prompt

install songodb
SExanples \RestAplDemo>npm
his vtiJity will wlb ya thrwp retingperkags- j sonsesible
ir. fovlts.
restapidemoe1.e.e
No
reposi tory field.
ee ghelp imit fu de injtive dotumtetin on thete fie ]ds 6.4
. onod aes fros 10 contributors and eudited 66 packages in 1. 215s
l v htthry .
d a vulnerabilities
tell E
'tereros
to insLsil aparhapr
: NodeJSExOnples \kes tApiDe
pres *ye step idomo)

ry i (Indrz }s) p )

module
Installation of
mongoose
t t o i t e to D d e ) somp ies \es1io1D gathap.

Issue the following commar

plGe
1his is y krst I
prompt:npm install mongoose
w
Mripts
test echo \rmur o *st per 11 jeð\ Command Prompt

uthor AA,Fuit.emear
D: Made SExanples \RestApiDeeo>npm install mongoose
restapidemoe1.0.0 No repository field.

ongooses.12.
odded 15 packages from 85 contributors and audited 81 packages in 1.841

Step 3: Now install some more packages that are required for creating this Rest packages are looking for fundin
A run npe fund for deteils

Installation of express module foundvulnerabilities


Issue the following command
plade 5Exaples \RestApiOemo
prompt:\>npm install express
Installation of nodemon
pn
Issue the following command at the command prompt
D:Mode Jst xamples \Res tAp iDemo vnpm instell eapress
1 rol lbackf al ledopt iona prompt:npm install -g nodemon-save-dev
np

DVode5anplesRestApiDemo npm instal11 -g nodemon- save-dev installable


fetchMetadata:
J resolveWithNeodule registry urle5.1.0 checking

Installation of mongodb module


Issue the
following command
The sample package.json file will show you all these dependencies of the modules you
prompt>npm install mongodtb have installed just now

TECHNICAL PUBLICA TIONS-An up thrust for knowledge


TE CHNICAL PUBLICA TIONS An up thnust to Anoeiedge
5 4 -47 Node JS in Dotails
Nade anced Web Programming

package json p uso(expreBejson)


//initial endpolnt
Ntaye Notei PP ovooRouter require(./toutes/employees')
p.uae(Vemployeer,employeeRouter)

ie tt hmat View Help


aPpliaten(8O82,( ) >
console.log('Server Started!"')
name":"estapidemo",
"version": "1.0.0",
deseript 1m: "This is my Rest API Demo Project",
folder named routes. Inside the routes folder create a file named
main "app. js s
Step5:
Create a
API.
'sripts": employees.js. This file will handle the GET and POST requests of REST
"start "nademon app. js" data into the
Using POST request we can create the API by inserting the
The GET request will retrieve and display the data from the database.
"author:A.A,Puntambekar",
*license": "IsC",
database.
in this file.
"dependenc ies": i{ Thus routing of GET and POST requests is done
"enpress": "*s.17.1",
'mngodb": **3.6.4", employees.js

mongoose": "*s. 12.0" constexpress require('express);

const routerexpress.Router() This is a router program


const Employee require(./models/employee) that routes on receiving the
particular type of request

Ln 1. Col1
100% Unix (LF) UTF-8
router get(, asyne(reqres)= >{
try
Employee.find() Handling GET command
Note that I have added const employees await
following line in
package.json file so that as soon as res.json(employees)
issued by the client, and using
changes in the file, the output gets retlected immediately. I need
I save any find(). displaying data present
app-js file every time. not have to run the in the Employee database
catch(err) {
"start": "nodemon app.js" res.send(Error is: '+err)
Step 4: Now create
your main server in a
file named app.js.
app.js
Handling the POST request. The data is
const express =

require('express'); rOuterpost(r, async(reqres)> { received here from client. Hence we use


const mongoose const employee= new Employeel{
require( mongoose'); name: req.body.name,
reqbody followed by name of the data
feld
r l = mongodb://localhost/EmployeeDB: URL for the designation: req.body.designation
database
name

const app = try


express(); const el await employee.save0
mongoose.connect(url. {useNewUrlParsertnue}) Connecting to MongoDB database res.json(el);
using Mongoose package
const con= mongoose.connection
//getting the connection object catch(err)
res.send(Error is: +em)
con.on(open'0=> {//on opening the
console.log(Connected to Database'connection,
) connecting with database
module.exports r o u t e r

TECHNICAL PUBLICATIONS
An up thrust TECHNICAL PUBLICATIONS An up thrust for knowledye
for knowledge
Advanced Web Programming 5- 48 5-49
Node JS in A O v O e W e bP r o n r
1 d v a n c e dv v e D F r O g a m m i n g
Node JS in Details
Step 6: Now create another folder nanmed models. Inside models folder Deians Command Prompt
-

nodemon r Un start
named employee.js. This file will describe the Schema.
The 6
Createe a
file
document are described in this file along with data ot D:Node JSExamplesRestAp1Demo>nodemon run start
type and the denon) 2.0.7

description is mentioned in this file. Note that the


schema is specifi ome other
to r e s t a r t et any tine, enter
nodemon *

nodemon ] watchirR path(s):


format. n nodemon) watchinE extnsiors5,mjs,]5or
JSON nodemon] starting node run start app. js

(node:13844) Warning: Accessing non-existent propertyMongoError of modul


employee.js e(Use
exports inside circular dependency
const mongoose = require('mongoose)
node-trace-warnings. to show where the warning was created)

const employeeSchema (node: 13844) DeprecationHarning: current Server Discovery and Monitoring en
=
new
mongoose.Schema({ gine is deprecated, ana will be removed in a future version. To use the new
Server Discover and Monitoring engine, pass option ( useUnifiedTopology: t
name:
constructor.
rue to
the MongoClient
Server Startedl !!
type: String.
Connected to Database
required: trie Preparing the schema
for the database

designation:
type: String. the Postman and click Create Select the POST command
required: true
Now, Open on Request.
issue the URL as

http://localhost:8082/employees
module.exports = mongoose.model(Employee,employeeSchema)
And then click on Send button
Step 7: For better
understanding, the folder structure of this project can be
following explorer window viewed in the
he
POST

ron torm-d www.formuncoded beyrca s


RestApiDemo
V models gnetion"; *CED

employee js
node_modules
V routes the data
Once we hit the send button we get the result by generating the unique_id for
employee js which we have inserted. It can be viewed as follows,
app.js
package-lock json
package json
Step 8: For getting the output, Open the command
prompt window and issue the cod oa
following command.
DINodeJSExamples RestApiDemo>nodemon run start
:AMdta",

You should
get the "Server started" and
"Connected to Database" messages
.s": asahheMT .
.

TECHNICAL TECHNICAL PUBLICATIONS-An up thrust for knowledge


PUBLICATIONS An up thrust
for knowledge
Advanced Web Programmng 5-50 Node J 5-61
in

etaids
ced WebProgrammingg
Node JS inDetals
In this, manner we can insert more data by selecting the Post comman.
Ths data is nicating with the server and
sent to the appjs server and then getting stored in the MongoDB database
Browser communic
server responding to the dient via
called as session.
In order to retrieve data being stored , we can use GET method on Postman browseris
ostman dient and esions is a mechanism
Sessi which allows to store data for individuals on sever side.
see the complete data in the form of JSON structure.
Following is an example of session handling mechanism. In this example we use the
cookie-parser package. It is basically a middleware which parses the cookies attached to
M

the dient request object. The express-session package is useful in creating the
middleware session.

Example Code

step 1: Create a folder in which you can store your source code for demonstrating
sessions. I have named this folder as SessionAppDemo.
Now create a package.json file using following command
DANodeJSExamplel SessionAppDemo >npm init
We can verify the data by opening the database created in
MongoDB Then install all the required packages such as express, cookie-parser and express
session. Use following commands
D:NodeJSExample\SessionAppDemo>npm install express
EmployeeDBemployees 3 2 748 Ou 1
DANodeJSExample\SessionAppDemo>pm install-save cookie-parser
DANodeJSExample SessionAppDemo>npm install-save express-session
RESET
Step 2: Now we will create a source file using js extension in which the session is
gdooumente 1-3d3 C created. The source code is as follows -

session Demo.js
var express = require(express)
var cookieParser require('cookie-parser
=

var session =

require(express-session)
var app =
express();:
In this manner
we have created our REST
API for
5.10 Sessions and Cookies employee details. app.use(cookieParser(0)%
app.use(session( {secret: "A secret Key })

5.10.1 Sessions app.get(, function(req, res)


Htp is stateless protocol. That
a if(req.session.viewCount)
tnen navigate to another page of means that when we load a
page in ourr
browser, an req.session.viewCount +
res.send(You
these same website the visited this page +
req.session. viewCount +
requests have originated from server has no means
o ) else f
times)
same browser or client. req.sesslon.viewCount 1:
res.send(Welcome to this page for the first timel
TECHNICAL PUBLICATIONSAn up thrust for
TECHNICAL knowledge
PUBLICATONS- An up thrust for
knowledge
5-53
Advanced Web Programming
5 52
Node JSin Details AdvancedWeb Programming Node JS in Details

Script Explanation

app.listen(8082);
var express =

require('express);
first open the command and Issue
prompt and Issue the var cookieParser =

require(cookie-parser);
Step 3: For getting the output, command
D:\NodeJSExamples\ SessionAppDemo>node sessionDemo.js session
var =
require('express-session');
Command Prompt ode sessonDemo js
In this script we use the above three modules
D: \Niode )SExamp les \SessionAppbeo »node sessionbemo. js
undef ined resave option; provide reseve option sessionDemo. js 89 var app = express();
undefined saveninitial ized option, prov1de saveUninitialized option

.J B
.Create instance of express in variable apP
app.use(cookieParser();
app.use(session({secret: " A secret Key'});

Now open the suitable web browser and enter the URL The app.use is a method used to configure the middleware such as cookie-parser or
session.
localhost 8082 X
The middleware functions determine the flow of request-response cycle. They are

C Olocalhost 8082 functions functions that have


executed after every incoming request.These are

Welcome to this page for the first time! access to the request object (req), the response object (res).
The cookie-parser and session are called third-party middlewares
cookie-parser is a middleware which parses cookies attached to the client request
object. Using session middleware we can perform various tasks such as creating the
session, setting the session cookie and creating the session object in request
object(reg)
Secret Here, the secret is the hash key passed to the header file so that this
information can be securely decoded at the server end only. This is important

because without a session secret, any third party app can easily look into the cookie
If
you just go on refreshing the above page for several times, with the of browser and hijack it. Having a secret ensures that when
changed. For instance it could be
the outpur help
using the secret key only known to the
something like this -

authenticating, the cookie data is encoded


client and the server; this data can then not beeasily decoded by a third listener.
localhost8082 X app.get(, function(req, res{
H{req.session.viewCount){
C Olocalhost8082
You visited this
Teq.session.viewCount++
page 10 times res.send(Youvisited this page" + req.session.viewCount + times';
else
Teq.session.viewCount 1;
Tes.send(Welcome to this page for the first timel");

app.listen(8082);

TECHNICAL PUBLICATIONS An up thrust for knowledge


TECHNICAL PUBLICATIONS- An up thrust for knowtedge
5-55
Advanced Web Programming 5-54
Node JS in cedWeb Programming Node JS in Detais
When user visits the web page a new session is created for the user and. Details X

cookie is
Command Prompt

assigned to it. So when next time when user visits the same page the.
page the
cookie 1nstall cookie-parser -save
checked and page view counter updated accordingly. is de1SExamples\studentcookie>npm
studentCookieel.8.8 No description

tudentCookie@1.0.8
No repository field.

5.10.2 Cookie c o o k i

age
e - p a r s e r g l

from 2
. 4 . 5

contributors and audited 51 packages in 1.173s


added 1 PpackaE
Cookie is a small piece of information used to store name-value pair. This conlu f o u n d v u l n e r a b i l i t i e s

is sent to the client with server request and stored at the client's machine. Fvo ta

when user loads the web site, this cookie is sernt with the request. This helps Every time D:NodeSExamples \studentCookie

track of the user's actions. eeping the cookie. The


file for setting the cookie and reading
Following example illustrates how to create cookie, display cookie data and clear i. Step 3: Now we will write a js
follows-
cookie. code is as
Step 1: Create a folder by suitable in current working
some

created a directory named studentCookie


name a
directory. I have appjs
const express require('express)
require('cookie-parser);
Step 2: Open the command prompt window and issue the npm init command for the const cookieParser =
Const app express()i
created folder. Refer the following screenshot -
app.use(cookieParser()

SGommand Prompt

wodeSExaples)studentCookienga init -y
rote to D:Viode)SExamples\studentCookie\package.json: app.get(/.(req.res) =>{
res.send(Cookie Demo");
studentCookie",
version1
description
aint index, js",
uripts var student {
,"test cho 1'Error: ne test specified" M exit r
rollno: "101
name: "Parth"
llcemse" IK
/Cookie is added
app.get(/setstudent,(req.res) = >

Wode Sxaolesistudentcookie Tes.cookie("studentData', student)


added to Cookie");
res.send("'Student data

Step 2: Install the packages express and cookie-parser


IDisplay Cookie
Comand Promn app.get(/getstudent,(req.res)=>
256 pies studentookiarpn install express res.send req.cookies);
ereated 4 lockile as packege
stadert(ookie.8.0 o desription
lock. json. You should coit this file.

ptadeetookieg18. N repository field.

pe4.17.1
dded parkages fron
fond 8 vulner biiatins
ntributors and audited s0 packages in 5.38s I/server listening
app.listen(B082, ()=> {
8082');
is listening at port
de llesiatadentokie console.log("Server

PUBLICATIONS-An up thrust
for knowledge
TECHNICAL
ancedWeb Programming 5- 57
Advanced Web Programming 5-56 Node JS in Node JS in Details
Details
and execute the js file as follows- localhost:8082/getstudent
Step 4: Now open the command prompt
Ceeman Pomode o C O localhost8082/getstudent
e samlesstadeetCokienode r
sa
erer is
listeeing port studentData": ("rollno" : "101","name":"Parth"))

Now open a web browser and type the url tor setting and getting the cookie
the demonstration
. Here is
Destroy Cookie

For deleting the cookie we use


locslhost8082
clearCookie(cookie Name)
C localhost8082 to delete cookie
Following code shows how a

Cookie Demo
app.js
constexpress require('express)
constcookieParser require(cookie-parser);
const app express();
app.use(cookieParser();

locaihost 8082/setstudent + app.get(/.(req.res) =>


res.send(CCookie Demo");
C o localhost 8082/setstudent

Student data added to Cookie var student={


rollno: "101",
name: "Parth"

IICookie is added
app.get(/setstudent',(req.res)> {
res.cookie("'studentData",student)
res.send(Student data added to Cookie'))

IDisplay Cookie
app.get(/getstudent, (req.res)>{
res.send(req.cookies)

TECHNICAL PUBLICATIONS-An up thrust for knowledge

TECHNICAL PUBLICATIONS An up thrust for


knowiedge
Advanced Web Programming 5-58 Node JS in Programming 5-59
Node JS in Details
Detals
localhost8082/getstudent X
Delete Cookie

app.get(/deletestudent, (reqres)->
res.clearCookie('studentData"); C Olocalhost:.8082/getstudent
res.send('Student data is removed from the cookie");

/server listening
app.listen(8082, ()=> {
console.log("Server is listening at port 8082):

Output

localhost8082/setstudent
C 0 localhost8082/setstudent 5.11 Design Patterns
Student data added to Cookie Definition of design pattern: Design pattern is general reusable solution to
commonly occurring problem within a given context in software design.
Ingeneral the pattern has four essential elements
Pattern name : The patterm name is used as handle to describe the design patterm. The
naming of the pattern increases the design vocabulary. Due to the name of the pattern it
becomes easy to think about the design and to communicate the design with the others.
Finding the appropriate name for the design pattern is one of the hardest and tricky part.
Problem: The problem describes when to apply the pattern. It explains the problem
localhost8082/deletestudent X X and its context. It might describe various things such algorithm for the problem, the
as

C localhost8082/deletestudent class or the object structure of the problem, it list down the conditions that must be
or can

followed before applying the pattern.


Student data is removed from the Solution : The solution describes the elements of the design, their relationships,
cookie
responsibilities and collaborations. The solution never describes the concrete design or

theimplementation because the pattern is like templates and it can be applied to various
problems in varied situations.
Consequence The consequences describe the results and trade-offs of applying
pattern. The consequernces for software often concerned with space and time trade-offs.
The listing of consequences helps in evaluation of the design pattern.
Let us discuss some of the popular design patterms and their implementations with the
help of Nodejs
(1) Singleton
The singleton is used when we need only single instance of a class. That means we
can not
create multiple instances. If there is no instance, a new one is created. But if there
is an existing instance then it will use that one.

TECHNICAL PUBLICATIONS- An up thrust for krnowledge


TECHNICAL PUBLICATIONS-An
up thrust for
knowledge
Advanced Web Programming 5-60 Node JS in e d Web Programming
5-61
Node JS in Details
design pattern, Details
Following is a simple example that illustrates the singleton callback): To listen to an event and react with
Step 1: Create a node js file that creates and returns a single instance of a conmpute on(eventName, a callback function.
) ng isa simple exam that shows how observer pattern,
This compute function computes
the sum of two numbers Follow
function.
m y O b s e r v a b l e . j s

sum.js = require('events');
function compute(a,b) { events
var
new events.EventEmitter();
retum atb; uar eventEmitter

module.exports.compute Compute; / user #1

Step 2: Now create another file named app-js, in which we will use require statement + user1 = function listner1() {
to console.log(user1 is listening.
get the above defined module. It does not matter how many times you will

equire this module in your application it


will only exist as a single incts.
ce
// user #2

app.js var user2


= function listner2(){
1/single instance only console.log(user2 is listening.);
varresultrequire(-/sum); instance is getting used.
I/Even though used multiple times,
a single
console.log(result.compute(2,3);

console.log(result.compute(10,20); /user #3
Output var user3 = function listner30 1
console.log(user3 is listening.);

Command Prompt

app.js event with the listener1 function


D:\NodeJSExamples \SingletonPatternEx>node Bind the connection
eventEmnitter.addListener(connection', user1);

with the listener2 function


p: NodeJSExamples\SingletonPatternEx / Bind the connection event
eventEmitter.on(connection, user2)

/ Fire the connection event

eventEmitter.emit('connection);

************

one Listener
Console.log("******** Removing
function
Remove the binding of listener1
event Emitter.removeListener('connection, user1):
2) Observer Pattern
console.log("user1 will not listen now. ):
he.observer pattern is a design pattern that defines a link between objects so eventEmitter.emit(connection');
This
whenone object's state changes, all dependent objects are updated automalticauy Adding new Listener
***
**)
console.log("*******
pattern allows communication between objects in a loosely coupled manner IAdd the binding of listener3
function
eventEmitter.addListener( connection, user3)
In and

them
this pattern, An object maintains a list of dependents/observers eventEmitter.emit('connection);

automatically on state changes. 1se the


use **************)
e e d it
to Removing all Listeners
In Nodejst make an element 'observable (our subject) we n
need console.log("********

needs:
Event Emitter class. This way, our service, will get exactly the methods it
TECHNICAL PUBLICATIONS-An up thrust
for knowledge

) emitfeventName): To emit an
event named 'eventName.
TECHNICAL PUBLICATIONS-An up thrust for knowledge
5-62
Advanced Web Progranmming Node JS ails anced Web Programming 5-63
Node JS in Details
Rermove the binding of listner1 function
eventEmitter.removeListener(connection, user2);
eventEmitter.removeListener(connection', user3) module.exports= Dell;

eventEmitter.emit(connection');
Output

HpJs
const Laptop require( JLaptop);
Command Prompt
myobservable. jss
p: ModeSExanples \0bservableExnode
user1 is listening. Hp extends Laptop {
class
user2 is listening.
******** Reaoving one Listener *****
constructor() {
super(HP
user1
user2
will not
is listenine.
listen now.

Adding new Listener**********


user2 is listening.
user3 is listenin module.exports Hp;
*************
* * * Removing all Listeners

D:Mode SExanp les \0bservableEx Lenovo.jsS


const Laptop require(,/Laptop);

class Lenovo extends Laptop {


(3) Factory Pattern
constructor(){
Factory pattern is
design pattern which is responsible for creating the instance
a super(LENOVO)
ot
several derived classes. Following example shows how to implement
factory pattern.
Step 1 We will create a parent class named Laptop. The code is as follows
module.exportsLenovo;
Laptop.js Step3: Now we will create one factory class named LaptopFactory. This class has a
create method that generates new Laptop based input string type.
classLaptop{ on

constructor(name) {
this.name = name.toString(): Laptop_factory.js
const Dell = require(./Dell);

const Hp require(/Hp);
Const Lenovo = require(./Lenovo');
showinfo(0{
console.log(Brand Name: "+this.name)
class LaptopFactory {
create(type) {
switch (type) {
module.exports= Laptop; case Dell
Step 2: Now we will create three more classes named: Dell, Hp and Lenovo that extc
returm new Dell();
case Hp
the above class
Laptop return new Hp();
case Lenovo:
Dell.js return new Lenovo();
const Laptop require(.Laptop default:
class Dell extends
Laptop(
constructor (){ console.log(Unknown Lapto brand...);
super(DELL)

TECHNICAL PUBLICATIONS An up thrust for knowledge


TECHNICAL PUBLICATIONS- An up thrust for knowledge
AvancedWeb Programming 5- 65
5-64 Node JS in Node JS in Details
Advanced Web Programming Details
nt-side caching is the
temporary storing of contents such as HTML pages, CSS
heets, JS scripts,
styleshe
and multimedia contents. Client caches help limit data cost by
= new
LaptopFactory(: keeping commonly. referenced data locally on the browser
module.exports

Now we will call the factory dlasses and try to display the conternts of tthese Leep
Step 4: in a app.js file.
showlnfo0 method Scaling
classes by calling
Scaling is used in node.js for increasing the performance and availability of the client
server application.
appj =
require(Maptop_factory);
const LaptopFactory
Scaling allows the Node.js to handle multiple requests simultaneously without any
LaptopFactory.Create(
Dell ): performance issue.
const Dell =

LaptopFactory.create(Hp);
const Hp =
There are two approaches used in scaling the node.js,
LaptopFactory.create(Lenovo);
const Lenovo
=

1) Horizontal Scaling: The horizontal scaling is a technique in which the application


const Dell2 =
LaptopFactory.create (Dell);
instances are duplicated to manage large number of incoming connections. This can
this
Dell.showinfo();
be done on single multi-core system or different machines can also be used for
Del12.showinío);
Hp.showinfof).
purpose.
Lenovo.showinfo():
Output
2) Vertical Scaling: The vertical scaling is a
technique in which the performance of
machine or its memory is increased.

scaling in node.js helps to increase the availability of the


server.
X Thus
Command Prompt

D: NodeSExamples \FactoryExample>node app.js


Brand Name: DELL
Brand Name: DELL
Brand Name: HP
Brand Name: LENOVO

D:NodeSExamples \FactoryExamp le.

5.12 Caching and Scalability


Caching
a cache,the
A cache is a
memory that stores the information during tun time. Dy u
server code
application returns the information from
memory instead of execub
process subsequent requests.
ne the serit

Node.js can be
optimized with caching services. Without a iromth
application will have to execute the
entire code and retrieve
i n f o r m a t i o n

database each time it


a processes request. TECHNICAL PUBLICATIONS- An up thrust for knowedge

TECHNICAL PURUCATIOnun
5- 66
d Web Programming Node J.
Notes

6 Database Programming with


Node JS and MongoDB
Syllabus
Basics of MongoDB, Data types, Connect Node JS with
MongoDB, Operations on data (Insert,
Find, Query, Sort, Delete, Update) using Node JS.

Contents
6.1 Basics of MongoDB

6.2 Data Types


6.3 MongoDB Installation

6.4 Database Commands


6.5 Connect Node JS with MongoDB
6.6 Operations on Data using Node JS

(6- 1)
TECHNICAL PUBLICATIONS An up thrust for
knowledge
Advanced Web Programming 6-2 Database Programming with Node JS
JS and MongoDB
and
n c e dW e b P r o g r a m m i n g 6-3 Database Programming with Node JS and MongoDB
6.1 Basics of MongoDB SQL Termns MongoDB Terms
MongoDB is an open source, documentbased database.
.Itis developed and supported by a company named 10gen which
h is now DatabasesS Databases
now
MongoDB Inc. known as
.The first ready version of MongoDB was released in March 2010.
Why MongoDB is needed7 Tables Collections
There are so many efficient RDBMS products available in the market, then wl
need MongoDB? Well, all the moden applications require Big data, faster
and flexible deployment. This need is satisfied by the document based
deuale
Rows Documents
MongoDB. databae se
like
Features of MongoDB
1) It is a schema-less, document based database system. Columns Fields
2) It provides high performance data persistence.
3) It supports Fig.6.1.1
multiple storage engines.
4) It has a rich Consider a student database as follows
query language support.
5) MongoDB provides high availability and redundancy with the To the left hand side we show the database in the form of table and to the right hand
help of side the database is shown in the form of collection.
That means it creates
multiple opies of the data and sends these replication,
different server so that if one server fails, then the data is
copies to a Collection

server.
retrieved from another
id 5271191e810c1934SdebEDeg.
Name uter Eagineering
6) MongoDB provides horizontal scalability with the Address gneering.

Document 1
means to distribute data on help of sharding. Sharding unelLanel
ineZ Lanez
Name
multiple servers. Course
AddresslLine1| Addressline2
7) In
MongoDB, every field in the document is indexed as Ankita Computer Engineeringg Lane1 Lane2
55slesloci9sdeBs0ea
to which data can be
searched
primary or secondary. Due Prajkta Mechanical Engineerin9 Street1 Street2 Name. Prara,
CourseMechanical Engineering
Document 2
very efficiently from the database. Kavita Civil Engineering Road1 Roadz Seet
ine~:Steer2
sQL Structure Vs.
MongoDB
Following figure shows the terms in SQL are id S07141e510c19729dey5Ded,
Narme avita
treated differently in MongoD5. In Fields Coursenl Engineering
MongoDB the data is not stored in tables, instead AddressS
inel-a
Document 3
of that, the there is a concept
collection which is
analogous to the tables. In the caue
called documents in same manner the rows in RDBMD
MongoDB, likewise the columns of the record in RDBM> are a calle
fields. Fig.6.1.2

Review Question
|1. List and explain various features of MongoDB.

TECHNICAL PUBLICATIONS An up thrust for


TECHNICAL knowledg
PUBLICATIONS An up thrust for
knowledge
6-5 Database Programming with Node JS and MongoDB
Advanced Web Programming 6-4 ode
Detabase Programming with Node JS
JS and Mand
v a n c e dVWeD P r o g r a m m i n g

MongotDR
6.2 Data Types Open File SecurityWarning

Following are various types of data types supported by MongoDB. Do you want to run ths tile?

1 Integer: This data type is used for storing the numerical value. Name 0adsimongodb-windows 86.64-444-signed.msi
Publisher: MongoDs, Inc
2 Boolean: This data type is used for implementing the Boolean values ie
Type Windows Installer Package
false. From CAUsers\DELL\Downioadsimongodb-windows xa

3) Double: Doubleis used for storing floating point data


Run Cancel
String: This is the most commonly used data type used for
for storine
storing tha
the
string Always ask before open1ng thes file
values
While files from the Internet can be usetul, this fie type can
5) Min/Max keys : This data type is used to compare a value against the lowect potentialy harm your computer. only nan software rom
or publishers you trust What s the a
highest BSON element.

6) For list of When the installation process starts following window gets popped uup
Arays: storing an array or
multiple values in one
key, this data
used.
type is
MongoDe 444 2008RZPIus SSL (64 bt) Setup

7 Object : The object is implemented for embedded documents.


Welcome to the Mongo08 4.4.4
8) 2008R2Plus SSL (64 bit) Setup Wizard
Symbol: This data type is similar to string data type. This data type is used to store
specific symbol type.
The Setup wzard well nstad Monga08 444 2008R2Pus SSL

9) Null: For storing the null values this data type is used. (64 bt) an our cmputer. Cd Next to continue ar Cancel to
e t the Setup Wizard

10) Date : This data type is used to store current date or time. We can also create our
own date or time
object.
11) Binary data: In order to store binary data we need to use this data type.
12) Regular expression: This data type is used to store regular expression.
6.3 MongoDB Installation
For installing the
MongoDB go to the web site
Just click Next button and choose the
on
Complete option for installation.
https://www.mongodb.com/try/download/community
Choose
normal procedure of installation by clicking the Next button.
Follow the

Software->Community Server. The executable file gets downloaded.


Run to execute it.
k on
Finally you will get following window on successful installation.

TECHINICAL PUBLICATnONS An up
thrust for knowledge
TECHNICAL PUBLICATIONS An up thrust for knowledge
Advanced Web Programming 6-7 Database Programmingith Node JS and MongoDB
6-6 Database Programming with Node Web Programming
AdvancedVWeb
JS a
MongoDB 4.4.4 2008R2Plus SSL (64 bit) Setup MongoDB System Properties

Advanced
System Protection Remote
Computer Name Hardware
Completed the MongoDB 4.4.4 You must be logged on as an Adm1nistator to make most of these changes.
2008R2Plus SSL (64 bit) Setup Wizard Penomance
and virual memory
Visual effects. processor scheduling. memory usage.
Cic the Finish button to
eat the Setup Wizard.
Settngs.

User Profles
Desktop seüngs related lo your sign-in

Setings

Startup and Recovery


failure. and debugging infomabon
System starnup. system

Setings
Environment Variables.

Back Finish Cancel


OK Cancel Appy
Click on Finish button,
complete the installation process.
to
In order to
verify whether it is installed correctly or not, tnvitonmcnt Variaoies

window and execute the command go to command prompt


for mogod.exe file's version. It variabies for DEL
is illustrated user

follows as
Variable
Chocolateylast PathUpdate
Value
132550151847677214

C A P r o g r a m F i l e s J a v a y d k - 1 5 0 . T \ b i n \ m y s q i - c o n n e c t o r - j a v a - 5

spath
Command Prompt One Drive
C\Users\DELL\ONeDrive

C\Users\DELL\OneDrive
Microsoft
Kc)
Windows [Version
7620 Microsoft (orporat10.0.19041. 804]
ion. All rights reserved.
OoeDriveConsumer C\Users\DELLJAPpData\Local\ Microsoft\WindowsAppsCAUs
CAUsersDELL\APpData\Local\Temp

TEMP CAUsers1DELAppDatalLocan femp


:1Users \DELL»"C:
kdb version v4.4.4 \Program Files\MongoDB \Server\4.4\bin\mongod.exe"--vers ion
TMP

Build Info: ( Issue this command New Edit Delete

version" "4.4.4".
eitversjon": "8db 3Ga6
s0dules": 0, 3dbla9d84bdcad@c83369623f 708e0397*, System
variabies

allocator": "temal loc", And you will get this result, Variable
Value
VPrOgramData\chocolatey
hviroOent":
Chocolateytnstall
distmod": "windows", if mongodb is installed dasspath
CProgram FilesJvaydk- 150 1binmysql-connector-java-s
C\Windows\system32\cmd exe
distarch°: "x86_64", ComSpec
target arch": "x86 64" Correctly !! DriverData
WindowsSystem32\DriverstDnverOata
CIProgram FilesJavaidk: 15.0.1
A AVA.
8
NUMBER OF PROCESSORS
Windows NT
Delete

OK Cance

To set the environment variable, Open System Properties and click on


Environme
Variables
TECHNICAL PUBLICATIONS-An up thrust for knowledge

TECHNICAL PUBLICATIONS- An up thrust for knowledge


Advanced Web Programming A d v a n c e dW e DP r o g r a m m i n g 6-9
Database Programming with Node JS and MongoDB
6-8 Database Programming with Node JS and -

Then click on the MongoDR


path variable and set the C mongodb.com/try/download/community
Ed1t envifonment varao.e
path of MongoDB by clicking New
button. Nominate
mongoDB. Cloud
%USERPROFILE%JAPpData\ LocalMicrosoft\WindowsApps
\ Software
PTicing Learn Solutions Docs

C\UsersDELLAppDatalRoaming\npm
CAProgram Files\MongoDB\Server\ 4.4\bin
New
Community Server
r e e and open docuTent catabase
Edit

Enterprise Server
Browse.. cvarced features and Sc ty

Developer Tools
Delete
Cornect, cortgue ard wor wth MorgoDB

Compass
GUl tor MongoD8
Move Up
VOngoJE
Ops Manager
Move Down On-r em maragermert patorm tor Mongobe

MongoDE Connectors
Easy ntegratons to out data estate
Edit text
MongoDB of
offers the flexible document model along with ad hoc quenes. indexit
access and analyze yOur data As a distnouted sy stem you get high a

As mine is a Windows
Select any suitable version as per your operating system.

operating system of 64 bit, I have chosen following option.

OK Cancel Available Downloads

Then sinmply continue Version

variable window.
clicking ok button and
just come out of the 1.26.0 (Stabie)
environment
Restart your command Pia:rorm

prompt window and now Windows 64-bit (7+) (MS)


and then
mongo at the simply issue the command mongod
command prompt window. It
will recognise this
prompt will appear command and
Package
msi

Installing Mongodb Compass


This tool is
(Graphical Tool) Download Copy
very useful for
graphical user interface. handling MongoDB database with the help of simple
Documentation

Archived releases

TECHNICAL PUBLICATIONS-
An up thrust for knowledge
TECHNICAL PUBLICATIONSAn up thrust for
knowledge
Advanced Web Pius 6-11 Database Programming with Node JS and MongoDB
6-10 Database Programming with Node JS and
a n c e dW e b Pogramming

Click on the Download


installer file which is
button. The exe tile will
get downloaded. Double
MongoDB click
Finish
button
ton. Just click the Start button of Windows, locate MongoDB
downloaded in your PC and the installation click tthe Just Anplication and simply click it to start the GUI for Mongo DB. You will get
Compass will start. process for Monosh
C o m p a s s A P p l i c a t i o n .

goDB f o l l o w i n gG U I

DMongoD8 Compass Setup


MorgoD8 Compass-Connect

Cornect View Help

Welcome to the
N o w C o n n e c t o n

Setup Wizard MongoDB Compass New Connection FCRTS


Fl in connection helds individually

Recents
Paste your connecbon s t i n g R V o New to Comoass and dont have a cluster
The Setup Wzard will Standard O)
install MongoD8 u oont r a t y tave a chuster. you can
computer. Oick Next to continue Compass on your
Cancel to eat the Tle re 'a ve vag kngl9 Ala
wzard or
Setup eg mengc setrame pastword glus
CREATE FOEE CLUSTE

Cornec

How do hrd my conrecion stngn


Ades?

a u hae r Auias o u s g o e Aa

How so format my connecon singS

ack
Cancel

Simply go on
clicking Next button, and then click on the install button
subsequent window. Finally you will get the on the
If we click the connect button then
we get following screen
installation completion screen.
MongoDB Compass Setup MongoDB Compass - locatnost27017

onnect Vew Help


Databases Pertermace
Local

Completed the MongoDB Compass Setup 3 DES cOLECTIONS C CREATE DATABASE

Wizard AVORIE Database Name


Storage s Collections

oST
localhost27017 20 0KB
mun
Cick the Finish button to ext
the Setup Wzard. USTER
Standalone
24.0NB
EOTON
contig
MongoDB 44.4 Community
20.0KS
local
E o r your dats

admun

conlig
OCal

Enish Cancet

knowledge
PUBLICATIONS An up thnust for
TECHNICAL PUBLICATIONS- An up thrust for
TECHNICAL

knowledge
Advanced Web Programming Node 6-13
12 Database Programming ith JS
and MongoDB Advanced Web Programming Database Programming with Node JS and MongoDB
6.4 Database Commands
Nlate that in above listing we can not see the mystudents database. This is
In this section will discuss how to create and handle database in
because we
not inserted any document into it. To get the name of the database
we
ase
various commands. MongoDB
MongaDa .

using
have

of show command, there should be some record


means of
in the listing by
s
present in the database.
(1) Create Database
(2) Drop Database
Open the command prompt and type the command mongo for
starting the The dropDatabase() command is used to delete the database. For example
The> prompt will appear. For
creating a database we need to use the "use" moneano
DB.
command
Syntax Command Prompt mongo X
use Database name >use mystudents
switched to db mystudents
For example db.dropDatabase()
"ok": 1}
Command Prompt mongo
X
use mystudents
switched to db mystudents

(3) Create Collection


There are two approaches of creating a collection
To check the currentdy selected database, use the
command db Method 1: We can create a collection directly when we insert a document.
Command Prompt mongo
db K Syntax
mystudents db.collection_name.insert({key1value1,key2:value2})
For example

Command Prompt mongo X


We can see the list of databases use EmployeeDB
present in the MongoDB using the command show Switched to db EmployeeDB
dbs
db.myemp. insert({"empname": "AAA","Salary":19000))
MriteResult({ "nInserted": 1 })
Command Prompt mongo
> show dbs

EmployeeD8 0.000G8
StudentDB1 0.00068B
admin 0.00068
config 0.00068
local .00068

We can
cross-verify whether the collection is created not
or by using following
command

TECHNICAL PUBLICATIONS- An up thrust for knowledge


TECHNICAL PUBLICATIONS -
An up thrust for
knowledge
Advanced Web Programming a n c e d W e b P r o g r a m m i n g
6-15
Database Programming with Node JS and MongoDB
6-14
Database Programming with Node JS and Mone For Following
example-Follow command shows how to create collection in a database using
Command Prompt mongo -

MongoDB
db.myemp.find () D
explicitc o m m a n d

_id": 0bjectId(
6053126clac6ebe 32be47c1b"), "empname" "AAA", "Salary" ommandPrompt mongo X
10000
u s e m y s t u d e n t s

mystudents
to db
switched
db.createCollection ("Student_details")
ok:1)

Note that the one


named myemp. document(analogous to row) is getting inserted in the (4) Display Collection

collection the created collection use the command "show collections" at the command
Method 2 : We can
Tocheck
create collection explicitly
using createCollection command. prompt
Syntax
Command Prompt-mongo
db.createCollection(name,options)
where
use mystudents
switched to db mystudents

name is
db.createCollection("Student_details")
the name of collection "ok" 1 }
show collections
options is an
optional field. This field is used to Student details
maximum number of documents and so on. specify some parameters such as size,
Following is a list of such
options.
Field
Type
Description (5) Drop Collection
the collection completely
capped Boolean collection command is actually used to remove
Capped collection is a fixed size collection. It The drop from database.
automatically command removes a collection completely
overwrites the oldest entries when it
reaches to maximum size. If rom the database. The drop
it
is set to true,
enabled a capped collection.
value as true,
When you
specify this Syntax
you need to specify the size db.collection name.dropl)
autolndexID parameter.
Boolean This field is For example
required to create index id automatically. Its default
value is false. Command Prompt mongo
Size db.Student_details.drop()
Number This value indicates the
maximum size in bytes for a clapped
rue

collection.
Max
Number It
specifies the maximum number of documents allowed in capped
collection.

TECHNICAL PUBLICATIONS An up thrust for knowledge


TECHNICAL PUBLICATIONS- An up thrust for
knowledge
le JS and
Advanced Web Progranmming -16 Database Programming with MongoDB Advancea Web Programming 6-17 Database Programming with Node JS and MongoDB
We can verify the deletion of the collection by using now
"show
collections in the
collections"
C o m m a n d Prompt mongo
database. var allstudents =

() Insert Documents
The document is inserted within the collection. The document is analogous to rovi
ows i BBB"
: 20
database.
Syntax name CCC"
db.oollection name.insert({key.value} age:19

For example
name "DDD",
"age":211
ommand Prompt mongo
db.Student_deteils.insert(("neme":"AMA","oge" : 22))
eriteResult( "nInserted 1 }) db.Student_details.insert (allStudents);

Then you will get

Command Prompt mongo


db.Student_details.insert (allStudents);
We can verify this insertion by issuing following command BulkiiriteResult ({
writeErrors" [ 1,
"writeConcernErrors" [ 1
|Command Prompt mongo "nInserted"

db.Student details.find() nUpserted"


s d 06ject 1d("s053957d1acbebe37be4ci«"), "nene: " , "ee: 22 ) "nMatched"0,
"nModified" :0,
"nRemoved":,
upserted" : [

In above screenshot, as you can see that it shows number 3 in front of nlnserted. This
Inserting Multiple Documents means that the 3 documents have been inserted by this command.
i s poseible to insert multiple documents at a time using a single commar To verify the existence of these documents in the collection you can use find command
Following screenshot shows how to insert multiple documents in the existing colletion as follows-

TECHNICAL PUBLICATIONS An up thrust for knowledge


EONIGAL PUBLIGATIONS An up du lor knculedp
Advanced Web Programming 18 Database Programming with Node JS and AdvancedWeb Programmingg 19
Database Programming with Node JS and MongoDB
MongoDB
Command Prompt - mongo
AMow using find0 command we can
verify if the desired data is deleted or not.
db.Student_details.find()
id" 0bjectId("6053357dlac6ebe32be47c1c") , "name" : "AAA", "age" Command Prompt mongo
22 }
"_id" : 0bjectId("605339001ac6ebe32be47c1d"), "name" "BB8", "age" db.Student_details. find ()
X
20 }
"_id":ObjectId("605339001ac6ebe32be47cle"), "name" "CCC", "age" 19
dD. biectId("6853357dlacóebe32be47c1c "), "name "AAA", 'age" : 22 )
"id": ObjectId("605339001ac6ebe32be47c1f "), "name" "DOD", "age" Objectid("605339001acbebe 2bea/cld"), "name "8B8", "age" : 20)
21 1 4 0bjectid("605339001ac6ebe32be47c1f"), "nase": "000, "age": 21

Deleting only one Document


(7) Delete Documents
Sometimes the delete criteria matches for more than one records and in such situation,
For deleting the document the remove
command is used. This is we can forcefully tell the MongoDB to delete only one document.
command. the simnlect
npl est
Syntax Syntax
db.collection name.remove(delete criteria, justOne)
db.collection_name.remove(delete criteria) The justOne is a Boolean value it can be 1 or 0. If we pass this value as 1 then only one
For example
document will get deleted.
First of all we can find out the documents
command present in the collection using find) For example
Command Prompt mongo
Command Prompt mongo db.Student details.remove({"age" :20),1)
db.Student _details.find () WriteResult(( "nRemoved": 1 )
idObjectid("6853357dlac bebe32be47clc"), "name "AAA", "age 22
i10:0jectld(6853398elacbebe32be47c1d°
d: ), "name" BBB,age
id: CbjectId("585339001ac6ebe32be47cle" ), "name Med
20 )
age": 19 }
0bjectId("685339001acbebe32be47c1f"), "name" "0DD", "age": 21
}

Now it can be verified using find0 command as follows


Now to delete a record with name "WWWN" we can issue the command as follows- Command Prompt mongo
Command Prompt mogo db.Student_details.find()
db.Studeent details.remove(("name": "M")) i d : 0bjectId("6053357dlac6ebe32be47clc). nane AAA age 2
id": ObjectId("605339081ac6ebe32be47c1F), nane DOD
MriteResult(( "nRemoved": 1}) id:0bjectId("6854586eS783af 51edeb3774"), "name" : "EEE"

TECHNICAL PUBLICATIONS An up thrust for knowledge


TECHNICAL PUBLICATIONS
An up thrust
for knowiedge
Advanced Web Programming
tvanced Web Programming 6-21
Database Programming with Node JS and MongoDB
6-20 Database Programming with Node JS and Monar the
Note that there were two And we want name "CCC" to "WWW", then the command
records that were
matching with age 20 with name
ngoDb can be
and "EEE", but since =

the single record


we have
passed justOne attribute as 1, "BBB issued a s

having name "BBB"


we
get the result by
deletino
ng Command Prompt mongo
x
Remove all the documents
student_details.update({"name": "CcC"},($set:("name":"M}
Re sult({ "nMatched": 1, "nupserted" 0, "nModified" :1 })
It is
possible to remove all the documents present in the
single command. collection with the
help a

Syntax
db.collection_name.remove({})
For example
This can be verified as

Comand Piompt mogo


db.Student _details.remove({}) Command Prompt mongo
WriteResult(( "nRemoved": 3 }) X
db.Student_details.find() db.Student_details.find()
id": ObjectId("6053357d1ac6ebe32be47c1e"), "name" "AAA, "age": 22
id" Objectid("605339001ac6ebe32be47c1d"), "name" "888, "age 20)
id" ObjectId("605339901acóebe32be47c1ie"), "name": "M, "age: 19
"age":
_id": ObjectId("605339001ac6ebe32be47c1f"), "name" "DDD", 21 }

(8) Update Documents


For
updating the document we have to Thus the document gets updated.
document can be updated. provide some criteria based on which the document. But we can update
By default the update command updates a single
to add {multi:true)
Syntax multiple documents as well. For that purpose we have
db.collection_name.update(criteria,update_data)
For
For example
example Suppose the collection db.Student_details.updatel{"age":21)Sset:{"age":23}}{multitrue})

"Student_details" contain following documents


Command Prompt mongo (9) Sortingg
the sort(0 method for arranging the
documents in ascending or descending
db.Student_details.find()
id
We can use

id" ObjectId("6853357dlacbebe32be47c1c"), "name" "AAA", "age": 22


order based on particular field of document.

"_id": ObjectId("685339001ac6ebe32be47c1d"), "name"


ObjectId("60533900lac6ebe32be47cle"
"_id": ObjectId
("605339001lac6ebe32be47c1f"),), "name"
"name"
"8BB", "age" 20 )
"CCC", "age"
:

19
Syntax
ascending order we should pass
value 1
:
"DO0", "age" 21 For displaying the documents in

ab.collection name find(.sort( {field name: 1) order of the field.


will be displayed in the descending
If we pass-1 then the document

For example
documents
Suppose the collection contains following

TECHNICAL PUBLICATIONS-An up
thrust for knowledge

TECHNICAL PUBLICATIONS An up thrust for


knowledge
Advanced Web Program. 6-22 Database Programming d v a n c e dW e b P r o g r a m m i n g 6-23 Database Programming with Node JS and
with Node JS and MongoDR ongoDB
Commans Ponpt m DB
Student details.find()
eeNeKSR atSlased37S"),
Connect.js

"AAA", MongoClient = require(mongodb').MongoClient;


6 jctie( WSAse73SRUfSladed i777* ),
jxtle( SAe?eSRufSleded II 78*). url mongodb:/localhost:27017/;
jcele( WASAiSNutsledebi79*). FE 21)
jectid(S4St17SNYtSledeb377a),
ojctld(°ISf1 SSiaf$ledeb377). 'nane:
/cteate database

G6, 'age" : 22 ) apgoClient.connect(url, function(err, db) {


if(err)

Now throw erT


to sort the data in
descending order dbo = db.db('studentDB"):
var
Command Aonpt mon -

console.log("Connected with Database"):


at_details.fine().sort({"age:-1})
d0xtie( wSASt12578af5lededa77a"), "FFF"
:
Ojectid("8545e73578afSledeb377*),
i
"nane":
eiksNUfSleded 3775*), *rame AAA
age
°CC°, *age" : 23 )
: In above code,
:jectId(*RS45+la5783afSledeb377>*), "nane": "GGG°, 'age" : Program Explanation
iC
:jectie( 6S4SeSSTSiaf
5laded3776*), "name :"868",
22 }
bJectia( ESRiS78ist5leded3779*). have to import the module 'mongodb' using require. Thus we are
i:
ejectIo("s8S4e?dsNisf5ledeb37 7s*),
"name: "EEE,
"rame"
'age": 1) First of all, we
DO0, age : 20
creating MongoDB client.
2 Then specify the URL for MongoDB by means of hostname(localhost) and port
number on which MongoDB is running (27017). This is a path at which we are

going to create a database.


Inside this function
3) Then we areusing connect method by passing the above URL.
a database object is created by a database name "studentDB'.
Note that before execution of the above code, it is necessary to install the mongodb

If we want to
package using the following command at the current working directory.
display data in ascending order we issue Prompt:>npm install mongodb
following command
Commanc onp nogo
db.Student_details.find().
_id : sort({"age":1}) 6.6 Operations on Data using Node JS
i d Objectid("6545e74578 3af51edeb3778"), DOD, age 20 The CRUD operations are performed in collaboration with Nodejs
and MongoDB. The
jectId(R545e695783af51edeb3776"),
:

"nane
4ic:jectId("58545f©35783af5ledeb3779"),
_ic: oo
i
nae
jectIa("s8545e5<57siaf51edeb3775"), "nase
: "BBB", 'age"
"EEE,
AA", "ege21
"age" 2
: 21
CRUD stands for Create, Read, Update and Delete operations.
'id: 0jectId(6ES45f1a5783af5ledeb377o"),
"name "G& these operations on the database with
: 0jectld("68545e73578 3af 51edeb3777*). "na will discuss how to perform
CCC' °Ee n this section we
("i
0bjectia(6545f125783af51edeb377a"), "name" :
"FFF", "age
the help of simple demo applications. installed in
we need to have MongoDB
Prerequisite: For performing these operations the
(It is a graphical tool) to verify
our machine. One must also install MongoDB Compass

operations performed by node.js on MongoDB.


6.5 Connect Node JS with MongoDB Example Code: In this example, we will create a Student database with two
fields -

For
connecting Node.js with
MongoDB we need
name and ity.
using following code. MongoClient. This can be created
Creation of Database
name as Student_Info. For that
Step 1: We will create a database studentDB and collection
I have created the folder by a

urpose make a folder in your current working directory.


ame StudentDBExample.
TECHNICAL PUBUCATIONS-An up thrust fn - TECHNICAL PUBLICATIONS-An up thrust for knowledge
Advanced Web Programming 6- 24
ed Web Pogrammin9
6-25
Database Programming with Node JS and MongoDB
Database Programming with Node JS and
Step 2:Open the command prompt go to the
commandds path of StudentDBExample. MongoDB Then specify theURL forMongoDB by means of hostname (localhost) and port
And isSitoe 2)
the her on which MongoDB is running (27017). This is a path at which we are
DINodeJSExamples StudentDB EXample> npm init
And press enter create a database.
key to
accept the default values. going to
By this package.json file
Step gets creat a Then we are using connect method by passing the above URL. Inside this function
3: Then install the
mongodb module using following command eated.
D:ANodeJSExamples\StudentDB EXample > npm install mongodib
a database object is created by database name "studentDB"
a

Step 4 Now create a


node.js file for a Then using the method createCollection for database object we can create a
follows- creating a database and collection.
The code :
s as collection inside the database "studentDB". The first parameter passed to this

create.js method is name of the collection. Note that here the collection name is
var MongoClient require(mongodb).MongoClient; "Student_Info".
var urlmongodb:/Nocalhost:27017/:
Ilcreate database 5) The message "Collection Created" is displayed on the console using console.log
MongoClient.comnect(url,
if
function(er, db){ method.
(err) throw err;
var dbo db.db('studentDB'); Insertion of Data
dbo.createCollection("Student_
iferr) Info",function(err,res) We can insert one document or multiple document at a time. First of all we will see the
throw err; code for inserting one document inside the above created collection.
console.logCollection Created')
insert.js
db.close();
var MongoCient recquire(mongodb).Mongo Cient;
varurl"mongodb://localhost:.27017;
Command Prompt
Output Iinsert
p:
Wode)SExamples \StudentoBEXample>node create.js MongoClient.connect(url, function(err, db) {
node:4968)
in a [AOKGOOB
version. ORIVER) Warning: Current Server if(err) throw err;
future To use the new
Discovery and
Monitoring Monitoring
Server 0iscover and
engine, passengine
is
option (deprecated, and will truereaoved
(Use node structor. be
(Use node
--trace-warning. useUnifiedTopolog: var dbo db.db("'studentD®');
collection Created to
show where the warning was
to t

created)
D: Mode var mydata =
{ name: "AAA", city: "Pune'}:
6Examples \StudentDBEXamp le. Note that the function(err res{
collection is dbo.collection("'Student _Info").insertOne(mydata,
created for the database if(err)
throw err,

console.log('One document Insertedi!l");


Program Explanation : In above
code, db.close()
1) First of all, we have to
import the module 'mongodb' using require. Thus we are
creating MongoDB client.

thrust for knowledge


TECHNICAL PUBLICATIONSAn up
TECHNICAL PUBLICATIONS An up thrust for
knowledg
Advancod Wob Programming 6-26
Node JsJS and
Database Programming with Node AdvancedWeb Programming 6-27 Database Programming with Node JS and MongoDB
Output MongoDB city: "Ahmedabad"
(name:"EEE,
JConimard ronpt

P: Mode JSExamples 1Student 0BEXanp le vnode insert.js dbo.collection(


lection("Student_Info).insertMany(mydata,function(er,res){
(node: 10812) [PONGO0B DRTVER] Marninc. Current Server Discovery and Honitoring
in a future
vers ion. To use the new Server Discover ond Honitoring engine, passengine is
option
deprecated, and ...

the MongoClient construc tor. useUnifiedTonoilogy. be if(err


ren
(Use node -trace -warnings to show here the
marning true emoved throw e r
pne docunent Inserted! ! was created) ) to console.log("Number ofrecords inserted are: "+res.insertedCount);
p: Mode SExamp les \Student06E Xamp le>
db.close():

Output
Program Explanation : In above code,
1) First of all, we have to Command Prompt
import the module 'mongodb' using require. Thus
creating MongoDB client. we ar
NodeJSExamples \StudentDBEXample>node insertmany.jis
re ode 6916) [MDNGODB ORIVER] Narning: Current Server Discoveryand Monitoring engine is deprecated, and ill be renoved
2) Then
specify the URL for a future version. To use the Server Discover and Honitoring engine, pass option ( useinifiedTopology: )to t
new true

MongoDB by means of he MongoClient constructor.


hostname(localhost) to show where the warning created)
was

number on which (Use node-trace-warnings


MongoDB is running(27017). This is a
and por
port Number oft records
inserted are: 4

database exists. path at which Our


p:Node3SExamples\StudentDBEXamples

3) Then we are
using connect method by
a database object is created passing the above URL. Inside
this
by a database name
functionn
access to studentDB "studentDB". Thus now we Program Explanation : In above code
can
4) Then a
JSON object is in the form We have created array of values in JSON object as Follows-
the form of document. (name:value).. We insert data in the var mydata =I
This document is collection in
created in the form {name: "BBB", city: "Mumbai"
mydata object is created with some of JSON. Hence the {name: "CCC", city: "Chennai" },
values.
5) This mydata is name: "DDD", city: "Delhi" }.
inserted into the collection
In the same
manner we can
using insertOne method. name: "EEE", city: "Ahmedabad" }
insert
illustrates it. multiple documents at a time.
Following code
command we can insert all the above documents at a
Then using the insertMany
insertmanyjs
var time
MongoClient require(
var

IAnsert
url mongodb).MongoClient;
"mongodb://localhost: 27017 dbo.collection('Student_Info").insertMany(mydata,function(err,res)

MongoClient.connect(url,
if
(err) throw function(err, db) { This program execution
can be verified in MongoDB compass.
er;
var dbo db.db/'studentDB')
var mydata=
name: BBB', city: "Mumbai'
Dame: "CCC, city: "Chennai" }.
{ name: DDD', }.
city: 'Delhi" }.
thrust for knowledge
TECHNICAL PUBLICATIONS- An up
TECHNICAL PUBLICATIONS- An up thrust for
knowledge
6- 28 Node JS
Database Programming with Node JS and vanced Web Programming
6- 29 Database Programming with Node JS and MongoDB
Advanced Web Programming and
rOTAL BIZE AV s Z
MongoDB Output
studentDB.Student_Info ocuMET0 OB OB
NDEXES
oTAL SIZE
4 AVG
Valldation
OKB 4
S12
X
Documet gatons Schema Explain Plan Indexes
UKD Command Prompt

OPTONS NodeJSExamples \StudentDBEXample>node display.js


FIND RESET p:Woo720) MONGo0B DRIVER] Marning: Current Server Discovery and Honitoring engine is deprecated, and will be removed
engine, pass option (useUní fiedTopology:true } to
ADD DATA E L0 C Displayung documents *>od nin future version. o use
new Server b s c o v e r àno
tne
Poni toring
CREFRESM
RE 1ient construc
tnE d e --trace-warnings. to show where the warning was created)
ojectle( "esso442fel4s02a ic99e") Note that all the
name: AA, city: Pune )
id: 6055d442fel4802ajc99cBe, documents of the
dty
id: 6055d5000a8ad71be46165t6,
name:
BBB City: t b a i )
id: 6055d5000a8ad71be46165t7,
name: CCC, city: 'Chennai} collection Student Info
name: 0 0 , city: Delhi })
i d : 605Sdse06a8ad /1b64b16t8, are displayed.
14:ojecuo("esAMaiad 7IDO46]65t6") name: "EEE, city: "Ahme dabad'
i d : 605sdse00a8ad 71be46165t9,
null

d: 0}ectidCeessdsevasad7 1bedo16sf7")

city: Thermal
In above code,
Program Explanation :
'mongodb' using require. Thus we are
. bjectie( "605s4se00aSad 71be46165f8* 1) First of al, we have to import the module
1ty DIhi
creating MongoDB client
14:ojetld(
"s05Sdse0naiad 71bea6165f9") 2) Then specify the URL for MongoDB by means of hostname(localhost) and port
at which our
ity: " dabad
number on which MongoDB is running(27017). This is a path
database exists.
above URL. Inside this functior
3) Then we are using connect method by passing the
Read Data "studentDB". Thus now we ca
a database object is created by a database name
We can read all the documents of the collection using find method. access to studentDB.
th
simple Node.js code that shows how to read the contents of the
Following is a
4) Then for reading the contents present in the
documents of the collectiorn we use

database cursor is created for reading


each record(document) of th
find) method. The
display.js
var MongoClient require('mongodb).MongoClient; collection.
var url var cursor = dbo.collection("'Student_Info").find({})
"mongodb://localhost:27017:
=

within a callback function.


I/Read Then using cursor.each function, each document is displayed

MongoClient.connect(url,
if function(er, db) { Updating Data
(err) throw er;
the document using updateOne method.
var dbo db.db('studentDB"): We can change one or more fields of
var cursor =

dbo.collection('Student_Info").find({})
cursor.each(function(er,doc){ update.js
console.log(doc): var MongoClient = require(mongodb).MongoClient;

db.close(): v a r u r l "mongodb:/nocalhost:27017/:

I/Update
MongoClient.connect(url, fnction(err, db) {
if (err) throw err;
var dbo = db.db('studentDB');

var mydata = { name: DDD"};


newdata =
{$set: {name:"TTT,city:"Jaypur}}
var

thrust for knowledge


TECHNICAL PUBLICATIONS-An up
TECHNICAL PUBLICATiONS An up thrust for
knowledge
6 30 Oatabase AdvancedWob Programming 6 31 DatobaseIProgramming with Node JSand MongoDe
Programing with Node JS md
do.colection('Sudent nioyxdateOneamydata,newdata, tunction(err,.reu)( Momo In above code
Explanatlon:
Program
console JogOne document Updatedil"'k
We are updating one document using updateOne method. This method require two
ameter first one is the existing data, and second one is the new data which you want to
dh.close( param

This can be done with the help of following lines of code


ut in place of the existing one.

varmydata-(name "DDD'}; lexistingrecord vwith name= "DDD"


Output
var newdata {$set: (name: TTT",city'Jaypur}} /lreplace it by a new data

Commar Pompe
Then updateOne method is called by passing these two parameters.

D: VRode
SEuaples\StudentDEEXpiemode
(node 1226) update.js
OEDS ORIVE] aming (urrent Sever
Deleting Data
in afuture version To use the new Dscovery and Nonitor ing
Aonitor ing engine, passengine
1s
the Mcrgotlient constructur.
Server Discover and
option
deprec ated, and will be This is the operation in which we are simply deleting the desired document. Here to
CUse node -- trace arnings ... to show here UseUnitiedTopology: removed
the warmine a s
true
ue
Cre document Updated!!
delete a single record we have used delete One method. The code is as follows-
to
created)
D:
\Node JSEuples \5tusentDeEple.
delete.js
varMongoClient = require(mongodb).MongoClient

var url =
"mongodb://localhost:27017/
Again this updation can be verified by IDelete
opening MongoDB compass MongoClient.comnect(url, function(er, db) {
studentDB.Student_Info
Documents DoCUMENTS O
TOTAL SZE VG SiZE
if (err) throw er;
var dbo = db.db("studentDB");
gregabons Schema Explain Plan Indexes var mydata= { name: "TIT};
Validatior
dbo.collection("Student _Info").deleteOne(mydata,functionlerr.res{
OPTIONS if(er)
ADO DATA EAE B throw erI
1d. ojectid(
Display1ng documents1 console.log("'One document Deleted!!");
nane A
"sessiaa) fel438 2a3. 99 cUe 7" )
db.close():
dty Pune

1d:0jectid("b8s545eetasad71te46 165t6")
nane. BB8
Output

Command Prompt
D:Mode1SExamples\StudentDBEXample>node delete.js be
renoved
1d: Current Server Discovery and Honitoring engine is deprecated, and will
nae Oojectid("bessdsaBatad i1 te46165f Cnode:11852) [NONGODB DRIVER] Warning:
true to
usedmifiedopology:
7)
To use the new Server Discover and Mon itoring engine, pass option {
city: "Chernai 1n a future version.
the MongoClient constructor.
node--trace-warnings ... to sho Mhere the warning was created)
Use
One documernt DeletedI

1d: 0ojectid(oessds00ea8ad7 1b846i65f) :ModeJSExamples \Student D8 EXample»


nane:TT This is updated
city: aypur
document
the contents of the
The above deletion operation can be verified by displaying
d:0ojectla("6e5sds008a8ad7 1be4616sf9
nane:EEE
city: Abmedabed collection

An up thrust for knowledge


TECHNICAL PUBLICATIONS
TECHNICAL PUBLICATIONS-An up
thrust for knowledge
Advanced Wed Programmin9 6-3
Database Programnming witn nNode JS and Node JS and Advanced Wob Programming 6-33 Database Programming with Node JSand MongoDB
Mongsba
ormans Prm peogram Explanation: In above code to sort in ascending order we use sort. The key
mode display js
wode Exaples \Stodenti Aanple . Aonitoring 1s
eng Ine deprecated,
utue
versin.

tor
fo use
Current Server
the n Server D1scover
Discovery and
and Ron1tor ing eng ine, pess option(useUnifiedtopoloe
and wi l

opology: *
true
to
ad
fie based
on which the document is to be sorted is city. We have passed 1 along with it
u e n t coms trar order. If
toho where the warning was created)
fot displaying the ity names in ascending we pass -1 then the ities are
d es S6aA7telea .
Note that the record
mbat )
d: bs asaddbi6,
id:SGN»sad/1ba061659, nane
nam.
t , city: hmedabed
name "DDD" is with
=

deleted Aisplayed in descending order. Simply change the above code as


varmydata={city 1}:

Node ISExanwles\Student0BEXenple b Then the output will be


Command Prompt

Sorting Data
le>node sort. js
D:Vlode3SExamples StudentD8EXamp
Data can be arranged in sorted order in the collection. For
displaying the c
de:9092) (PONODB ORTVER] Marning: Current server Discovery and Ponitoring engire is deprecated, and will be resoved
future version. To use the new Server 0iscover and
Monitoring engine, pass option ( uselnifiedTopology: true ) to t
ordered data we use the method sort.
Following code illustrates how to he Nongoclient
construc
tor.
in ascending order of the filed named city.
display the da a (Use node -trace-arnings
Sorted the Documents in ascendinz ocde
to
shohere the warning was created)

68554442fe14882aJc99cBe7, nae: AAA, city: Pune .

id: 685545e00a8ad71be46165f6, B88, city: mba ,


sort.js i d : 6e55d5e0da8ad 71 be46165+7, CCC, city: "Chennai' },
var MongoClient i d : 60554se0daßad 71b46165F9, EEE,city: ahmedabad
=

require(mongodb). MongoClient;
var url'mongodb:/localhost:27017/ : Node)SExanples \StudentD8EXaple
/sort in ascending order

MongoClient.comnect(url, function(erz, db) {


if (er) throw e r
dbo db.db('studentDE"):
ver =
Review Questions
varmydata={city: 1}: 1. Explain insertion and deletion database operation using Node/s.
dbo.collection('
ifer)
Student_Info").find().sort(mydata). toArray(function(er,res){ 2. Write a program to display the sorted data in the database using Nodejs
throw e
console log(Sorted the Documents in ascending order of city."):
console.logtres);
db.close(

Output
Command Prompt
X
p: \Mode)SExamples \StudentDBEXample>node sort.js
node:14612)
in [ONGOD8 DRIVER the
Marning:Server
Current Server
Discovery and Monitoring engine is deprecated, and will be removed
future version. To
e
use ne Discover and
the Mongolient constructor Monitor ing engine, pass option useUnifiedTopo logy: true to
(Use node
-trace-warnings -.
Sorted the Documents in
to show here the
warning was created)
ascending order of city...
í id:
(id:
605s4s80008ed71be46165+9, nase: 'EEE, city: "Ahne dabad ,
685sdse00aBad71b846165f7, nane: CCC, city:
id: 685SdseveaBad71b046165f6, nase:
BBB
Chenrnal
City: Mumbal
d: 6855d442fel4882a3c99c8e7, nane:
"AAA, city: "Pune
P:Viode JSExaples \StudentDBEXanole»

thust for knowtedge


TECHNICAL PUBLICATIONS-An up
TECHNICAL PUBLICATIONS An up thrust
for knowledge
Auvance IVe Prgammin9 6 34 Database
Node JS
Progranmming wilhh Node JS and
and
Notes MonyotDB
SOLVED MODEL QUESTION PAPER
(As per New Syllabus)
Advanced Web Programmingg
Semester-VI (IT) Professional Elective III

Time:2Hours] ITotal Marks : 70

Instructions: 1) Attempt all questions.


2) Make suitable assumptions wherever necessary.
3) Figures to the right indicate full marks.

a1 a) what are the benefits of CSS? (Refer section 1.1.1) [03


b) Explain the use of font-families in CSS with the help of suitable example.
(Refer section 1.7.1) (04]
c)Write a JavaScript for passuoord verification. (Refer example 1.16.1) [O7
a.2 a) Enlist the featiures of Angular JS (Refer section 2.2) 031

b) Explain MVC with Angular JS Refer section 2.5) [04


c) Explain the controller directive in Angular jS with suitable example.
(Refer section 2.8) [O7
OR
in Angular JS with suitable example
c) Explain the working of Scope object
(Refer section 2.9) [O71
in Angular JS.(Refer section 3.1)
Q.3 a) List and explain the use of three ng-directives
[03]
in detail (Refer section 3.6)
b) Explain the concept of Single Page Application(SPA)
041
three radio buttons each
C) Write anAngular IS script to create a form having color name when
the name of particular color. Display
the appropriate
indicating
section 3.4)
particular radio button is pressed. (Refer
OR
section 3.6) [o3]
Q.3 a) features of SPA (Refer
List any three
in Angular Js with
suitable programming example
b) Explain the use of routing [04]
(Refer section 3.3)
its types with
suitable Angular JS code
c)What is Data binding? Explain 07
(Refer section 3.5)
(M-1)
TECHNICAL PUBLICATIONS An up thrust
for knowledge
M-2 Solved Model Question
Advanced Web Programming Paper
the various uses of Node.js? (Refer section 4.1)
Q.4 a) What are
03)
What is npm? Explain the use of package manage in Node.js with suitable
suitable eexample
b)
(Refer section 4.2)
04
c)Explain the callbacks in node js with suitable example. (Refer section 4.5)
O7
OR

Enlist the features of Node.js.(Refer section 4.3)


Q.4 a) 03)
b) What is the use of npm init?Give example. (Refer section 4.2)
04
c) Explain any four methods of console object in node.js with suitable examples
(Refer section 4.4)
Q.5 a) Explain concept of event emitter. (Refer section 5.1.1)
the 031
b) What is REST API? Explain various parts of client request. (Refer section 5.9)
041
c) What is event loop? Explain its working with suitable block diagram
(Refer section 5.1.2) O7
OR
Q.5 a) Enlist the features of MongoDB (Refer section 6.1) [03

b) Explain the three commonly used set timer functions in node js


(Refer section 5.2) 041
the creation of student database using MongoDB and Node.js. Also wrie
c)
c) Explain
the Node.js script to display the contents of student database. (Refer section 6.6)

TECHNICAL PUBLICATIONS - An up thrust for knowledge

You might also like