Professional Documents
Culture Documents
AWP Book
AWP Book
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
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
(v)
1.7.5 Font Weights. . 28
1.7.6 Font Shorthands.. .l 29
1.7.7Text Decoration. 30
.133
1.8 Lists.
1.9 Responsive Design... T-39
1.10.6 Form...
Part II:JavaScript
. . 1 64
1.11 Java Script Synta
.... 1 - 67
*******
.1-77
1.13.1 Definition of DOM. * * *
***"
.1-77
1.13.2 DOM Tree..
1.13.3 Using DOM Methods.. . . 1 78
*************************.
(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 - 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-9
2.8 Controller . .
. 2 -
15
2.9 Scope..
2.10 Services.. . . 2 16
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
. .
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 - 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 - 22
6.5 Connect Node IS with MongoDB...
(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
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
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.
Review Question
1. What is CSS? Enlist the benefitsof CSS.
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 -
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
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
display
float
overflow
position
visibility
Z-index
Lists list-style
list-style-image
list-style-type
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-
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
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.
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.
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.
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
Aont-family:Arial;
color:red;
Property left:20px
Value
<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
h3
Computer | Protected Mode: 0ff a 100
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;
</style>
</head>
<hody>
<h1>India is My Country</h1>
<h2> All the Indians my brothers and sisters </h33>
are
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
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.
<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
I love my country
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>
</tr>
/td><td>5</td>
<tr class="three"><td>POR<
</tr>
</body>
s/html>
<head
stitle>Generic Class Selector Form</title>
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>
Output
Generc Cless Selector Form Windows Intermet Explorer
Tongue Twister
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>
#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
-Aristote
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>
<hr/>
<ul type="'disc">
<li>A friend in need is a friend indeed</li>
<li>Cleanliness is next to Godliness </lí>
<br/><br/>
<em>
-From My Collection.
</em>
</body>
</html>
Output
Universal Selector - Windows Internet Explorer
Famous Proverbs
From My Collection.
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.
<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
Google
Facebook
<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>
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
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
/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.
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 -
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
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.
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>
e uggested stes
Get More Add-ons
favortes
Page
éColor Properbes
Cursive
Zapf-chancery
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
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
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.
<IDOCTYPE html>
<html
head>
Output
<title>Font-Size Demo</title>
D HTM Lemples otsa m
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
case.
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
oblique
The illustration is as given below.
HTML Document[FontSt.html]
<IDOCTYPE html>
<html
<head>
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
Output
100%
4Computer | Protected Mode Off
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:
<body
p class= "myfont">I Love my Country!!</p>>
/body>
</html>
Output
I Love my Country!!!
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;}
</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
<IDOCTYPE html>
<html>
<head>
stitle>Text Alignment Demo</title>
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>
Output
100%
Computer | Protected Mode Off
1.8 Listss
unordered list and ordered lists. The unordered lists
are
There two types of lists
-
are
Square
.None
<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>
</body>
</html>
Output
Carot
Cucumber
Spinach
</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
<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
Indian Idols
8 Naranyan Murthy
8 Lata Mangeshkar
Abhinav Bindra
Sachin Tenchlkar
&ARRehman
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>
</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>
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
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%
Tablet
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.
tag
Following line must be included in your HTML document to set the viewport
name =
"viewport" content =
"width"=device-width, intial-scale = 1.0">
<meta
Fig. 1.9.2
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.
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
HTML Document
<IDOCTYPE html>
html>
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
.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
-
<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
Or
<head>
Script declarations <title>Bootstrap Example </title>
ead> <meta charset="utf-8">
<link rel="stylesheet'
href-"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css>>
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
</div>
<div class= "row"
Output <div class="col-*-*"> </div>
e -
OX <div class="col-*-*"></divV>
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
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">
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!!!
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"
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
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
</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
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
AAA Pune
Bootstrap Example
BB8 Mumbai
file//d://mgDemo.html C Search
cCc Chennai
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
=
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.
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>
</html>
2. Horizontal Form
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
nput type
initial-scale=1>
=
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
-
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
=
=
</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
=
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>
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
<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
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 -
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 >
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.
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.
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>
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
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>
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
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
PUBLICATIONS
-
An up thrust for knowledge
TECHNICAL TECHNICAL
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()
<body>
<strong
SCript type="text/javascript'>
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
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
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
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.
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
<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
</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
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
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
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
name= "mybutton"/>
Kinput type="button"
< s c r i p t >
pnode.appendChild(node);
t.getElementById "'div1";
**
gets changed.
element
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
<Jdiv>
Kseript>
var pnode= document.cresteElement('p').
<Bripts
pnode.appendChild(node), arentnoderemove
Child(node);
document getElementByld('div1').
varelement =
ecript
h t m l >
x First Sentence
fle d test html +
Third Sentence
file:///d:/test.html C aSearch
Furst Sentence
Second Sentence
< / 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
-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
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
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
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
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.
e.clientX
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)
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>
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
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...
Wekome
browser's window.
Following script along Mode Off 100%
Computer | Protected
attribute
JavaScripttonloadDemo.htm/]
catch(err) {
Block of code to handle errors
message =
document.getElementByld('myD"):
message.innerHTML = ";
num = document.getElementByid('demo").value;
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.
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'>
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
In JavaScript task.
the validation of these widgets is an important </labels
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
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
OutputRun2)
3
Internet
Explorer
Cust
Windows
X Pioggie¬N
Attbute-
of onklick Tag
Demo
ele///aasciptTetDemol.htm
Demo of onlclick
Tag
Attibute
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
L
Message from webpage
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>
if ((emailD.value==null)||(emaillD.value= ="))
< / h e a d >
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
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 " )
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> </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
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
<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>
1 The web applications architectures are based on Hl request response protocol Fig. 1.17.21
Traditional web application
col. architectur
cture
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
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
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
else
pwd:password(optional)
send) sends the request to the server. req=new ActiveXObject("Microsoft.req):
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
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
>>
function MyFun()
STUDENT INFORMATION
Clidk
var xhttp =
new
XMLHttpRequest()
xhttp onreadyststechange = function()
Load_XML_File(this);
button will get
On clicking the we
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+)
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
AJAX
Explain
Syllabus
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-
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.
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
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,
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.
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>
</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
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 -
<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
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
leiax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.minjs'> </script>
<html>
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
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
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=
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>
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
Contents
31 Directives
32 Modules
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.
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»
4. Delete file
input of another stream. output of one
1. Read file 2. Create file 3. Update file
JS in
1. Read Operation
Det Operation
File
operation can be performed synchronously or a s y n c .
The read file
the file
Normally while reading
the last parameter to the readFile function. The form of this callback fundi functio where
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
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";
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 -
4. Delete File
Operation
To delete the file, we use
unlink) method.
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
-
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
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
-
ata
client.write(mydata); those a r e
-
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
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
build to node.js programs One for server and other for client.
e have two
knowledge
TECHNICAL PUBLICATIONS An up thrust for
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;
=
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();
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.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
Fig. 5.6.1
IP address of the
Ste web page by providing the
W e b client requests for the desired
website
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
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
out
Steps out of the function
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.
D:Node SExamples> We can inspect the values of the variable using watch and watchers command.
2str
3 var "This
strlen = line
is replacing
str.lengthh;
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
a I c e T e b
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);
localhost:8082 Output
C
Welcome User!! X
localhost:8082/about
C loclhost:8082/about
Routing
Routing is a manner by which an application responds to a client's request based on
app.js
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
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
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.
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
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 =
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
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
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 .
.
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 })
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
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 -
app.listen(8082);
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
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
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) = >
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
Cookie Demo
app.js
constexpress require('express)
constcookieParser require(cookie-parser);
const app express();
app.use(cookieParser();
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)
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
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.
sum.js = require('events');
function compute(a,b) { events
var
new events.EventEmitter();
retum atb; uar eventEmitter
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
console.log(result.compute(10,20); /user #3
Output var user3 = function listner30 1
console.log(user3 is listening.);
Command Prompt
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);
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.
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)
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
=
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
TECHNICAL PURUCATIOnun
5- 66
d Web Programming Node J.
Notes
Contents
6.1 Basics of MongoDB
(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.
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
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
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
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
Setings
Environment Variables.
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
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
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.
variable window.
clicking ok button and
just come out of the 1.26.0 (Stabie)
environment
Restart your command Pia:rorm
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
goDB f o l l o w i n gG U I
Welcome to the
N o w C o n n e c t o n
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
a u hae r Auias o u s g o e Aa
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
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
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
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)
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.
() 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);
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-
Syntax
db.collection_name.remove({})
For example
This can be verified as
19
Syntax
ascending order we should pass
value 1
:
"DO0", "age" 21 For displaying the documents in
For example
documents
Suppose the collection contains following
TECHNICAL PUBLICATIONS-An up
thrust for knowledge
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
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
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,
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
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
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
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');
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
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
=
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)
require(mongodb). MongoClient;
var url'mongodb:/localhost:27017/ : Node)SExanples \StudentD8EXaple
/sort in ascending order
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»