0% found this document useful (0 votes)
7 views366 pages

Jquery Notes

jQuery is a lightweight JavaScript library created by Jhon Resig in 2006, designed to simplify JavaScript usage on websites by reducing the amount of code needed for common tasks. It offers features like DOM manipulation, event handling, and AJAX support, and is widely used by major companies due to its cross-browser compatibility and extensive community support. jQuery's syntax allows for easy selection and manipulation of HTML elements, and it provides various methods for effects, animations, and event handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views366 pages

Jquery Notes

jQuery is a lightweight JavaScript library created by Jhon Resig in 2006, designed to simplify JavaScript usage on websites by reducing the amount of code needed for common tasks. It offers features like DOM manipulation, event handling, and AJAX support, and is widely used by major companies due to its cross-browser compatibility and extensive community support. jQuery's syntax allows for easy selection and manipulation of HTML elements, and it provides various methods for effects, animations, and event handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JQuery

JQuery
 jQuery is a lightweight, "write less, do more", JavaScript library by Jhon
Resig in 2006.
 The purpose of jQuery is to make it much easier to use JavaScript on your
website.
 jQuery takes a lot of common tasks that require many lines of JavaScript
code to accomplish, and wraps them into methods that you can call with a
single line of code.
 jQuery also simplifies a lot of the complicated things from JavaScript, like
AJAX calls and DOM manipulation.
 The jQuery library contains the following features:
 HTML/DOM manipulation
 CSS manipulation
 HTML event methods
 Effects and animations
 AJAX
 Utilities
Vijayan.R / Prof / SCORE / VIT
Why jQuery?
 There are lots of other JavaScript frameworks out there, but jQuery seems
to be the most popular, and also the most extendable.
 Many of the biggest companies on theWeb use jQuery, such as:
 Google
 Microsoft
 IBM
 Netflix
 jQuery will run exactly the same in all major browsers.
 Why?
 Easy to manipulate DOM
 Cross browser platform
 Large community
 1000s of plugin

Vijayan.R / Prof / SCORE / VIT


 Adding jQuery to Your Web Pages
 There are several ways to start using jQuery on your web [Link] can:
 Download the jQuery library from [Link]
 Include jQuery from a CDN, like Google
 Downloading jQuery
 There are two versions of jQuery available for downloading:
 Production version - this is for your live website because it has been minified and
compressed
 Development version - this is for testing and development (uncompressed and
readable code)
<head>
<script src="[Link]"></script>
</head>
 Do you wonder why we do not have type="text/javascript"
inside the <script> tag?
This is not required in HTML5. JavaScript is the default scripting language in
HTML5 and in all modern browsers!

Vijayan.R / Prof / SCORE / VIT


jQuery CDN
 If you don't want to download and host jQuery yourself, you can include it from a CDN
(Content Delivery Network).
 Both Google and Microsoft host jQuery.
 Google CDN:
<head><script src="[Link]
/script></head>
 Microsoft CDN:
<head><script src="[Link]
[Link]"></script></head>
 One big advantage of using the hosted jQuery from Google or Microsoft:
Many users already have downloaded jQuery from Google or Microsoft when visiting another
site. As a result, it will be loaded from cache when they visit your site, which leads to faster
loading time. Also, most CDN's will make sure that once a user requests a file from it, it will be
served from the server closest to them, which also leads to faster loading time.

Vijayan.R / Prof / SCORE / VIT


jQuery Syntax
 The jQuery syntax is tailor-made for selecting HTML elements and
performing some action on the element(s).
 Basic syntax is: $(selector).action()
 A $ sign to define/access jQuery
 A (selector) to "query (or find)" HTML elements
 A jQuery action() to be performed on the element(s)
 Examples:
jQuery uses CSS syntax
 $(this).hide() - hides the current element. to select elements.
 $("p").hide() - hides all <p> elements.
 $(".test").hide() - hides all elements with class="test".
 $("#test").hide() - hides the element with id="test".

Vijayan.R / Prof / SCORE / VIT


The Document Ready Event
 It is good practice to wait for the document to be fully loaded and
ready before working with it. This also allows you to have your
JavaScript code before the body of your document, in the head
section.
 Here are some examples of actions that can fail if methods are run
before the document is fully loaded:
 Trying to hide an element that is not created yet
 Trying to get the size of an image that is not loaded yet
 Tip: The jQuery team has also created an even shorter method for
the document ready event:
$(document).ready(function() $(function(){
{ // jQuery methods go here...
// jQuery methods go here... })
})Vijayan.R / Prof / SCORE / VIT
jQuery Selectors
jQuery selectors are used to "find" HTML elements based on their name, id,
classes, types, attributes, values of attributes and much more. It's based on the
existing CSS Selectors, and in addition, it has some own custom selectors. All
selectors in jQuery start with the dollar sign and parentheses: $().
The element Selector
The jQuery element selector selects elements based on the element
[Link] can select all <p> elements on a page like this: $("p")
The #id Selector
The jQuery #id selector uses the id attribute of an HTML tag to find
the specific element. An id should be unique within a page, so you should use
the #id selector when you want to find a single, unique element. To find an
element with a specific id, write a hash character, followed by the id of the
HTML element:$("#test")
The .class Selector
The jQuery class selector finds elements with a specific class. To find
elements with a specific class, write a period character, followed by the name of
the class: $(".test")
Vijayan.R / Prof / SCORE / VIT
Example – element selector
<html><head>
<script
src="[Link]
</script><script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script></head><body>
<h2>This is a heading</h2><p>This is a paragraph.</p>
<p>This is another paragraph.</p><button>Click me</button>
</body></html>

Vijayan.R / Prof / SCORE / VIT


Example – id selector
<html><head><script
src="[Link]
js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
</script></head><body>
<h2>This is a heading</h2><p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<button>Click me</button></body></html>
Vijayan.R / Prof / SCORE / VIT
Example – class selector
<html> <head> <script
src="[Link]
js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
</script></head><body>
<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button></body></html>
Vijayan.R / Prof / SCORE / VIT
jQuery Event Methods
 All the different visitor's actions that a web page can respond to are
called events.
 An event represents the precise moment when something happens.
"The keypress event is fired, the moment you press a key".

Vijayan.R / Prof / SCORE / VIT


Event Methods
 click()-The function is executed when the user clicks on the HTML
element.
 dblclick()-The function is executed when the user double-clicks on the
HTML element
 mouseenter()-The function is executed when the mouse pointer enters
the HTML element
 mouseleave()-The function is executed when the mouse pointer leaves the
HTML element
 mousedown()-The function is executed, when the left, middle or right
mouse button is pressed down, while the mouse is over the HTML element
 mouseup()-The function is executed, when the left, middle or right mouse
button is released, while the mouse is over the HTML element
 hover()-takes two functions and is a combination of the mouseenter() and
mouseleave() methods
 focus()-The function is executed when the form field gets focus
 blur()-The function is executed when the form field loses focus
 on()-method attaches one or more event handlers for the selected elements
Vijayan.R / Prof / SCORE / VIT
<html><head><script
src="[Link]
js"></script>
<script>
$(document).ready(function(){
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
}); </script></head><body>
<p id="p1">Enter this paragraph.</p></body></html>

Vijayan.R / Prof / SCORE / VIT


<html><head><script
src="[Link]
><script>
$(document).ready(function(){
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css({"background-color”:”yellow”,”font-size”:”200%“});
} });});
</script></head><body><p>Click or move the mouse pointer over this
paragraph.</p></body></html>

Vijayan.R / Prof / SCORE / VIT


jQuery Effects - Hide and Show
$("#hide").click(function(){
$("p").hide();
});

$("#show").click(function(){
$("p").show();
});

$("button").click(function(){
$("p").hide(1000);
});
The optional speed parameter specifies the speed of the hiding/showing,
and can take the following values: "slow", "fast", or milliseconds.

Vijayan.R / Prof / SCORE / VIT


jQuery Effects - Toggle
<html> <head> <script
src="[Link]
s"></script> <script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
}); });
</script> </head> <body>
<button>Toggle between hiding and showing the paragraphs</button>
<p>This is a paragraph with little content.</p> <p>This is another
small paragraph.</p>
</body> </html>
Vijayan.R / Prof / SCORE / VIT
jQuery Effects - Fading
 fadeIn() method is used to fade in a hidden element
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000); });
 fadeOut() method is used to fade out a visible element
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000); });
 fadeToggle() method toggles between the fadeIn() and fadeOut() methods
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000); });
 fadeTo() method allows fading to a given opacity (value between 0 and 1)
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow",
Vijayan.R / Prof / SCORE / VIT
0.7);});
jQuery Effects - Sliding
<html><head><script
src="[Link]
><script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});});</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc; slideDown()
border: solid 1px #c3c3c3;} slideUp()
#panel { slideToggle()
padding: 50px; display: none;}
</style></head><body> <div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div></body></html>
Vijayan.R / Prof / SCORE / VIT
jQuery Effects - Animation
 The jQuery animate() method is used to create custom animations.
 By default, all HTML elements have a static position, and cannot be
moved. To manipulate the position, remember to first set the CSS
position property of the element to relative, fixed, or absolute!
$("button").click(function(){
$("div").animate({top: '250px'}); });
 multiple properties can be animated at the same time
$("button").click(function(){
$("div").animate({
opacity: '0.5',
height: '150px',
width: '150px‘
});}); $(selector).animate({params},speed,callback);
Vijayan.R / Prof / SCORE / VIT
 It is also possible to define relative values (the value is then relative to
the element's current value). This is done by putting += or -= in front
of the value.
$("button").click(function(){
$("div").animate({
left: '250px',
height: '+=150px',
width: '+=150px'
});});
 You can even specify a property's animation value as "show", "hide",
or "toggle“
$("button").click(function(){
$("div").animate({
height: 'toggle'
});});
Vijayan.R / Prof / SCORE / VIT
 Uses Queue Functionality
 This means that if you write multiple animate() calls after each other,
jQuery creates an "internal" queue with these method calls. Then it
runs the animate calls ONE by ONE.
$("button").click(function(){
var div = $("div");
[Link]({height: '300px', opacity: '0.4'}, "slow");
[Link]({width: '300px', opacity: '0.8'}, "slow");
[Link]({height: '100px', opacity: '0.4'}, "slow");
[Link]({width: '100px', opacity: '0.8'}, "slow"); });
 The example below first moves the <div> element to the right, and
then increases the font size of the text.
$("button").click(function(){
var div = $("div");
[Link]({left: '100px'}, "slow");
[Link]({fontSize: '3em'}, "slow"); });
Vijayan.R / Prof / SCORE / VIT
Vijayan.R / Prof / SCORE / VIT
jQuery stop() Method $(selector).stop(stopAll,goToEnd);
 The jQuery stop() method is used to stop an animation or effect
before it is finished.
 The stop() method works for all jQuery effect functions, including
sliding, fading and custom animations.
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});});

Vijayan.R / Prof / SCORE / VIT


jQuery Callback Functions
 JavaScript statements are executed line by line. However, with effects,
the next line of code can be run even though the effect is not finished.
This can create errors. To prevent this, you can create a callback
function. A callback function is executed after the current effect is
100% finished.
 $("button").click(function(){
$("p").hide("slow", function(){ callback
alert("The paragraph is now hidden");
});});
 $("button").click(function(){
$("p").hide(1000); without callback
alert("The paragraph is now hidden");
});
Vijayan.R / Prof / SCORE / VIT $(selector).hide(speed,callback);
jQuery Method Chaining
 Chaining allows us to run multiple jQuery methods (on the same
element) within a single statement.
 The following example chains together the css(), slideUp(), and
slideDown() methods. The "p1" element first changes to red, then it
slides up, and then it slides down:
<html><head><script
src="[Link]
s"></script><script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
});});</script></head><body>
<p id="p1">jQuery is fun!!</p><br><br><br>
<button>Click me</button></body></html>
Vijayan.R / Prof / SCORE / VIT
jQuery DOM Manipulation
 DOM = Document Object Model
The DOM defines a standard for accessing HTML and XML
documents:"The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically
access and update the content, structure, and style of a document."
 Three simple, but useful, jQuery methods for DOM manipulation
are:
 text() - Sets or returns the text content of selected elements
 html() - Sets or returns the content of selected elements
(including HTML markup)
 val() - Sets or returns the value of form fields
 attr() – Sets or returns the attribute of form fields
Vijayan.R / Prof / SCORE / VIT
<html> <head> <script
src="[Link]
/3.3.1/[Link]"></script> <script>
$(document).ready(function(){
$("#btn1").click(function(){
alert("Text: " + $("#test").text()); });
$("#btn2").click(function(){
alert("HTML: " + $("#test").html()); });
$("#btn3").click(function(){
alert("Value: " + $("#t1").val()); });
});</script></head><body>
<p id="test">This is some <b>bold</b> text in a paragraph.</p>
<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>
<p>Name: <input type="text" id="t1" value="Mickey Mouse"></p>
<buttonVijayan.R
id="btn3">Show
/ Prof / SCORE / VIT
Value</button></body></html>
Vijayan.R / Prof / SCORE / VIT
 The jQuery attr() method is used to get attribute values.
 The following example demonstrates how to get the value of the href
attribute in a link:
<html><head><script
src="[Link]
s"></script><script>
$(document).ready(function(){
$("button").click(function(){
alert($("#w3s").attr("href"));
});});
</script></head><body>
<a href="[Link] id="w3s">
[Link]</a>
<button>Show hrefValue</button></body>
Vijayan.R / Prof / SCORE / VIT
Add new HTML content
jQuery methods that are used to add new content:
 append() - Inserts content at the end of the selected elements
 prepend() - Inserts content at the beginning of the selected
elements
 after() - Inserts content after the selected elements
 before() - Inserts content before the selected elements

Vijayan.R / Prof / SCORE / VIT


 $("p").append("Some appended text.");

 $("p").prepend("Some prepended text.");

 $("img").after("Some text after");

 $("img").before("Some text before");

Vijayan.R / Prof / SCORE / VIT


Adding several elements
function appendText() {
// Create element with HTML
var txt1 = "<p>Text.</p>";
// Create with jQuery
var txt2 = $("<p></p>").text("Text.");
// Create with DOM
var txt3 = [Link]("p");
[Link] = "Text.";
// Append the new elements
$("body").append(txt1, txt2, txt3);
}

Vijayan.R / Prof / SCORE / VIT


Adding several elements
function afterText() {
var txt1 = "<b>I </b>"; // Create element with HTML
// Create with jQuery
var txt2 = $("<i></i>").text("love ");
// Create with DOM
var txt3 = [Link]("b");
[Link] = "jQuery!";
// Insert new elements after <img>
$("img").after(txt1, txt2, txt3);
}

Vijayan.R / Prof / SCORE / VIT


Remove Elements/Content

To remove elements and content, there are mainly two jQuery


methods:
 remove() - Removes the selected element (and its child
elements)
$("#div1").remove();

 empty() - Removes the child elements from the selected


element
$("#div1").empty();

Vijayan.R / Prof / SCORE / VIT


Display JSON data in Table Format
<html><head><script
src="[Link]
<style> #mytable,td{ border:1px solid blue;}</style> <script>
$(document).ready(function () {
var obj=[ { item : "001", name : "apple", category : "fruit", color : "red" },
{ item : "002", name : "melon", category : "fruit", color : "green" },
{ item : "003", name : "banana", category : "fruit", color : "yellow" } ]
var tbl=$("<table/>").attr("id","mytable");  table creation at dynamically
$("#div1").append(tbl);
for(var i=0;i<[Link];i++) { var tr="<tr>";
var td1="<td>"+obj[i]["item"]+"</td>";
var td2="<td>"+obj[i]["name"]+"</td>";
var td3="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3); }}) </script> </head><body>
<div id="div1"> </div></body></html>
Vijayan.R / Prof / SCORE / VIT
Vijayan.R / Prof / SCORE / VIT
EXERCISE
1. Use a jQuery method to hide the <p> element when it is clicked
on.
2. Use a jQuery method to hide the <p> element when it is clicked
on. The speed should be "slow".
3. There is a hidden <p> element in the document. Use a jQuery
method to show the <p> element with a click of a button.
4. Toggle between hiding and showing the <p> element when you
click on the "Toggle" button.
5. Use a jQuery method to slide up the <div> [Link] duration
of the effect should be "slow".

Vijayan.R / Prof / SCORE / VIT


Vijayan.R / Prof / SCORE / VIT
Exercise
 Develop a quiz application using Jquery methods. The
application should be developed in such a way that after the
user attempted a quiz question, the answer along with the
explanation should be displayed when the user clicks the
answer button. Use sliding methods to develop the same.
 Develop a animated application using Jquery, the application
should be developed in such a way that the user pressed the
button, the object along with text should be move from left
to right, right to left , top to bottom and bottom to top with
particular set of intervals after completing the task it should
be hide.
Vijayan.R / Prof / SCORE / VIT
Exercise
 Use jQuery selectors to identify elements with these
properties in a hypothetical page: ◦ All p tags that have no
children, but only if they don't have a class of ignore ◦ Any
element with the text "REPLACE_ME" in it. ◦ All div tags
with a child that has a class of special ◦ All heading elements
(h1, h2, h3, h4, h5, h6) ◦ Every other visible li. Use the
DOM API to target the #square and periodically change it's
position in a random direction. Use jQuery selectors instead
of the DOM API.

Vijayan.R / Prof / SCORE / VIT


Program1 :

<!doctype html>
<html>
<head>
<script src="[Link]"></script>
</head>
<style>
#d1{
background-color:yellow;
}
div{
background-color:pink;
width:200px;
height:200px;

}
</style>
<body>

<h1> jQuery </h1>


<div id="d1"> hello </div>
<p id="p1"> This is a paragraph </p>
<p id="p2"> This is a paragraph </p>
<img src="[Link]" width="200px" height="200px">
<script>
$(function(){
$("#d1").hide(1000).show(2000);
$("#p1").css("backgroundColor","red");
$("#p1").css("text-align","right");
$("#p2").css({'backgroundColor':'blue', 'text-align':'center'});
$("p").html("<h2> HEllo World!</h2>");
$("img").attr("src","[Link]");
});

// $("#p2").css("backgroundColor", "red");
// $("#p2").css({background-color:'red'});
// $("p: first ").attr("align","right");
// $("#p1").html("<b> Hello </b>");
// $("#div1").before("<p> Hello </p>")

</script>
</body>
</html>
Program2 :

<!doctype html>
<html>
<head>
<script src="[Link]"></script>
</head>
<style>
#p1{
display:none;
}
</style>
<body>

<h1> jQuery Effects</h1>


<img src="[Link]" id="img1" width="200" height="200">
<img src="[Link]" id="img2" width="200" height="200">
<button id="b1"> B1 </button>
<button id="b2"> B2 </button>
<button id="b3"> B3 </button>

<p id="p1"> This is a Rose image</p>


<script>
$(document).ready(function(){
$("#b1").click(function(){
$("#img1").fadeToggle(2000);
});
$("#b2").click(function(){
$("#img2").slideToggle(2000);
});
$("#b3").click(function(){
$("#img3").slideToggle(2000);
});
$("#img1").click(function(){
$("#b1").hide();
});

});

$(document).ready(function(){
$("#img1").click(function(){
$("#p1").slideToggle();
});

});
</script>

</body>
</html>

Program 3:

<html><head>
<style>
div{
background-color: yellow;
width:100px;
height:100px;
margin: 20px;
}
#d2{
background-color: blue;
}
</style>
<script src="[Link]"></script>
<script>
$(document).ready(function(){
$("#b1").click(function(){
let x = $("#p1").html();
if( x == "Full Stack")
$("#d1").html(x);
else if(x == "Deep Learning")
$("#d2").html(x);
else if(x == "Cyber Security")
$("#d3").html(x);
$("#d1").css("background-color","red");

});
$("#b2").click(function(){
let bg=$("#d2").css("background-color");
$("#d3").css("background-color",bg);
alert(bg);
});
$("#b3").click(function(){
$("#d3").css("background-color","red");
});

});
</script>
</head><body>
<button id="b1"> Button1 </button>
<button id="b2"> Button2 </button>
<button id="b3"> Button3 </button>
<p id="p1">Deep Learning</p>
<div id="d1"> </div>
<div id="d2"> </div>
<div id="d3"> </div>
</body>
</html>

Program 4:
<!doctype html>
<html>
<head>
<script src="[Link]"></script>
</head>
<style>
</style>
<body>
<h1> Form Validation </h1>
Name : <input type="text" id="t1">
<span id="p1"></span><br>
<button> Validate </button>

<script>
$(document).ready(function(){
$("button").click( () => {
let x=$("#t1").val();
if(![Link](/^[A-Za-z]{6,15}$/))
{
$("#p1").html("Name should contain only alphabets");
$("#p1").css("color","red");
}

});
});
</script>
</body>
</html>

Program 5:

<html><head>
<script src="[Link]"></script>
<script>
$(document).ready(function(){
$("#b1").click(function(){
$("#p1").toggle();
});
$("#b2").click(function(){
$("#p2").toggle();
});
$("#b3").click(function(){
$("#p3").toggle();
});

});
</script>
</head><body>
<button id="b1"> Btn1 </button>
<button id="b2"> Btn2 </button>
<button id="b3"> Btn3 </button>

<p id="p1"> First line</p>


<p id="p2"> Second line</p>
<p id="p3"> Third line</p>
</body>
</html>

Program 6:
<!doctype html>
<html>
<head>
<script src="[Link]"></script>
</head>
<body>
<h1> Friends </h1>
Name : <input type="text" id="t1">
<button> Add </button>
<div id="d1"></div>
<script>
$(document).ready(function(){
$("button").click( () => {
let x=$("#t1").val();
let friends=$("#d1").html();
alert(friends);
if([Link] < 7)
fri ="<p style='color:green'>"+x+"</p>";
else
fri ="<p style='color:blue'>"+x+"</p>";
$("#d1").html(friends+fri);
$("#t1").val("");

});
});
</script>
</body>
</html>

Program 7:

<!doctype html>
<html>
<head>
<script src="[Link]"></script>

</head>
<style>
#d1{
border: 2px solid blue;
margin:5px;
width:200px;
height:200px;
}
#d2{
border: 2px solid red;
margin:5px;
width:300px;
height:300px;
}
.d3{
border: 2px solid yellow;
margin:5px;
width:400px;
height:400px;
}

</style>
<body>
<div>
<div id="d2">
<div id="d1">
<ul id="u1">
<li> Full Stack </li>
<li> Deep Learning </li>
<li> Image Processing </li>
</ul>
<ul id="u2">
<li> Full Stack </li>
<li> Applied Machine Learning </li>
<li> NoSQL Databases </li>
</ul>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#u1").remove();
$("#u1").append("<li> Cyber Security</li>");

});
</script>
</body>
</html>
AJAX- Asynchronous JavaScript and
XML
Module-4
Introduction to AJAX
 AJAX = Asynchronous JavaScript and XML.
 Update a web page without reloading the page
 Request data from a server - after the page has loaded
 Receive data from a server - after the page has loaded
 Send data to a server - in the background
 AJAX is a technique for creating fast and dynamic web pages.
 AJAX allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it is possible to
update parts of a web page, without reloading the whole page.
 Classic web pages, (which do not use AJAX) must reload the entire page if the
content should change.
 Examples of applications using AJAX: Google Maps, Google Suggest, Gmail,
Youtube, Flickr, and Facebook tabs.
 AJAX is a web browser technology independent of web server software.
 AJAX meant to increase the web page's interactivity, speed, and
usability.
2 Vijayan.R / Prof / SCORE 2/9/2026
Comparison

3 Vijayan.R / Prof / SCORE 2/9/2026


How AJAX works?

4 Vijayan.R / Prof / SCORE 2/9/2026


5 Vijayan.R / Prof / SCORE 2/9/2026
AJAX is based on Internet Standards

1. XMLHttpRequest object (to exchange data asynchronously with a


server)
2. JavaScript/DOM (to display/interact with the information)
3. CSS (to style the data)
4. XML or JSON (often used as the format for transferring data)

Note: AJAX applications are browser- and platform-independent!

AJAX can be used for interactive communication with a database and an


XML file .
6 Vijayan.R / Prof / SCORE 2/9/2026
AJAX - The XMLHttpRequest Object
 JavaScript object that performs asynchronous interaction
with the server.
 All modern browsers support the XMLHttpRequest object.
 Object can be used to exchange data with a server behind the
scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.

7 Vijayan.R / Prof / SCORE 2/9/2026


8 Vijayan.R / Prof / SCORE 2/9/2026
9 Vijayan.R / Prof / SCORE 2/9/2026
Sample Code
<!DOCTYPE html>
<html> <body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change
Content</button>
</body></html> <head>
<script>
function loadXMLDoc()
{
.... AJAX script goes here ...
}
</script>
10 Vijayan.R / Prof / SCORE </head> 2/9/2026
<html> <head> <script>
function loadXMLDoc(){
var xmlhttp;
if ([Link])
xmlhttp=new XMLHttpRequest();
[Link]=function()
{
if ([Link]==4 && [Link]==200)
[Link]("myDiv").innerHTML=[Link]
Text; }
[Link]("GET","AJAX_TextFile.txt",true);
[Link](); } </script> </head> <body>
11 Vijayan.R / Prof / SCORE 2/9/2026
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change
Content</button>
</body> </html>

C:/wamp/www/[Link]
AJAX is not a new programming language.
AJAX is a technique for creating fast and dynamic web pages.

12 Vijayan.R / Prof / SCORE 2/9/2026


The XMLHttpRequest Object
The XMLHttpRequest object is used to exchange data with a server
behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.
var xmlhttp;
if ([Link])
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("[Link]");
}

13 Vijayan.R / Prof / SCORE 2/9/2026


Send a Request To a Server
[Link]("GET","ajax_info.txt",true); [Link]();
[Link]("GET","[Link]?t=" + [Link](),true);
[Link]("GET","[Link]?fname=Henry&lname=Ford",true);
The file can be any kind of file, like .txt and .xml, or server scripting files like
.asp and .php (which can perform actions on the server before sending the
response back).
Method Description
Specifies the type of request, the URL, and if the
request should be handled asynchronously or not.
open(method,url,async) method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
Sends the request off to the server.
send(string)
string: Only used for POST requests
14 Vijayan.R / Prof / SCORE 2/9/2026
Asynchronous - True or False?
 Sending asynchronous requests is a huge improvement for web
developers. Many of the tasks performed on the server are very time
consuming. Before AJAX, this operation could cause the application
to hang or stop.
 With AJAX, the JavaScript does not have to wait for the server
response, but can instead:
 execute other scripts while waiting for server response
 deal with the response when the response ready

15 Vijayan.R / Prof / SCORE 2/9/2026


[Link]=function()
{
if ([Link]==4 && [Link]==200)
{
[Link]("myDiv").innerHTML=[Link]
ponseText;
}
}
[Link]("GET","ajax_info.txt",true);
[Link]();

16 Vijayan.R / Prof / SCORE 2/9/2026


Async=false
 Using async=false is not recommended, but for a few small
requests this can be ok.
 Remember that the JavaScript will NOT continue to execute, until
the server response is ready. If the server is busy or slow, the
application will hang or stop.

 Note: When you use async=false, do NOT write an


onreadystatechange function - just put the code after the send()
statement:
 [Link]("GET","ajax_info.txt",false);
[Link]();
[Link]("myDiv").innerHTML=[Link]
nseText;

17 Vijayan.R / Prof / SCORE 2/9/2026


AJAX - Server Response
Property Description
responseText get the response data as a string

responseXML get the response data as XML data

If the response from the server is not XML, use the responseText
property.

[Link]("myDiv").innerHTML
=[Link];

18 Vijayan.R / Prof / SCORE 2/9/2026


 If the response from the server is XML, and you want to parse it as an
XML object, use the responseXML property:
 Request the file cd_catalog.xml and parse the response:

xmlDoc=[Link];
txt=“ “;
x=[Link]("ARTIST");
for (i=0;i<[Link];i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
[Link]("myDiv").innerHTML=txt;

19 Vijayan.R / Prof / SCORE 2/9/2026


The onreadystatechange event
 When a request to a server is sent, we want to perform some
actions based on the response.
 The onreadystatechange event is triggered every time the
readyState changes.
 The readyState property holds the status of the XMLHttpRequest.
 Three important properties of the XMLHttpRequest object:
[Link]=function() {
if ([Link]==4 && [Link]==200) {
[Link]("myDiv").innerHTML=
[Link]; } }
Note: The onreadystatechange event is triggered five times (0-4), one
time for each change in readyState.
20 Vijayan.R / Prof / SCORE 2/9/2026
Property Description
Stores a function (or the name of a function) to
onreadystatechange be called automatically each time the readyState
property changes
Holds the status of the XMLHttpRequest.
Changes from 0 to 4:
0: request not initialized
readyState 1: server connection established
2: request received
3: processing request
4: request finished and response is ready
200: "OK"
status
404: Page not found
21 Vijayan.R / Prof / SCORE 2/9/2026
AJAX with JSON
<html><head><script type = "text/javascript">
function loadJSON(){
var data_file = "[Link]
/* var data_file = "[Link]";*/
var http_request = new XMLHttpRequest();
try{ // Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){ // Internet Explorer Browsers
try{ http_request = new ActiveXObject("[Link]");
}catch (e) {
try{
http_request = new ActiveXObject("[Link]");
}catch (e){ // Something went wrong
alert("Your browser broke!"); return false;
}}}
22 Vijayan.R / Prof / SCORE 2/9/2026
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function [Link] to parse JSON data
var jsonObj = [Link](http_request.responseText);
// jsonObj variable can be accessed
[Link]("Name").innerHTML =
[Link];
[Link]("Country").innerHTML =
[Link];
}}
http_request.open("GET", data_file, true);
http_request.send(); } </script> </head>
23 Vijayan.R / Prof / SCORE 2/9/2026
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr></table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update
Details </button> </div> </body></html>

24 Vijayan.R / Prof / SCORE 2/9/2026


25 Vijayan.R / Prof / SCORE 2/9/2026
Exercise
 The following example will demonstrate how a web page can
communicate with a web server while a user type characters in an
input field:

Start typing a name in the input field below:


First name: a
Suggestions: Anna , Amanda

Start typing a name in the input field below:


First name: m
Suggestions: no suggestion

26 Vijayan.R / Prof / SCORE 2/9/2026


Exercise

27 Vijayan.R / Prof / SCORE 2/9/2026


jQuery ajax() Method
 The $.ajax() method provides core functionality of Ajax in jQuery. It sends
asynchronous HTTP requests to the server.
 Syntax: $.ajax(url); $.ajax(url,[options]);
 url: A string URL to which you want to submit or retrieve the data
 options: Configuration options for Ajax request. An options parameter can
be specified using JSON [Link] parameter is optional.
 xhr: A callback for creating the XMLHttpRequest object.
 success:A callback function to be executed when Ajax request succeeds.
 data: A data to be sent to the server. It can be JSON object, string or array.
 timeout: A number value in milliseconds for the request timeout.

28 Vijayan.R / Prof / SCORE 2/9/2026


<!DOCTYPE html> <html><head>
<meta name="viewport" content="width=device-width" /><script
src=[Link]
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#ajaxBtn').click(function(){
$.ajax('/jquery/getdata', // request url
{ success: function (data, status, xhr) { // success callback function
$('p').append(data); } }); }); });
</script></head><body>
<h1> jQuery ajax() demo Retrive data from server </h1>
<input type="button" id="ajaxBtn" value="Send Ajax request" />
<p> </p></body></html>

29 Vijayan.R / Prof / SCORE 2/9/2026


$(document).ready(function () {
$('#ajaxBtn').click(function(){
$.ajax('/jquery/getjsondata', {
dataType: 'json', // type of response data
timeout: 500, // timeout milliseconds
success: function (data,status,xhr) { // success callback function
$('p').append([Link] + ' ' + [Link] + ' ' +
[Link]); },
error: function (jqXhr, textStatus, errorMessage) { // error callback
$('p').append('Error: ' + errorMessage); }}); });});

30 Vijayan.R / Prof / SCORE 2/9/2026


$(document).ready(function () {
$('#ajaxBtn').click(function(){
$.ajax('/jquery/submitData', {
type: 'POST', // http method
data: { myData: ' This is mareeswari data.' }, // data to submit
success: function (data, status, xhr) {
$('p').append('status: ' + status + ', data: ' + data); },
error: function (jqXhr, textStatus, errorMessage) {
$('p').append('Error: ' + errorMessage); }});}); });

In the options parameter, we have specified a type


option as a POST, so ajax() method will send http
POST request. Also, we have specified data option
as a JSON object containing data which will be
31 Vijayan.R / Prof / SCORE submitted to the server. 2/9/2026
 The jQuery get() method sends asynchronous http GET request to the
server and retrieves the data.
 Syntax: $.get(url, [data],[callback]);
 The jQuery post() method sends asynchronous http POST request to the
server to submit the data to the server and get the response.
 Syntax: $.post(url,[data],[callback],[type]);
 The jQuery load() method allows HTML or text content to be loaded
from a server and added into a DOM element.
 The jQuery load() method allows HTML or text content to be loaded
from a server and added into a DOM element.
 Syntax: $.load(url,[data],[callback]);

32 Vijayan.R / Prof / SCORE 2/9/2026


Ajax will not die. Traditional Ajax refers to
XMLHttpRequest (XHR), Future It has now been
replaced by fetch.

33 Vijayan.R / Prof / SCORE 2/9/2026


 Persistent (or Keep-alive) Connections
 In HTTP/1.0, the server closes the TCP connection after delivering the response by default (Connection: Close). That
is, each TCP connection services only one request. This is not efficiency as many HTML pages contain hyperlinks
(via <a href="url"> tag) to other resources (such as images, scripts – either locally or from a remote server). If you
download a page containing 5 inline images, the browser has to establish TCP connection 6 times to the same server.
 The client can negotiate with the server and ask the server not to close the connection after delivering the response, so
that another request can be sent through the same connection. This is known as persistent connection (or keep-alive
connection). Persistent connections greatly enhance the efficiency of the network. For HTTP/1.0, the default
connection is non-persistent. To ask for persistent connection, the client must include a request header "Connection:
Keep-alive" in the request message to negotiate with the server.
 For HTTP/1.1, the default connection is persistent. The client do not have to sent the "Connection: Keep-alive"
header. Instead, the client may wish to send the header "Connection: Close" to ask the server to close the connection
after delivering the response.
 Persistent connection is extremely useful for web pages with many small inline images and other associated data, as all
these can be downloaded using the same connection. The benefits for persistent connection are:
 CPU time and resource saving in opening and closing TCP connection in client, proxy, gateways, and the origin server.
 Request can be "pipelined". That is, a client can make several requests without waiting for each response, so as to use
the network more efficiently.
 Faster response as no time needed to perform TCP’s connection opening handshaking.
 In Apache HTTP server, several configuration directives are related to the persistent connections:
 The KeepAlive directive decides whether to support persistent connections. This takes value of either On or Off.
 KeepAlive On|OffThe MaxKeepAliveRequests directive sets the maximum number of requests that can be sent
through a persistent connection. You can set to 0 to allow unlimited number of requests. It is recommended to set to a
high number for better performance and network efficiency.
 MaxKeepAliveRequests 200The KeepAliveTimeOut directive set the time out in seconds for a persistent connection
to wait for the next request.
 KeepAliveTimeout 10
34 Vijayan.R / Prof / SCORE 2/9/2026
<html> <head> <script>
function loadXMLDoc(){
var xmlhttp;
if ([Link])
xmlhttp=new XMLHttpRequest();
[Link]=function()
{
if([Link]==4 && [Link]==200)
[Link]("myDiv").innerHTML=[Link];
}
[Link]("GET","[Link]",true);
[Link](); }
</script> </head> <body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body> </html>
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">

<script type = "application/javascript">


function loadJSON() {
var data_file = "[Link]";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("[Link]");

}catch (e) {

try{
http_request = new ActiveXObject("[Link]");
}catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}

}
}

http_request.onreadystatechange = function() {

if (http_request.readyState == 4 && http_request.status==200 ) {


// Javascript function [Link] to parse JSON data
var jsonObj = [Link](http_request.responseText);

// jsonObj variable now contains the data structure and can


// be accessed as [Link] and [Link].
[Link]("Name").innerHTML = [Link];
[Link]("Country").innerHTML = [Link];
}
}

http_request.open("GET", data_file, true);


http_request.send();
}

</script>

<title>[Link] JSON</title>
</head>

<body>
<h1>Cricketer Details</h1>

<table class = "src">


<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>

<div class = "central">


<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>

</body>

</html>
<html>
<head>
<meta content = "text/html; charset=utf-8">
<title> JSON in Ajax JQuery </title>
<script>
function load()
{
var url = "[Link]";
var req;
if ([Link]){
req = new XMLHttpRequest();
}
else if ([Link]) {
req=new ActiveXObject ("[Link]");
}
[Link] = function() {
if ([Link] == 4)
{
var JSONObj = [Link]([Link]);
var dd=new Date([Link]);
[Link]("Day").innerHTML = [Link]();
[Link]("Month").innerHTML = [Link]()+1;
[Link]("Year").innerHTML = [Link]();
}}
[Link] ("GET", url, true);
[Link] ();
}
</script>
</head>
<body>
Day: <span id="Day"></span><br/>
Month: <span id="Month"></span><br/>
Year: <span id="Year"></span><br/>
<button type="button" onclick="load()">Click here to load info.</button>
</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>

<p>The getAllResponseHeaders() function returns all the header information of a resource, like
length, server-type, content-type, last-modified, etc:</p>

<p id="demo"></p>

<script>
var xhttp = new XMLHttpRequest();
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
[Link]("demo").innerHTML =
[Link]();
}
};
[Link]("GET", "[Link]", true);
[Link]();
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>

<p>The getResponseHeader() function is used to return specific header information from a


resource, like length, server-type, content-type, last-modified, etc:</p>

<p>Last modified: <span id="demo"></span></p>

<script>
var xhttp=new XMLHttpRequest();
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
[Link]("demo").innerHTML =
//[Link]("Last-Modified");
[Link]("Content-type");
}
};
[Link]("GET", "[Link]", true);
[Link]();
</script>

</body>
</html>
<!DOCTYPE html> <html><head>
<meta name="viewport" content="width=device-width" />
<script src=[Link] </script>
<script type="text/javascript">
$(document).ready(function () {
$('#ajaxBtn').click(function(){
$.ajax('[Link]', {
dataType: 'json', // type of response data
timeout: 5000, // timeout milliseconds
success: function (data,status,xhr) { // success callback function
$('p').append([Link] + ' ' +
[Link] + ' ' +[Link]); },
error: function (jqXhr, textStatus, errorMessage) { // error callback
$('p').append('Error: ' + errorMessage); }}); });});

</script></head><body>
<h1> jQuery ajax() demo Retrive data from server </h1>
<input type="button" id="ajaxBtn" value="Send Ajax request" />
<p> </p></body></html>
<html>
<head><script src="[Link]
></script></head>
<body><div>
<label>Start location:
<input type="text" id="start" /></label>
<label>End location:
<input type="text" id="dest" /></label>
<label>Non-stop?
<input type="checkbox" id="stops"></label>
<button id="go">Go!</button>
</div><div id="results"></div>
<script>
$(document).ready(function(){
$("#go").click(function(){
var noStops = $("#stops").is(":checked");
var start = $("#start").val();
var dest = $("#dest").val();
$("#results").val("");
var jsonflights="";
$.ajax('[Link]',{
dataType: 'json', // type of response data
timeout: 5000, // timeout milliseconds
success: function (data,status,xhr) { // success callback function
jsonflights = data;
var title = "<h1>Flights from " + start
+ " to " + dest +"</h1>";
$("#results").append(title);
var mydata = jsonflights[dest];
for(var i = 0;i<[Link];i++){
var flight = mydata["flights"][i];
if(flight["stops"] == 0 || !noStops) {
var ele=$("<p id='p1'></p>").text("$"
+ flight["price"] + " from " +
flight["carrier"] + " with " +
flight["stops"] +" stops");
$("#results").append(ele);
if(flight["price"] < 1000) {
$("#p1").css({"font-weight":"bold"});
}}
}}});});});
</script>

</body></html>
{"Edinburgh":{
"start":"Seattle",
"flights":[{"carrier":"Delta","price":812,
"stops":2},
{"carrier":"Air France","price":1020,
"stops":0},
{"carrier":"Air France","price":1190,
"stops":3}]
},"New York":{
"start":"Seattle",
"flights":[{"carrier":"British Airlines",
"price":782,"stops":1},
{"carrier":"Delta","price":1562,"stops":2},
{"carrier":"United","price":957,"stops":1},
{"carrier":"KLM","price":687,"stops":3},
{"carrier":"KLM","price":1458,"stops":1}]
}
}
Module 4
Client/Server Communication
 HTTP- Request/Response Model
 HTTP Methods
 RESTful APIs
 AJAX
 AJAX with JSON

[Link] / Prof / SCORE


HyperText Transfer Protocol (HTTP)

[Link] / Prof / SCORE


HTTP
 HTTP is an asymmetric request-response client-server protocol. An
HTTP client sends a request message to an HTTP server. The
server, in turn, returns a response message. In other words,
HTTP is a pull protocol, the client pulls information from the
server (instead of server pushes information down to the client).
 HTTP is a stateless protocol. In other words, the current request
does not know what has been done in the previous requests.
 HTTP permits negotiating of data type and representation, so as
to allow systems to be built independently of the data being
transferred.
 It is an application-level protocol for distributed, collaborative,
hypermedia information systems.
[Link] / Prof / SCORE
HTTP Request and Response Messages
 An HTTP message consists of a message header and an
optional message body, separated by a blank line.

[Link] / Prof / SCORE


HTTP Request Message
 request-method-name request-URI HTTP-version
 request-method-name: HTTP protocol defines a set of request
methods, e.g., GET, POST, HEAD, and OPTIONS.
 The client can use one of these methods to send a request to the
server.
 request-URI: specifies the resource requested.
 HTTP-version: HTTP/1.0 and HTTP/1.1.

[Link] / Prof / SCORE


HTTP Response Message
 The response message body contains the resource data requested.

[Link] / Prof / SCORE


Status Line
 The status code is a 3-digit number:
 1xx (Informational): Request received, server is continuing the
process.
 2xx (Success): The request was successfully received, understood,
accepted and serviced.
 3xx (Redirection): Further action must be taken in order to
complete the request.
 4xx (Client Error): The request contains bad syntax or cannot be
understood.
 5xx (Server Error): The server failed to fulfill an apparently valid
request.

[Link] / Prof / SCORE


Some common HTTP status codes
Status Range Description Examples
100 Informational 100 Continue
200 Successful 200 OK
201 Created
202 Accepted
300 Redirection 301 Moved Permanently
304 Not Modified
400 Client error 401 Unauthorized
402 Payment Required
404 Not Found
405 Method Not Allowed
500 Server error 500 Internal Server Error
[Link]
501 / Prof / SCORE
Not Implemented
HTTP Request Methods
 A client can use one of these request methods to send a request message to
an HTTP [Link] methods are:
 GET: A client can use the GET request to get a web resource from the
server.
 HEAD: A client can use the HEAD request to get the header that a GET
request would have obtained. Since the header contains the last-modified
date of the data, this can be used to check against the local cache copy.
 POST: Used to post data up to the web server.
 PUT: Ask the server to store the data.
 DELETE: Ask the server to delete the data.
 TRACE:Ask the server to return a diagnostic trace of the actions it takes.
 OPTIONS: Ask the server to return the list of request methods it supports.
 Refer more on this: [Link]
[Link] / Prof / SCORE
URL and URI
 URL (Uniform Resource Locator) is used to uniquely identify a
resource over the web.
 protocol://hostname:port/path-and-file-name
 Eg://[Link]/docs/[Link],[Link]
news:[Link], telnet://[Link]/
 The URL after encoding is called encoded URL. (%20 or '+‘ for blank space)
 URI (Uniform Resource Identifier) is more general than URL, which
can even locate a fragment within a resource.
 [Link]
 The request parameters, in the form of name=value pairs, are separated from
the URL by a '?'.The name=value pairs are separated by a '&'.
 The #nameAnchor identifies a fragment within the HTML document,
defined via the anchor tag <a name="anchorName">...</a>.
 URL rewriting for session management, e.g., "...;sessionID=xxxxxx".
[Link] / Prof / SCORE
REST
 Representational state transfer (REST)
or RESTful Web services are one way of providing
interoperability between computer systems on
the Internet. It was introduced and defined in 2000
by Roy Fielding in his doctoral dissertation.
 REST is an architecture style for designing networked
applications. It is a lightweight that, rather than using
complex mechanisms such as CORBA, RPC or SOAP to
connect between machines, simple HTTP is used to make
calls between machines. In many ways, the World Wide Web
itself, based on HTTP, can be viewed as a REST-based
architecture.
[Link] / Prof / SCORE
 RESTful applications use HTTP requests to post data (create
and/or update), read data (e.g., make queries), and delete
data.
 Thus, REST uses HTTP for all four CRUD
(Create/Read/Update/Delete) operations.
 REST is not a "standard". There will never be a W3C
recommendation for REST, for example.
 DNS is another valid discovery mechanism. FWIW, UDDIv3
does specify a REST interface.
 A REST service is a web service, but a web service is not
necessarily a REST service.

[Link] / Prof / SCORE


REST Constraints
 If you follow all constraints (design rules) designed by the
REST architectural style your systems is considered
RESTful. These constraints don't dictate what kind of
technology to use; they only define how data is transferred
between components and what benefits we get following the
guidelines.
 Client-Server
 Stateless
 Cacheable
 Uniform Interface
 Layered System
 Code On Demand (Optional)
[Link] / Prof / SCORE
Client-Server
 A client component that sends requests and a server component
that receives requests. After receiving a request the server may also
issue a response to the client.
 Applying separation of concerns: Client-Server as in the diagram :
 Separates user interface concerns from data storage concerns.
 Improves portability of interface across multiple platforms.
 Improves scalability by simplifying server components.
 Allows the components to evolve independently.

[Link] / Prof / SCORE


Stateless
 The constraint says that the server should not remember the
state of the application. As a consequence, the client should
send all information necessary for execution along with each
request, because the server cannot reuse information from
previous requests as it didn’t memorize them.

[Link] / Prof / SCORE


"State Transfer" in REST
 Services in REST do not maintain the state of an interaction
with a requester; that is, if an interaction requires a state, all
states must be part of the messages exchanged.
 By being stateless, services increase their reliability by
simplifying recovery processing. (A failed service can recover
quickly.)
 Furthermore, scalability of such services is improved because
the services do not need to persist state and do not consume
memory, representing active interactions.
 Both reliability and scalability are required properties of the
Web. By following the REST architectural style, you can meet
[Link]
requirements.
/ Prof / SCORE
Cacheable
 REST includes cache constraints so that the "second fetch" doesn't have
to be made at all if the data is already sitting in your local cache.
 If your data can be designed in such a way to take advantage of this, you
can reduce total network traffic by orders of magnitude.

[Link] / Prof / SCORE


Uniform Interface
 REST assumes a simple interface to manipulate resources in a
generic manner. This interface basically supports the create,
retrieve, update, and delete (CRUD) method.

[Link] / Prof / SCORE


 REST is defined by four interface constraints: identification
of resources; manipulation of resources through
representations; self-descriptive messages; and,
hypermedia as the engine of application state.
 Messages are self-describing.
 Example : Each request can be interpreted by itself
1. /search-results?q=to-do
2. /search-results?q=todo&page=2
3. /search-results?q=todo&page=3

[Link] / Prof / SCORE


"Representational" in REST
 The basic concept of the REST architecture is that of a
resource.
 A resource is any piece of information that you can identify
uniquely.
 In REST, requesters and services exchange messages that
typically contain both data and metadata.
 The data part of a message corresponds to the resource in a
particular representation as described by the accompanying
metadata (format), which might also contain additional
processing directives.
 You can exchange a resource in multiple representations.
Both communication partners might agree to a particular
[Link] / Prof / SCORE
representation in advance.
 For example, the data of a message might be information about
the current weather in New York City the resource. The data
might be rendered as an HTML document, and the language in
which this document is encoded might be German.
 In the REST architectural style, servers only offer resources.
Resources are conceptual things about which clients and servers
communicate.
 Example for REST resource: /todolists/7/items/35/
 This above thing is not a command, it is the address of a
resource, a thing.
 Representation might be in any format: HTML, JSON,XML,
Pdf,Video,…
 Eg Video Resource:
 [Link]

[Link] / Prof / SCORE


Layered System
 There are many layers between the client and the server.
These are called intermediaries and can be added at various
points in the request-response path without changing the
interfaces between components, where they do things to
passing messages such as translation or improving
performance with caching.
 Intermediaries include proxies (Chosen by Client) and
gateways (Chosen by Server).
 This contributes to the scalability of the overall
environment.

[Link] / Prof / SCORE


[Link] / Prof / SCORE
Code on Demand (Optional)
 It allows a client to download and execute code from a server.
 For example, if all of the client software within an organization is
known to support Java applets , then services within that
organization can be constructed such that they gain the benefit of
enhanced functionality via downloadable Java classes.
 At the same time, however, the organization's firewall may prevent
the transfer of Java applets from external sources, and thus to the
rest of the Web it will appear as if those clients do not support
code-on-demand.
 This simplifies clients by reducing the number of features required
to be pre-implemented.

[Link] / Prof / SCORE


[Link] / Prof / SCORE
REST and HTTP are not same !!
 REST != HTTP
 In simplest words, in the REST architectural style, data and
functionality are considered resources and are accessed using Uniform
Resource Identifiers (URIs). The resources are acted upon by using a
set of simple, well-defined operations. The clients and servers
exchange representations of resources by using a standardized
interface and protocol – typically HTTP.

[Link] / Prof / SCORE


Real Time Examples
 [Link] 
[Link]
Enterprise Web Services are a set of consistent, secure, REST Web services that
enable UW developers to integrate applications and Web pages with essential
UW business systems.
 Service Options
 Enterprise Web Services are fully documented in the UW Web Services
Registry ([Link]).They include:
 StudentWeb Service (SWS) -SWS v5.4.1 Released 01/25/2017
 HR/Payroll Web Service (HRPWS)
 FinancialWeb Service (FWS)
 Person Web Service (PWS)
 SpaceWeb Service
 ID Card Web Service
[Link] / Prof / SCORE
What is the MEAN stack?

The MEAN stack can be summarized as follows:

 M = MongoDB/[Link]: the popular database, and an elegant ODM for [Link].


 E = [Link]: a lightweight web application framework.
 A = [Link]: a robust framework for creating HTML5 and JavaScript-rich web
applications.
 N = [Link]: a server-side JavaScript interpreter.

The MEAN stack is a modern replacement for the LAMP (Linux, Apache, MySQL,
PHP/Python) stack that became the popular way for building web applications in the late
1990s.

A REST API which has no user interface, but could instead serve as the basis for any kind of
interface, such as a website, an Android application, or an iOS application.

What is a REST API?

REST stands for Representational State Transfer. It is a lighter weight alternative to SOAP
and WSDL XML-based API protocols.

REST uses a client-server model, where the server is an HTTP server and the client sends
HTTP verbs (GET, POST, PUT, DELETE), along with a URL and variable parameters that
are URL-encoded. The URL describes the object to act upon and the server replies with a
result code and valid JavaScript Object Notation (JSON).

Because the server replies with JSON, it makes the MEAN stack particularly well suited for
our application, as all the components are in JavaScript and MongoDB interacts well with
JSON. We will see some JSON examples later, when we start defining our Data Models.

The CRUD acronym is often used to describe database operations. CRUD stands for
CREATE, READ, UPDATE, and DELETE. These database operations map very nicely to
the HTTP verbs, as follows:

 POST: A client wants to insert or create an object.


 GET: A client wants to read an object.
 PUT: A client wants to update an object.
 DELETE: A client wants to delete an object.

These operations will become clear later when define our API.

Some of the common HTTP result codes that are often used inside REST APIs are as follows:

 200 - “OK”.
 201 - “Created” (Used with POST).
 400 - “Bad Request” (Perhaps missing required parameters).
 401 - “Unauthorized” (Missing authentication parameters).
 403 - “Forbidden” (You were authenticated but lacking required privileges).
 404 - “Not Found”.
A complete description can be found in the RFC document, listed in the resources section at
the end of this blog. We will use these result codes in our application and you will see some
examples shortly.

Why Are We Starting with a REST API?

Developing a REST API enables us to create a foundation upon which we can build all other
applications. As previously mentioned, these applications may be web-based or designed for
specific platforms, such as Android or iOS.

Today, there are also many companies that are building applications that do not use an HTTP
or web interface, such as Uber, WhatsApp, Postmates, and [Link]. A REST API also makes
it easy to implement other interfaces or applications over time, turning the initial project from
a single application into a powerful platform.

Functional Requirements for the REST API

 Create an account.
 Subscribe/unsubscribe to feeds.
 Read feed entries.
 Mark feeds/entries as read or unread.

Additionally, a user should be able to reset their password.

The following table shows how these operations can be mapped to HTTP routes and verbs.

Route Verb Description Variables


firstName
lastName
/user/enroll POST Register a new user
email
password
/user/resetPassword PUT Password Reset email
Get feed subscriptions for
each user with
/feeds GET
description and unread
count
/feeds/subscribe PUT Subscribe to a new feed feedURL
Get all entries for feeds
/feeds/entries GET
the user is subscribed to
Get all entries for a
/feeds/&ltfeedid&gt/entries GET
specific feed
Mark all entries for a read =
/feeds/&ltfeedid&gt PUT specific feed as read or &lttrue |
unread false&gt
read =
Mark a specific entry as
/feeds/&ltfeedid&gt/entries/&ltentryid&gt PUT &lttrue |
either read or unread
false&gt
Route Verb Description Variables
Unsubscribe from this
/feeds/&ltfeedid&gt DELETE
particular feed

In a production environment, the use of secure HTTP (HTTPS) would be the standard
approach when sending sensitive details, such as passwords.
<!DOCTYPE html>
<!--class selector-->
<html>
<head>
<!--<script src="[Link]
<script src="[Link]
<script>
$(document).ready(function(){
$("#click").click(function(){
$(".test").hide();
});
$("#show").click(function(){
$(".test").show();
});
});
</script>
</head>
<body>

<h2 class="test">This is a heading</h2>

<p class="test">This is a paragraph.</p>


<p>This is another paragraph.</p>

<button id="click">Click me</button>


<button id="show">show</button>

</body>
</html>
<!DOCTYPE html>
<!--element selector-->
<html>
<head>
<script
src="[Link]
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide(5000);
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button id="hide">Click me to hide paragraphs</button>


<button id="show">Click me to show paragraphs</button>
</body>
</html>
<!DOCTYPE html>
<!--events-->
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#p1").click(function(){
$(this).hide();
});
$("#p2").dblclick(function(){
$(this).hide();
});
/*
$("#p3").mouseenter(function(){
alert("You entered p1!");
});
/*
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");

$("#p1").mousedown(function(){
alert("Mouse down over p1!");});

$("#p1").mouseup(function(){
alert("Mouse up over p1!");});

$("#p4").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
*/
$("input").focus(function(){
$(this).css("background-color", "yellow");
});
$("input").blur(function(){
$(this).css("background-color", "green");
});

$("#p5").on({
mouseenter:function(){
$(this).css("background-color","lightgray");
},
mouseleave:function(){
$(this).css("background-color", "lightblue");
},
click:function(){
$(this).css({"background-color":"yellow","color":"red"});
}
});

});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>


<p id="p1">1 Click me away!</p>
<p id="p2">2 dbl Click me too!</p>
<p id="p3">3 "mouseenter" Click me too!</p>
<p id="p4">4 "hover" Click me too!</p>
<p id="p5">5 "input css" Click me too!</p>
Name: <input type="text" name="fullname"><br>
Email: <input type="text" name="email">
</body>
</html>
<!DOCTYPE html>
<!--ID selector-->
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide(5000);
});
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>

<button>Click me</button>

</body>
</html>
<!DOCTYPE html>
<!--showhidetoggle-->
<html>
<head>
<!--<script src="[Link]
<script src="[Link]

<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
$("#hidesecond").click(function(){
$("p").hide(1000);
});
$("#slow").click(function(){
$("p").show(1000);
});
$("#second").click(function(){
$("p").hide(1000);
});
$("#toggle").click(function(){
$("p").toggle(1000);
});
});
</script>
</head>
<body>

<p>If you click on the "Hide" button, I will disappear.</p>

<button id="hide">Hide</button>
<button id="show">Show</button>
<button id="hidesecond">hide in 1 second</button>
<button id="slow">show in slow</button>
<button id="toggle">toggle show p</button>
</body>
</html>
<!DOCTYPE html>
<!--fadein fadeout fadetoggle fateto-->
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#fadein").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
$("#fadeout").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
$("#fadetoggle").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
$("#fadeto").click(function(){
$("#div1").fadeTo("slow",NBSP0.15);
$("#div2").fadeTo("slow",NBSP0.4);
$("#div3").fadeTo("slow",NBSP0.7);});

});
</script>
</head>
<body>

<p>Demonstrate fadeIn() with different parameters.</p>

<button id="fadein">Click to fade in boxes</button>


<button id="fadeout">Click to fade out boxes</button>
<button id="fadetoggle">Click to fade toggle boxes</button>
<button id="fadeto">Click to fadeto toggle boxes</button><br><br>
<div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div>

</body>
</html>
<!DOCTYPE html>
<!--slidingupdown-->
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown();
});
$("#flipup").click(function(){
$("#panel").slideUp();
});
$("#fliptoggle").click(function(){
$("#panel").slideToggle(3000);
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel {
padding: 50px;
display: none;
}
#flipup {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#fliptoggle {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
</style>
</head>
<body>

<div id="flip">Click to slide down panel</div>


<div id="panel">Hello world!</div>
<div id="flipup">Click to slide up panel</div>
<div id="fliptoggle">Click to slideToggle panel</div>
</body>
</html>
<!DOCTYPE html>
<!--animate-->
<html>
<head>
<!--<script src="[Link]
<script src="[Link]
<script>
$(document).ready(function(){
$("#first").click(function(){
$("div").animate({left: '250px'});
});

$("#secondmultiple").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
$("#togglebutton").click(function(){
$("div").animate({
height: 'toggle'
});
});

$("#queuebutton").click(function(){
var div = $("div");
[Link]({height: '300px', opacity: '0.4'}, "slow");
[Link]({width: '300px', opacity: '0.8'}, "slow");
[Link]({height: '100px', opacity: '0.4'}, "slow");
[Link]({width: '100px', opacity: '0.8'}, "slow");
});
});
</script>
</head>
<body>

<button id="first">Start Animation</button>


<button id="secondmultiple">Start Animation multiple css</button>
<button id="togglebutton">Start Animation toggle</button>
<button id="queuebutton">Start Animation queue animate</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the
position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div><br>

</body>
</html>
<!DOCTYPE html>
<!--stopeffects-->
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
font-size: 18px;
text-align: center;
background-color: #555;
color: white;
border: solid 1px #666;
border-radius: 3px;
}

#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>

<button id="stop">Stop sliding</button>

<div id="flip">Click to slide down panel</div>


<div id="panel">Hello world!</div>

</body>
</html>
<!DOCTYPE html>
<!--chaining-->
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("color", "red").slideUp(2000).slideDown(2000).fadeIn(3000);
});
});
</script>
</head>
<body>

<p id="p1">jQuery is fun!!</p>

<button>Click me</button>

</body>
</html>
<!DOCTYPE html>
<!--DOM manipulation-text-html-val-attr-->
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
//get
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
$("#btn3").click(function(){
alert("Value: " + $("#test7").val());
});
$("#btn4").click(function(){
alert($("#w3s").attr("href"));
});
//set
$("#btn5").click(function(){
$("#test1").text("Hello world!");
});
$("#btn6").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn7").click(function(){
$("#test7").val("Dolly Duck");
});

});
</script>
</head>
<body>

<p id="test">This is some <b>bold</b> text in a paragraph.</p>


<p id="test1">This is some <b>bold</b> text in a paragraph.</p>
<p id="test2">This is some <b>bold</b> text in a paragraph.</p>
<p id="test3">This is some <b>bold</b> text in a paragraph.</p>
<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>
<button id="btn3">Show value</button>
<button id="btn4">Show attribute</button>
<button id="btn5">Set Text</button>
<button id="btn6">Set HTML</button>
<button id="btn7">Set value</button>

<p>Name: <input type="text" id="test7" value="Mickey Mouse"></p><br>


<p><a href="[Link] id="w3s">VIT-Vellore Institute of Technology</a></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#check").click(function(){
$("input[name='rd1']").css("background-color","red");
}); });
</script>
</head>
<body>

<form action="">
Name: <input type="text" name="user"><br>
Password: <input type="password" name="password"><br>
<button type="button">Useless Button</button>
<input type="button" value="Another useless button"><br>
<input type="radio" value="rd" name="rd1" checked="true">radfasdf<br>
<input type="reset" value="Reset">
<input type="button" id="check" value="Submit"><br>
</form>

</body>
</html>
<html>
<head>
<title>The Selector Example</title>
<script src="[Link]

<script type = "text/javascript" language = "javascript">


$(document).ready(function() {
/* Selects all elements matched by <input> that have a name value exactly equal to
username.*/
$("input[name='username']").val("Enter Name!");
$("input[name='username']").css("background-color","yellow");
});
</script>
</head>

<body>
<input type = "text" name = "username"></input>
<br/><br/>
<input type = "text" name = "password"></input>
<br/><br/>
<input type = "text" name = "email"></input>
</body>
</html>
<html> <head>
<script src="[Link]
</script><script>
$(document).ready(function(){
$("#btn").click(function(){
alert("Your Full Name is: " + $("#t1").val()+$("#t2").val());
//[Link]("Your Full Name is: " + $("#t1").val()+$("#t2").val());
}); });
</script></head><body>
<p> First Name: <input type="text" id="t1"></p>
<p> Last Name:<input type="text" id="t2"></p>

<button id="btn">Show Value</button>


</body></html>
<html> <head>
<script src="[Link]">
</script><script>
$(document).ready(function(){
$("#btn1").click(function(){
alert("Text: " + $("#test").text()); });
$("#btn2").click(function(){
alert("HTML: " + $("#test").html()); });
$("#btn3").click(function(){
alert("Value: " + $("#t1").val()); }); });
</script></head><body>
<p id="test">This is some <b>bold</b> text in a paragraph.</p>
<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>
<p>Name: <input type="text" id="t1" value="Mickey Mouse"></p>
<button id="btn3">Show Value</button>
</body></html>
<!DOCTYPE html>
<!--Adding elements-->
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});

$("#btn2").click(function(){
$("ol").append("<li>Appended item</li>");
});
$("#btn3").click(function(){
$("p").prepend("<b>Prepended text</b>. ");
});
$("#btn4").click(function(){
$("ol").prepend("<li>Prepended item</li>");
});
$("#btn5").click(function(){
$("img").before("<b>Before</b>");
});

$("#btn6").click(function(){
$("img").after("<i>After</i>");
});
});
function appendText() {
var txt1 = "<p>Texthtml.</p>"; // Create text with HTML
var txt2 = $("<p></p>").text("Textjquery."); // Create text with jQuery
var txt3 = [Link]("p");
[Link] = "TextJSDOM."; // Create text with DOM
$("body").append(txt1, txt2, txt3); // Append new elements
}
function afterText() {
var txt1 = "<b>I </b>"; // Create element with HTML
var txt2 = $("<i></i>").text("love "); // Create with jQuery
var txt3 = [Link]("b"); // Create with DOM
[Link] = "jQuery!";
$("ol").after(txt1, txt2, txt3); // Insert new elements after img
}
</script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>

<button id="btn1">Append text</button>


<button id="btn2">Append list items</button>
<button id="btn3">Prepend text</button>
<button id="btn4">Prepend list item</button>
<button onclick="appendText()">Append text several elements</button>
<img src="[Link]" alt="jQuery" width="100" height="140"><br><br>

<button id="btn5">Insert before</button>


<button id="btn6">Insert after</button>
<button onclick="afterText()">Insert after several elements</button>

</body>
</html>
<!DOCTYPE html>
<!--remove elements-->
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#remove").click(function(){
$("#div1").remove();
});
$("#empty").click(function(){
$("#div1").empty();
});
$("#filterremove").click(function(){
$("p").remove(".test");
});
});
</script>
</head>
<body>

<div id="div1" style="height:400px;width:300px;border:1px solid black;background-color:yellow;">

<p>This is some text in the div.</p>


<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
<p class="test">This is p element with class="test".</p>
<p class="test">This is p element with class="test".</p>
<p class="demo">This is p element with class="demo".</p>

</div>
<br>

<button id="remove">Remove div element</button>


<button id="empty">Empty div element</button>
<button id="filterremove">filter remove p element</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("city").each(function(index,element){
if([Link]()=='on'){
[Link]("background-color","green");
}
});
});
</script>
</head>
<body>

<input type="radio" class="city" value="ny" name="cityname">NY<br>


<input type="radio" class="city" value="paris" name="cityname">PS<br>
<input type="radio" class="city" value="london" name="cityname">LD<br>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Form Validation jQuery:Demo Preview</title>
<script src="[Link]
<script>
$(document).ready(function() {

$("#submit").click(function() {

// Initializing Variables With Form Element Values


var firstname = $("#firstname").val();
var addr = $("#addr").val();
var zip = $("#zip").val();
var state = $("#state").val();
var username = $("#username").val();
var uemail = $("#email").val();

// Initializing Variables With Regular Expressions


var name_regex = "/^[a-zA-Z]+$/";
//var email_regex = "/^[w-.+]+@[a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/";
var emailpatt="/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/";
var add_regex = "/^[0-9a-zA-Z]+$/";
var zip_regex = "/^[0-9]+$/";

// To Check Empty Form Fields.


if([Link]==0) {
$("#display").text("* All fields are mandatory *");
$("#firstname").focus();
return false;
}

// Validating Name Field.


else if (([Link](name_regex)==false) || [Link] == 0) {
$("#p1").text("* For your name please use alphabets only *");
// This Segment Displays The Validation Rule For Name
$("#firstname").focus();
return false;
}
// Validating Username Field.
else if (([Link] <= 6 && [Link] >= 8) || [Link] == 0) {
$("#p2").text("* Please enter between 6 and 8 characters *");
// This Segment Displays The Validation Rule For Username
$("#username").focus();
return false;
}

// Validating Email Field.


else if(([Link](emailpatt)==false) || [Link] == 0) {
$("#p3").text("* Please enter a valid email address *");
alert(uemail);
// This Segment Displays The Validation Rule For Email
$("#email").focus();
return false;
}
// Validating Select Field.
else if (state == "Please Choose") {
$("#p4").text("* Please Choose any one option");
// This Segment Displays The Validation Rule For Selection
$("#state").focus();
return false;
}
// Validating Address Field.
else if ([Link](add_regex)==false || [Link] == 0) {
$("#p5").text("* For Address please use numbers and letters *");
// This Segment Displays The Validation Rule For Address
$("#addr").focus();
return false;
}
// Validating Zip Field.
else if ([Link](zip_regex)==false || [Link] == 0) {
$("#p6").text("* Please enter a valid zip code *");
// This Segment Displays The Validation Rule For Zip
$("#zip").focus();
return false;
} else {
alert("Form Submitted Successfuly!");
return true;
}
});
});

</script>
</head>
<body>
<div class="main">
<h1>Form Validation Using jQuery</h1>
<div id="form">
<h2>Java script form validation</h2>
<form method="get"> <!-- Form Starts From Here -->
<p id="display"></p>
<label>Full Name:</label>
<input type="text" id="firstname">
<p id="p1"></p> <!--This Segment Displays The Validation Rule For Name-->
<label>Username(6-8 characters):</label>
<input id="username" type="text">
<p id="p2"></p> <!-- This Segment Displays The Validation Rule For User Name -->
<label>Email:</label>
<input id="email" type="text">
<p id="p3"></p> <!-- This Segment Displays The Validation Rule For Email -->
<label>State:</label>
<select id="state">
<option>Please Choose</option>
<option>America</option>
<option>Australia</option>
<option>Sweden</option>
<option>Africa</option>
</select>
<p id="p4"></p> <!-- This Segment Displays The Validation Rule For Selection -->
<label>Address:</label>
<input id="addr" type="text">
<p id="p5"></p> <!-- This Segment Displays The Validation Rule For Address -->
<label>Zip Code:</label>
<input id="zip" type="text">
<p id="p6"></p> <!-- This Segment Displays The Validation Rule For Zip -->
<button id="submit">Check Form</button>
</form>
<!-- This Segment Displays The Validation Rule -->
</div>
</div>
</script>
</body>
</html>
JSON-JavaScript Object Notation.
JSON
 JSON stands for JavaScript Object Notation.
 It is an open standard data-interchange format.
 It is lightweight and self describing.
 It is originated from JavaScript.
 JSON is text, written with JavaScript object notation.
 It is easy to read and write than XML. For AJAX applications, JSON
is faster and easier than XML.
 It is language independent (interoperability).
 It supports array, object, string, number and values.
 The format was specified by Douglas Crockford.
 The JSON file must be save with .json extension.
 The MIME type for JSON text is "application/json"
[Link] / Asso Prof / SITE / VIT
JSON and XML
 JSON and XML are human readable formats and are language
independent. They both have support for creation, reading and
decoding in real world situations.
 JSON
{"car":{"company": “Volkswagen”, "name": "Vento", "price":
800000 }}
 XML
<car>
<company>Volkswagen</company>
<name>Vento</name>
<price>800000</price>
</car>
[Link] / Asso Prof / SITE / VIT
A syntax for storing and exchanging data
 When exchanging data between a browser and a server, the data can
only be text.
 JSON is text, and we can convert any JavaScript object into JSON,
and send JSON to the server.
 We can also convert any JSON received from the server into
JavaScript objects.
 This way we can work with the data as JavaScript objects, with no
complicated parsing and translations.
 If you have data stored in a JavaScript object, you can convert the
object into JSON, and send it to a server using [Link]().
 If you receive data in JSON format, you can convert it into a
JavaScript object using [Link]().

[Link] / Asso Prof / SITE / VIT


Uses of JSON
 It is used while writing JavaScript based applications that includes
browser extensions and websites.
 JSON format is used for serializing and transmitting structured data
over network connection.
 It is primarily used to transmit data between a server and web
applications.
 Web services and APIs use JSON format to provide public data.
 JSON uses JavaScript syntax, but the JSON format is text only.
Text can be read and used as a data format by any programming
language.

[Link] / Asso Prof / SITE / VIT


[Link] / Asso Prof / SITE / VIT
Example 1 – to store employee data -
[Link]
{"employees":[
{ "name":"Sonoo",
"email":"sonoojaiswal1987@[Link]"},
{ "name":"Rahul",
"email":"rahul32@[Link]"},
{ "name":"John",
"email":"john32bob@[Link]"}
]}

[Link] / Asso Prof / SITE / VIT


Example 2 – to store book data – [Link]
{ "book": [
{ "id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt" },
{ "id":"07",
"language": "C++",
"edition": "second",
"author": "[Link]" }
]}

[Link] / Asso Prof / SITE / VIT


JSON syntax
 Data is represented in name/value pairs. JSON names require double quotes.
JavaScript names don't.
 Curly braces hold objects and each name is followed by ':'(colon), the
name/value pairs are separated by , (comma).
{
"employee": {"name": "sonoo", "salary": 56000, "married": true}
}
 Square brackets hold arrays and values are separated by ,(comma).
1. ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sat
urday"]  Values in an Array
2. [ {"name":"Ram", "email":"Ram@[Link]"}, Objects in an Array
{"name":"Bob", "email":"bob32@[Link]"}
]
[Link] / Asso Prof / SITE / VIT
JSON Datatypes
 Number
 Integer (0-9 ,+ve,-ve), Fraction, Exponent.
 Octal and hexadecimal formats are not used.
 No NaN or Infinity is used in Number.
{
"integer": 34,
"fraction": .2145,
"exponent": 6.61789e+0
}
 String  It is a sequence of zero or more double quoted
Unicode characters with backslash escaping.
Eg: “aaa ”,’aaa’,\n,\t

[Link] / Asso Prof / SITE / VIT


JSON Datatypes
 Boolean  true, false
 Array  an ordered collection of values
 Value – String, number, true or false, null etc
 Object – unordered collection of key:value pairs
 Whitespace – can be used between any pair of tokens. It can be added
to make a code more readable.
var obj1 = {"name": "Sachin Tendulkar"}
var obj2 = {"name": "Saurav Ganguly"}
 null  empty type
var i = null;
 JSON values cannot be one of the following data types: a function, a
date, undefined
[Link] / Asso Prof / SITE / VIT
Accessing Object Values
myObj = { "name":"John", "age":30, "car":null };
 x = [Link];  Output: John
 x = myObj["name"];  Output: John
 for (x in myObj) {
[Link]("demo").innerHTML += x;
} Output:
name
age
car
 for (x in myObj) {
[Link]("demo").innerHTML += myObj[x];
} Output:
John
30
null
[Link] / Asso Prof / SITE / VIT
[Link]
<html><body>
<p>Use bracket notation to access the property values.</p>
<p id="demo"></p>
<script>
var myObj = {"name":"John", "age":30, "car":null};
for (x in myObj) {
[Link]("demo").innerHTML += myObj[x] +
"<br>";}
</script></body></html>

[Link] / Asso Prof / SITE / VIT


Nested Objects
<html> <body> <p>How to access nested JSON objects.</p>
<p id="demo"></p><script>
var myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat" } }
[Link]("demo").innerHTML += [Link].car2 +
"<br>"; //or:
[Link]("demo").innerHTML += [Link]["car2"];
</script> </body></html>

[Link] / Asso Prof / SITE / VIT


Modify Values
 [Link].car2 = "Mercedes"; //or
 [Link]["car2"] = "Mercedes";
Delete Object Properties
delete [Link].car2;

[Link] / Asso Prof / SITE / VIT


Arrays in JSON Objects
<body> <p>Looping through an array using a for in loop:</p>
<p id="demo"></p> <script>
var myObj, i, x = "";
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ] };
for (i in [Link]) {
x += [Link][i] + "<br>";}
[Link]("demo").innerHTML = x;
</script></body></html>
[Link] / Asso Prof / SITE / VIT
Nested Arrays in JSON Objects
 Values in an array can also be another array, or even another
JSON object:
 myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang"
] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
[Link] / Asso Prof / SITE / VIT
 Accessing:
for (i in [Link]) {
x += "<h1>" + [Link][i].name + "</h1>";
for (j in [Link][i].models) {
x += [Link][i].models[j];
}
}
 Modify using index:
[Link][1].name= "Mercedes";
 Delete using index:
delete [Link][1];

[Link] / Asso Prof / SITE / VIT


A common use of JSON is to exchange data to/from a web server.
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with [Link]()
<html> <body>
<h2>Create JSON string from a JavaScript object.</h2>
<p id="demo"></p><script>
var obj = {"name":"John", "age":30, "city":"NewYork"};
var myJSON = [Link](obj);
[Link]("demo").innerHTML = myJSON;
</script> </body></html>

[Link] / Asso Prof / SITE / VIT


A common use of JSON is to exchange data to/from a web
[Link] receiving data from a web server, the data is
always a string. Parse the data with [Link](), and the
data becomes a JavaScript object.
<html> <body><h2>Create Object from JSON String</h2>
<p id="demo"></p><script>
var txt = '{"name":"John", "age":30, "city":"NewYork"}'
var obj = [Link](txt);
[Link]("demo").innerHTML = [Link] + ",
" + [Link];
</script></body></html>

[Link] / Asso Prof / SITE / VIT


<!DOCTYPE html>
<html>
<body>
<h2>Convert a string into a date object.</h2>
<p id="demo"></p>
<script>
var text = '{"name":"John", "birth":"1986-12-14", "city":"NewYork"}';
var obj = [Link](text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}});
[Link]("demo").innerHTML = [Link] + ", " + [Link];
</script>
</body>
</html>

[Link] / Asso Prof / SITE / VIT


JSON Tools
 JSON Editors
 JSON Parser
 JSON Viewer
 JSON Tree Viewer Tool

[Link] / Asso Prof / SITE / VIT


[Link] / Asso Prof / SITE / VIT
[Link] / Asso Prof / SITE / VIT
JSON From the Server : You can request JSON from the server by using an
AJAX request. As long as the response from the server is written in JSON
format, you can parse the string into a JavaScript object.

[Link] / Asso Prof / SITE / VIT


[Link] / Asso Prof / SITE / VIT
The PHP File
 PHP has some built-in functions to handle JSON.
 Objects in PHP can be converted into JSON by using the PHP
function json_encode():
<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>

[Link] / Asso Prof / SITE / VIT


[Link] JSON Javascript

1 Strings in JSON must be written in double JavaScript names don't.


quotes. Eg: “name”:“John”

2 values must be one of the following data types: values can be all of the JSON value types,
a string,a number plus any other valid JavaScript
an object (JSON object),an array,a boolean expression, including: a function, a date,
and null undefined

[Link] / Asso Prof / SITE / VIT


Exercise
 Develop a json program for creating 20 students personal
information using the following fields as a inputs and print
the outputs in table format,student name,
date_of_birth(date,month,year),parents(fathers_name,moth
ers_name),
blood_group,email,phone(landline,mobile),address(door_no
,street_name,place_name,pincode),degree(ug,pg and
others),employee(self or organization).

[Link] / Asso Prof / SITE / VIT


JSON Schema
 JSON Schema is a specification for JSON based format for defining
the structure of JSON data. It was written under IETF draft which
expired in 2011. JSON Schema −
 Describes your existing data format.
 Clear, human- and machine-readable documentation.
 Complete structural validation, useful for automated testing.
 Complete structural validation, validating client-submitted data.

[Link] / Asso Prof / SITE / VIT


Introduction to JSON schema
Now we’re interacting with a JSON based product catalog.

 What is productId?
 Is productName required?
 Can the price be zero (0)?
 Are all of the tags string values?
 When you’re talking about a data format, you want to have
metadata about what keys mean, including the valid inputs for
those keys. JSON Schema is a proposed IETF standard how to
answer those questions for data.
[Link] / Asso Prof / SITE / VIT
JSON Schema
Languages Libraries
C WJElement (LGPLv3)
Java json-schema-validator (LGPLv3)
.NET [Link] (MIT)
ActionScript Frigga (MIT)
3
Haskell aeson-schema (MIT)
Python Jsonschema
Ruby autoparse (ASL 2.0); ruby-jsonschema (MIT)
PHP php-json-schema (MIT). json-schema (Berkeley)
Orderly (BSD); JSV; json-schema; Matic (MIT); Dojo;
JavaScript
[Link] / Asso Prof / SITE / VIT
Persevere (modified BSD or AFL 2.0); [Link].
JSON Schema
No. Keyword & Description
$schema :
1 The $schema keyword states that this schema is written according to the draft
v4 specification.
2 title : You will use this to give a title to your schema.

3 description : A little description of the schema.

type : The type keyword defines the first constraint on our JSON data: it has
4
to be a JSON Object.
properties : Defines various keys and their value types, minimum and
5
maximum values to be used in JSON file.
6 required : This keeps a list of required properties.

minimum : This is the constraint to be put on the value and represents


7
minimum acceptable value.
[Link] / Asso Prof / SITE / VIT
JSON Schema
exclusiveMinimum : If "exclusiveMinimum" is present and has
8 boolean value true, the instance is valid if it is strictly greater than
the value of "minimum".
maximum : This is the constraint to be put on the value and
9
represents maximum acceptable value.
exclusiveMaximum : If "exclusiveMaximum" is present and has
10 boolean value true, the instance is valid if it is strictly lower than the
value of "maximum".
multipleOf : A numeric instance is valid against "multipleOf" if the
11 result of the division of the instance by this keyword's value is an
integer.
maxLength : The length of a string instance is defined as the
12
maximum number of its characters.
[Link] / Asso Prof / SITE / VIT
{ "$schema": "[Link]
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": { JSON Schema Example
"id": {
"description": "The unique identifier for a product",
"type": "integer" },
"name": {
"description": "Name of the product",
"type": "string" },
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
} },
"required": ["id", "name", "price"] }
[Link] / Asso Prof / SITE / VIT
Example scenario
 This example provides a typical minimum you are likely to see in
JSON Schema. It contains: Data
 $id keyword
 $schema keyword
 title annotation keyword
 type instance data model
 properties validation keyword
 Three keys: firstName, lastName and age each with their own:
 description annotation keyword.
 type instance data model .
 minimum validation keyword on the age key.

[Link] / Asso Prof / SITE / VIT


JSON Schema
{ "$id": "[Link]
"$schema": "[Link]
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name." },
"lastName": {
"type": "string",
"description": "The person's last name." },
"age": {
"description": "Age in years which must be equal to or greater
than zero.",
"type": "integer",
"minimum": 0 } } }
[Link] / Asso Prof / SITE / VIT
Example :Describing geographical coordinates
{ "id": "[Link]
"$schema": "[Link] “
title": "Longitude and Latitude Values",
"description": "A geographical coordinate.",
"required": [ "latitude", "longitude" ],
"type": "object",
"properties": {
"latitude": { Data
"type": "number",
"minimum": -90,
"maximum": 90 },
"longitude": {
"type": "number",
"minimum": -180,
[Link] / Asso"maximum":
Prof / SITE / VIT 180 } } }
Arrays of things
Arrays are fundamental structures in JSON – here we demonstrate a
couple of ways they can be described:
 An array of string values.
 An array of objects.
Also introduced the following with this example:
 definitions keyword
 $ref keyword

[Link] / Asso Prof / SITE / VIT


{ "id": "[Link]
"$schema": "[Link]
"description": "A representation of a person, company, organization, or
place",
"type": "object",
"properties": { "fruits": { "type": "array", "items": { "type": "string" } },
"vegetables": { "type": "array", "items": { "$ref": "#/definitions/veggie"
} } },
"definitions": { "veggie": { "type": "object", "required": [ "veggieName",
"veggieLike" ],
"properties": { "veggieName": { "type": "string", "description": "The
name of the vegetable." }, “
veggieLike": { "type": "boolean", "description": "Do I like this vegetable?"
}}}}}
[Link] / Asso Prof / SITE / VIT
Write JSON Schema for following JSON Data
{ "productId": 1,
"productName": "An ice sculpture",
"price": 12.50,
"tags": [ "cold", "ice" ],
"dimensions": { "length": 7.0, "width": 12.0, "height": 9.5 },
"warehouseLocation": { "latitude": -78.75, "longitude": 20.4 } }

[Link] / Asso Prof / SITE / VIT


Quiz Question Data
myQuestions = [ { question: "Who is the strongest?", answers: { a:
"Superman", b: "The Terminator", c: "Waluigi, obviously" },
correctAnswer: "c" }, { question: "What is the best site ever created?",
answers: { a: "SitePoint", b: "Simple Steps Code", c: "Trick question;
they're both the best" }, correctAnswer: "c" }, { question: "Where is
Waldo really?", answers: { a: "Antarctica", b: "Exploring the Pacific
Ocean", c: "Sitting in a tree", d: "Minding his own business, so stop
asking" }, correctAnswer: "d" } ];

[Link] / Asso Prof / SITE / VIT


<!DOCTYPE html>
<html>
<body>

<p>Access a JSON object using dot notation:</p>

<p id="demo1"></p>
<p id="demo2"></p>
<script>
var myObj, x,y;
myObj={"name":"John", "age":30, "car":null};
x = [Link];
y = myObj["age"];
[Link]("demo1").innerHTML = x;
[Link]("demo2").innerHTML = y;
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<p>How to loop through all properties in a JSON object.</p>

<p id="demo1"></p>
<p id="demo2"></p>
<script>
var myObj, x,y;
myObj = {"name":"John", "age":30, "car":null};
for (x in myObj) {
[Link]("demo1").innerHTML += x + "<br>";
}

for (y in myObj) {
[Link]("demo2").innerHTML += myObj[y] + "<br>";
}
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<p>Access an array value of a JSON object.</p>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
var myObj, x,i;
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
};
x = [Link][0];
[Link]("demo1").innerHTML = x;

//loop
for (i in [Link]) {
x += [Link][i] + "<br>";
}
[Link]("demo2").innerHTML = x;

for (i = 0; i < [Link]; i++) {


x += [Link][i] + "<br>";
}
[Link]("demo3").innerHTML = x;

</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<p>Looping through arrays inside arrays.</p>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
var myObj, i, j,x = "";
myObj = {
"name":"John",
"age":30,
"cars": [
{"name":"Ford", "models":["Fiesta", "Focus", "Mustang"]},
{"name":"BMW", "models":["320", "X3", "X5"]},
{"name":"Fiat", "models":["500", "Panda"] }
]
}
for (i in [Link]) {
x += "<h2>" + [Link][i].name + "</h2>";
for (j in [Link][i].models) {
x += [Link][i].models[j] + "<br>";
}
}
[Link]("demo1").innerHTML = x;

//modify
[Link][1].name="Mercedes";

for (i in [Link]) {
x += [Link][i] + "<br>";
}
[Link]("demo2").innerHTML = x;

//delete
delete [Link][1];
for (i in [Link]) {
x += [Link][i] + "<br>";
}
[Link]("demo3").innerHTML = x;

</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<p>How to access nested JSON objects.</p>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="modify"></p>
<p id="delete"></p>
<script>
var i;
var myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
[Link]("demo1").innerHTML += [Link].car2 + "<br>";
var x;
[Link].car2 = "Mercedes"; //modify
for (i in [Link]) {
x += [Link][i] + "<br>";
}
[Link]("modify").innerHTML = x;

delete [Link].car2; //delete


for (i in [Link]) {
x += [Link][i] + "<br>";
}
[Link]("delete").innerHTML = x;

</script>
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>Create JSON string from a JavaScript object.</h2>

<p id="demo"></p>

<script>
var obj = { name: "John", age: 30, city: "New York" };
var myJSON = [Link](obj);
[Link]("demo").innerHTML = myJSON;
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>Create JSON string from a JavaScript array.</h2>

<p id="demo"></p>

<script>

var arr = [ "John", "Peter", "Sally", "Jane" ];


var myJSON = [Link](arr);
[Link]("demo").innerHTML = myJSON;

</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>[Link] will convert any date objects into strings.</h2>

<p id="demo"></p>

<script>
var obj = { name: "John", today: new Date(), city: "New York" };
var myJSON = [Link](obj);
[Link]("demo").innerHTML = myJSON;
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

<script>
var txt = '{"name":"John", "age":30, "city":"New York"}'
var obj = [Link](txt);
[Link]("demo").innerHTML = [Link] + ", " + [Link];
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>Convert a string into a date object.</h2>

<p id="demo"></p>

<script>
var text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = [Link](text);
[Link] = new Date([Link]);
[Link]("demo").innerHTML = [Link] + ", " + [Link];
</script>

</body>
</html>
Node JS
Introduction
 [Link] is a very powerful JavaScript-based framework/platform built
on Google Chrome's JavaScriptV8 Engine.
 [Link] allows you to run JavaScript on the server.
 [Link] was developed by Ryan Dahl in 2009 and its latest version is
v0.10.36.
 It is used to develop I/O intensive web applications like video
streaming sites, single-page applications, networking applications, and
other web applications.
 [Link] also provides a rich library of various JavaScript modules which
simplifies the development of web applications using [Link] to a great
extent.
 [Link] is open source, completely free, and used by thousands of
developers around the world.
[Link] = Runtime Environment + JavaScript Library
2 [Link] / Prof / SCORE / VIT
3 [Link] / Prof / SCORE / VIT
Why [Link]?
 [Link] uses asynchronous programming!
 A common task for a web server can be to open a file on the server and
return the content to the client.
Here is how PHP or ASP handles a file request:
 Sends the task to the computer's file system.
 Waits while the file system opens and reads the file.
 Returns the content to the client.
 Ready to handle the next request.
Here is how [Link] handles a file request:
 Sends the task to the computer's file system.
 Ready to handle the next request.
 When the file system has opened and read the file, the server returns the
content to the client.
 [Link] eliminates the waiting, and simply continues with the next request.
 [Link] runs single-threaded, non-blocking, asynchronously programming,
which is very memory efficient.
4 [Link] / Prof / SCORE / VIT
5 [Link] / Prof / SCORE / VIT
Who uses [Link]?
 Following is the link on github wiki containing an exhaustive list of
projects, application and companies which are using [Link]. This list
includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber,
Wikipins,Yahoo!, andYammer to name a few.

What Can [Link] Do?


 [Link] can generate dynamic page content
 [Link] can create, open, read, write, delete, and close files on the
server
 [Link] can collect form data
 [Link] can add, delete, modify data in your database
6 [Link] / Prof / SCORE / VIT
What is a [Link] File?
 [Link] files contain tasks that will be executed on certain events
 A typical event is someone trying to access a port on the server
 [Link] files must be initiated on the server before having any effect
 [Link] files have extension ".js"
 Download [Link]
 The official [Link] website has installation instructions for
[Link]: [Link]
 Check the installation by

7
[Link] / Prof / SCORE / VIT
[Link] HTTP Module
The Built-in HTTP Module
 [Link] has a built-in module called HTTP, which allows [Link]
to transfer data over the Hyper TextTransfer Protocol (HTTP).
 To include the HTTP module, use the require() method:
 var http = require('http');
[Link] as a Web Server
 The HTTP module can create an HTTP server that listens to
server ports and gives a response back to the client.
 Use the createServer() method to create an HTTP server.
 The function passed into the [Link]() method, will be
executed when someone tries to access the computer on port
8080.
8 [Link] / Prof / SCORE / VIT
Add an HTTP Header
 If the response from the HTTP server is supposed to be displayed as
HTML, you should include an HTTP header with the correct content
type.
 The first argument of the [Link]() method is the status code,
200 means that all is OK, the second argument is an object containing
the response headers.
Read the Query String
 The function passed into the [Link]() has a req argument
that represents the request from the client, as an object
([Link] object).
 This object has a property called "url" which holds the part of the url
that comes after the domain name:

9 [Link] / Prof / SCORE / VIT


C:\Users\admin\[Link]
var http = require('http');
[Link](function (req, res)
{
[Link](200,{'Content-Type':'text/html'});
[Link]('Hello vijayanYour Node JS Server is ready!');
}).listen(8080);

10 [Link] / Prof / SCORE / VIT


[Link] - explanation
 The basic functionality of the "require" function is that it reads
a JavaScript file, executes the file, and then proceeds to return an object.
Using this object, one can then use the various functionalities available in the
module called by the require function. So in our case, since we want to use
the functionality of http and we are using the require(http) command.
 In this 2nd line of code, we are creating a server application which is based
on a simple function. This function is called, whenever a request is made to
our server application.
 When a request is received, we are asking our function to return a 'Hello
vijayan Your Node JS Server is ready!' response to the client. The writeHead
function is used to send header data to the client and while the end function
will close the connection to the client.
 We are then using the [Link] function to make our server application
listen to client requests on port no 8080. You can specify any available port
[Link]
here./ Prof / SCORE / VIT
11
Executing the code
 Save the file on your computer: C:\Users\admin\[Link]
 In the command prompt, navigate to the folder where the file is stored.
Enter the command node [Link]
 Now, your computer works as a server! If anyone tries to access your
computer on port 8080, they will get a "Hello vijayan Your Node JS
Server is ready!" message in return!
 Start your internet browser, and type in the address:
[Link]

12 [Link] / Prof / SCORE / VIT


What are modules in [Link]?
 Consider modules to be the same as JavaScript libraries. A set of functions you
want to include in your application.
 Modules in Node js are a way of encapsulating code in a separate logical unit. There
are many readymade modules available in the market which can be used within
Node js.
 Below are some of the popular modules which are used in a Node js application
 Express framework – Express is a minimal and flexible Node js web application
framework that provides a robust set of features for the web
and Mobile applications.
 [Link] - [Link] enables real-time bidirectional event-based
[Link] module is good for creation of chatting based applications.
 Jade - Jade is a high-performance template engine and implemented
with JavaScript for node and browsers.
 MongoDB - The MongoDB [Link] driver is the officially supported [Link]
driver for MongoDB.
 Restify - restify is a lightweight framework, similar to express for building REST
APIs
 Bluebird - Bluebird is a fully featured promise library with focus on innovative
13 features and/ performance
[Link] Prof / SCORE / VIT
Procedure in Lab
 Save program in /home/mock3/[Link]
 Run in the command prompt like node [Link]
 Open the web browser and type localhost:8080/ you will get the
output.

14 [Link] / Prof / SCORE / VIT


C:\Users\admin\node_httpurl.js
var http = require('http');
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]([Link]);
[Link]();
}).listen(8080);

15 [Link] / Prof / SCORE / VIT


Initiate the node js server

Run the browser

Run the browser with adding contents in url

16 [Link] / Prof / SCORE / VIT


C:\Users\admin\node_httpurl_querystring.j
s Split the Query String
var http = require('http');
var url = require('url');
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
var q = [Link]([Link], true).query;
var txt = [Link] + " " + [Link];
var txt=[Link]+ " " +[Link]+ " " +[Link];
[Link](txt);
}).listen(8080);

There are built-in modules to easily split the query string into
readable parts, such as the URL module.
17 [Link] / Prof / SCORE / VIT
Initiate the node js server

Run the browser

Run the browser with adding query string by ? in url

18 [Link] / Prof / SCORE / VIT


C:\Users\admin\[Link]
[Link] = function () {
return Date(); Use the exports keyword to make
}; properties and methods available
outside the module file.
C:\Users\admin\node_datemodule.js
var http = require('http');
var dt = require('./datemodule');
[Link](function (req, res) {
[Link](200,{'Content-Type':'text/html'});
[Link](“Vijayan, The date and time are currently: " +
[Link]());
[Link]();}).listen(8080);
19 [Link] / Prof / SCORE / VIT
20 [Link] / Prof / SCORE / VIT
[Link] File System Module
 The [Link] file system module allows you to work with the file
system on your computer.
 To include the File System module, use the require() method:
var fs = require('fs');
 Common use for the File System module: Read files,Create files,
Update files, Delete files and Rename files.
 The [Link]() method is used to read files on your computer.
 The File System module has methods for creating new/update files:
[Link](),[Link](),[Link]()
 To delete a file with the File System module, use [Link]() method.

21 [Link] / Prof / SCORE / VIT


C:\Users\admin\[Link]
<html>
<body>
<h1> My First Page</h1>
<p> Hi, everybody.....<br>I am Vijayan </p>
</body>
</html>

22 [Link] / Prof / SCORE / VIT


C:\Users\admin\node_readfile.js
var http = require('http');
var fs = require('fs');
[Link](function (req, res)
{
[Link]('[Link]', function(err, data) {
[Link](200, {'Content-Type': 'text/html'});
[Link](data);
[Link]();
});}).listen(8080);

23 [Link] / Prof / SCORE / VIT


Initiate node_readfile.js

Run in browser

24 [Link] / Prof / SCORE / VIT


[Link] NPM
 NPM is a package manager for [Link] packages, or modules if you
like. Modules are JavaScript libraries you can include in your project.
 [Link] hosts thousands of free packages to download and
use.
 The NPM program is installed on your computer when you install
[Link]
Download a Package
 Open the command line interface and tell NPM to download the
package you want.

 NPM creates a folder named "node_modules", where the package will


be placed. All packages you install in the future will be placed in this
folder.
25 [Link] / Prof / SCORE / VIT
Using a Package
var http = require('http');
var uc = require('upper-case');
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]([Link]("Hello Vijayan!"));
[Link]();
}).listen(8080);

26 [Link] / Prof / SCORE / VIT


27 [Link] / Prof / SCORE / VIT
Node JS - Events
 [Link] is perfect for event-driven applications.
 Every action on a computer is an event. Like when a connection is made or a
file is opened.
 Objects in [Link] can fire events, like the readStream object fires events
when opening and closing a file.

C:\Users\admin\node_event_fileopen.js
var fs = require('fs');
var readStream = [Link]('./[Link]');
[Link]('open', function () {
[Link]('The file is open');});

28 [Link] / Prof / SCORE / VIT


Event-Driven Programming
 [Link] uses events heavily and it is also one of the reasons why
[Link] is pretty fast compared to other similar technologies. As soon
as Node starts its server, it simply initiates its variables, declares
functions and then simply waits for the event to occur.
 In an event-driven application, there is generally a main loop that
listens for events, and then triggers a callback function when one of
those events is detected.

29 [Link] / Prof / SCORE / VIT


What and Why event emitter?
 Put simply, it allows you to listen for "events" and assign actions
to run when those events occur. If you're familiar with front-end
JavaScript, you'll know about mouse and keyboard events that
occur on certain user interactions. These are very similar, except
that we can emit events on our own, when we want to, and not
necessary based on user interaction.
 The principles EventEmitter is based on have been called the
publish/subscribe model, because we can subscribe to events and
then publish them. There are many front-end libraries built with
pub/sub support, but Node has it build in.

30 [Link] / Prof / SCORE / VIT


 [Link] has a built-in module, called "Events", where you can create-, fire-, and
listen for- your own events.
 All event properties and methods are an instance of an EventEmitter
object.
 You can assign event handlers to your own events with the EventEmitter
[Link] fire an event, use the emit() method.
var events = require("events");
var myEmitter=new [Link]();
[Link]("someEvent", function () {
[Link]("event has occured"); });
[Link]("someEvent");

31 [Link] / Prof / SCORE / VIT


 // Import events module
var events = require('events');

 Create an eventEmitter object


var eventEmitter = new [Link]();

 Bind event and event handler as follows


[Link]('eventName', eventHandler);

 // Fire an event
[Link]('eventName');

32 [Link] / Prof / SCORE / VIT


EventEmitter properties and methods
Method Description
addListener(event,
Adds the specified listener
listener)
Sets the maximum number of listeners allowed for
defaultMaxListeners
one event. Default is 10
emit(event, [arg1], Call all the listeners registered with the specified
[arg2], [...]) name
eventNames() Returns an array containing all registered events
Returns the maximum number of listeners allowed
getMaxListeners()
for one event
listenerCount(emitter, Returns the number of listeners with the specified
event) name
listeners(event) Returns an array of listeners with the specified name
on(event, listener) Adds the specified listener
Adds the specified listener once. When the specified
33 once()
listener has been executed, the listener is removed
[Link] / Prof / SCORE / VIT
EventEmitter properties and methods
Adds the specified listener as the first event with the
prependListener()
specified name

Adds the specified listener as the first event with the


prependOnceListener() specified name, once. When the specified listener has
been executed, the listener is removed

Removes all listeners with the specified name, or ALL


removeAllListeners([event])
listeners if no name is specified

Removes the specified listener with the specified


removeListener(event, listener)
name

Sets the maximum number of listeners allowed for


setMaxListeners(n)
one event. Default is 10
34 [Link] / Prof / SCORE / VIT
util module
 The util module is primarily designed to support the needs of
[Link]' own internal APIs.
 However, many of the utilities are useful for application and
module developers as well.
 [Link](constructor, superConstructor)
 Inherit the prototype methods from one constructor into another.
The prototype of constructor will be set to a new object created
fromsuperConstructor.

35 [Link] / Prof / SCORE / VIT


var events=require('events');
var util=require('util');
var person=function(name){[Link]=name;};
[Link](person,[Link]);
var vijay=new person(‘vijay');
var raja=new person('raja');
var shri=new person('shri');
var people=[vijay,raja,shri];
[Link](function(person){
[Link]('speak',function(msg) {
[Link]([Link]+' said: '+msg);});});
[Link]('speak','hai students');
[Link]('speak','hello friends');

36 [Link] / Prof / SCORE / VIT


[Link] VS Apache
1. It's fast
2. It can handle tons of concurrent requests
3. It's written in JavaScript (which means you can
use the same code server side and client side)

Platform Number of request per second

PHP ( via Apache) 3187,27


Static ( via Apache ) 2966,51
[Link] 5569,30

37 [Link] / Prof / SCORE / VIT


Callback
 Callback is an asynchronous equivalent for a function
 A callback function is called at the completion of a
given task.
 Node makes heavy use of callbacks.
 All the APIs of Node are written in such a way that
they support callbacks.

38 [Link] / Prof / SCORE / VIT


Callback
 For example, a function to read a file may start
reading file and return the control to the execution
environment immediately so that the next
instruction can be executed.
 Once file I/O is complete, it will call the callback
function while passing the callback function, the
content of the file as a parameter.
 So there is no blocking or wait for File I/O.
 This makes [Link] highly scalable, as it can
process a high number of requests without waiting
39
for any function to return results.
[Link] / Prof / SCORE / VIT
Blocking Code Example

var fs = require("fs");
var data = [Link]('[Link]');
[Link]([Link]()); [Link]("Program
Ended");

o/p:
 Welcome to [Link]
 Program Ended

40 [Link] / Prof / SCORE / VIT


Non-Blocking Code Example

var fs = require("fs");
[Link]('[Link]', function (err, data) { if (err) return
[Link](err); [Link]([Link]()); });
[Link]("Program Ended");

o/p:
 Program Ended
 Welcome to [Link]

41 [Link] / Prof / SCORE / VIT


Blocking and Non Blocking code
 These two examples explain the concept of
blocking and non-blocking calls.
 The first example shows that the program
blocks until it reads the file and then only it
proceeds to end the program.
 The second example shows that the program
does not wait for file reading and proceeds to
print "Program Ended" and at the same time,
the program without blocking continues
reading the file.

42 [Link] / Prof / SCORE / VIT


Blocking and Non Blocking code
 Thus a blocking program executes very much in
sequence.
 From the programming point of view, it is easier to
implement the logic but non-blocking programs do
not execute in sequence.
 In case a program needs to use any data to be
processed, it should be kept within the same block
to make it sequential execution.

43 [Link] / Prof / SCORE / VIT


Conclusion
 [Link] faster than apache but it more
hungry system’s CPU and memory

 [Link] use event based programming, it


make the server doesn’t wait for the IO
operation to complete while it can handle
other request at the same time
 Ref: [Link]
i-use-node-js

44 [Link] / Prof / SCORE / VIT


45 [Link] / Prof / SCORE / VIT
 step 1: npm install express --save
 Express allows us to set up middlewares to respond to HTTP
Requests
 step 2: npm install body-parser --save
 If you want to read HTTP POST data , you have to use the
“body-parser” node module.
 npm install mongoose --save
 Mongoose is an object document modeling (ODM) layer which
sits on the top of NodeJS MongoDB driver.
 How to run node appln
 node [Link]
 [Link]

46 [Link] / Prof / SCORE / VIT


File System
 Synchronous vs Asynchronous
 Every method in the fs module has synchronous as
well as asynchronous forms.
 Asynchronous methods take the last parameter as the
completion function callback and the first parameter of
the callback function as error.
 It is better to use an asynchronous method instead of a
synchronous method, as the former never blocks a
program during its execution, whereas the second one
does.

47 [Link] / Prof / SCORE / VIT


 Syntax for writing to a file
 [Link](filename, data[, options], callback)
 This method will over-write the file if the file already exists
Parameters
 Here is the description of the parameters used −
 path − This is the string having the file name including path.
 data − This is the String or Buffer to be written into the file.
 options − The third parameter is an object which will hold
encoding.
 callback − This is the callback function which gets a single
parameter err that returns an error in case of any writing error.

48 [Link] / Prof / SCORE / VIT


Reading from a file
 [Link](fd, buffer, offset, length, position, callback)
 This method will use file descriptor to read the file. If you want to read the file
directly using the file name, then you should use another method available.
 Parameters
 Here is the description of the parameters used −
 fd − This is the file descriptor returned by [Link]().
 buffer − This is the buffer that the data will be written to.
 offset − This is the offset in the buffer to start writing at.
 length − This is an integer specifying the number of bytes to read.
 position − This is an integer specifying where to begin reading from in the
file. If position is null, data will be read from the current file position.
 callback − This is the callback function which gets the three arguments, (err,
bytesRead, buffer).

49 [Link] / Prof / SCORE / VIT


File System
 Ex: [Link]
 [Link]
 [Link]

50 [Link] / Prof / SCORE / VIT


Truncate a File
 The syntax of the method to truncate an opened file −

 [Link](fd, len, callback)

 the description of the parameters used −

 fd − This is the file descriptor returned by [Link]().

 len − This is the length of the file after which the file
will be truncated.

 callback − This is the callback function.

51 [Link] / Prof / SCORE / VIT


setTimeout(cb, ms)

 The setTimeout(cb, ms) global function is used to


run callback cb after at least ms milliseconds.

 The actual delay depends on external factors like


OS timer granularity and system load.

 A timer cannot span more than 24.8 days.

 Ex: [Link]

52 [Link] / Prof / SCORE / VIT


clearTimeout(t)

 The clearTimeout(t) global function is used to


stop a timer that was previously created with
setTimeout().
 t is a timer which is cleared.

 Ex: [Link]

53 [Link] / Prof / SCORE / VIT


Buffer

54 [Link] / Prof / SCORE / VIT


Stream

 In buffer,it collects all the chunks of data and when the buffer
is full ,it passes the chunk of data down the stream to be
processed and sends to client.

55 [Link] / Prof / SCORE / VIT


streams

56 [Link] / Prof / SCORE / VIT


 Writeable streams (when a response is received it is writing
the data to the stream and client receives it)
 Readable streams(whenever we request data to the server, it
will be reading the data coming from the stream)
 Duplex streams
[Link]

57 [Link] / Prof / SCORE / VIT


Streams
 Each type of Stream is an EventEmitter instance and throws
several events at different instance of times.

 For example, some of the commonly used events are −

 data − This event is fired when there is data is available to


read.

 end − This event is fired when there is no more data to read.

 error − This event is fired when there is any error receiving or


writing data.

58 [Link] / Prof / SCORE / VIT


Piping the Streams

 Piping is a mechanism where we provide the


output of one stream as the input to another stream.

 It is normally used to get data from one stream and


to pass the output of that stream to another stream.

 There is no limit on piping operations

 Ex: [Link]

59 [Link] / Prof / SCORE / VIT


Chaining the Streams

 Chaining is a mechanism to connect the output of


one stream to another stream and create a chain of
multiple stream operations.

 It is normally used with piping operations.

 Use piping and chaining to first compress a file


and then decompress the same.

 Ex: [Link] , [Link]

60 [Link] / Prof / SCORE / VIT


Buffer
 Whenever we receive a file or data from some stream, that data
cannot be used natively in javascript, so make it consumable, the
raw data is converted into usable format and for that we use the
buffer data.
 Node Buffer can be constructed in a variety of ways.
 Method 1
 Following is the syntax to create an uninitiated Buffer of size
10
 var buf = new Buffer(10);
 Method 2
 Following is the syntax to create a Buffer from a given array −
 var buf = new Buffer([10, 20, 30, 40, 50]);

61 [Link] / Prof / SCORE / VIT


Buffer
 Following is the syntax to create a Buffer with
optionally encoding type −

 var buf = new Buffer("Simply Easy Learning",


"utf-8");

 Though "utf8" is the default encoding, you can use


any of the following encodings "ascii", "utf8",
"utf16le", "ucs2", "base64" or "hex".

62 [Link] / Prof / SCORE / VIT


Writing to Buffers

 Following is the syntax of the method to write into a Node Buffer −


 [Link](string[, offset][, length][, encoding])
 the description of the parameters used −
 string − This is the string data to be written to buffer.
 offset − This is the index of the buffer to start writing at. Default value
is 0.
 length − This is the number of bytes to write. Defaults to
[Link].
 encoding − Encoding to use. 'utf8' is the default encoding.
 Return Value
 This method returns the number of octets written. If there is not
enough space in the buffer to fit the entire string, it will write a part of
the string.

63 [Link] / Prof / SCORE / VIT


Example of Buffer
 buf = new Buffer(256);
 len = [Link]("Simply Easy Learning");
 [Link]("Octets written : "+ len);

64 [Link] / Prof / SCORE / VIT


Reading from Buffers

 [Link]([encoding][, start][, end])


 the description of the parameters used −
 encoding − Encoding to use. 'utf8' is the default encoding.
 start − Beginning index to start reading, defaults to 0.
 end − End index to end reading, defaults is complete
buffer.
 Return Value
 This method decodes and returns a string from buffer data
encoded using the specified character set encoding.
 [Link]

65 [Link] / Prof / SCORE / VIT


Example of Buffer program
 buf = new Buffer(26);
 for (var i = 0 ; i < 26 ; i++)
 { buf[i] = i + 97; }

 [Link]( [Link]('ascii'));
 // outputs: abcdefghijklmnopqrstuvwxyz

 [Link]( [Link]('ascii',0,5));
 // outputs: abcde
 [Link]( [Link]('utf8',0,5));
 // outputs: abcde
 [Link]( [Link](undefined,0,5));
66 // encoding
 [Link] defaults
/ Prof / SCORE / VIT to 'utf8', outputs abcde
Convert Buffer to JSON

 [Link]()

 var buf = new Buffer('Simply Easy Learning');


 var json = [Link](buf);
 [Link](json);

 o/p: [ 83, 105, 109, 112, 108, 121, 32, 69, 97, 115,
121, 32, 76, 101, 97, 114, 110, 105, 110, 103 ]

67 [Link] / Prof / SCORE / VIT


Concatenate Buffers

 [Link](list[, totalLength])

 list − Array List of Buffer objects to be


concatenated.

 totalLength − This is the total length of the


buffers when concatenated.

 This method returns a Buffer instance.

68 [Link] / Prof / SCORE / VIT


Concatenate Buffers

 var buffer1 = new Buffer(‘Node js ');


 var buffer2 = new Buffer('Simply Easy Learning');
 var buffer3 = [Link]([buffer1,buffer2]);

 [Link]("buffer3 content: " +


[Link]());

 o/p:
 buffer3 content: Node js Simply Easy Learning

69 [Link] / Prof / SCORE / VIT


Copy Buffer

 [Link](targetBuffer[, targetStart][, sourceStart][, sourceEnd])

 Here is the description of the parameters used −

 targetBuffer − Buffer object where buffer will be copied.


 targetStart − Number, Optional, Default: 0
 sourceStart − Number, Optional, Default: 0
 sourceEnd − Number, Optional, Default: [Link]

 No return value.
 Copies data from a region of this buffer to a region in the
target buffer even if the target memory region overlaps with
the source.

70 [Link] / Prof / SCORE / VIT


Copy Buffer

 var buffer1 = new Buffer('ABC');


 //copy a buffer
 var buffer2 = new Buffer(3);
[Link](buffer2);
 [Link]("buffer2 content: " +
[Link]());

 O/P: buffer2 content: ABC

71 [Link] / Prof / SCORE / VIT


Slice Buffer
 to get a sub-buffer of a node buffer −
 [Link]([start][, end])
 the description of the parameters used −
 start − Number, Optional, Default: 0
 end − Number, Optional, Default: [Link]
 Returns a new buffer which references the same
memory as the old one, but offset and cropped by
the start (defaults to 0) and end (defaults to
[Link]) indexes
 [Link]

72 [Link] / Prof / SCORE / VIT


Example of Slicing Buffer

 var buffer1 = new Buffer(‘WelcometoNodejs');


//slicing a buffer
 var buffer2 = [Link](0,6);
 [Link]("buffer2 content: " +
[Link]());

 o/p: Welcome

73 [Link] / Prof / SCORE / VIT


Buffer Length
 to get a size of a node buffer in bytes −
 [Link];
 Returns the size of a buffer in bytes.
 Ex:
 var buffer = new Buffer(‘WelcometoNodejs');
 //length of the buffer
 [Link]("buffer length: " + [Link]);

 o/p:

74
 buffer length : 15
[Link] / Prof / SCORE / VIT
extends keyword instead of inherits
var EventEmitter = require('events');
class MyStream extends EventEmitter {
write(data) {
[Link]('data', data); }}
stream = new MyStream();
[Link]('data', (data) => {
[Link](`Received data: "${data}"`);
});
[Link]('From Mareeswari');

75 [Link] / Prof / SCORE / VIT


Express JS
Express JS
 [Link] is an amazing tool for building networking services and
applications.
 Express is a [Link] Web Framework. ExpressJS is a web application
framework that provides you with a simple API to build websites, web
apps and back ends.
 It is flexible as there are numerous modules available on npm, which
can be directly plugged into Express.
 Express was developed by TJ Holowaychuk and is maintained by
the [Link] foundation and numerous open source contributors.
 Express is a minimal and flexible [Link] web application framework
that provides a robust set of features for web and mobile applications. It
is an open source framework developed and maintained by the [Link]
foundation.

R Vijayamn/Prof / SCORE / VIT


Express framework:
 Core features of Express framework
 It can be used to design single-page, multi-page and hybrid web
applications.
 It allows to setup middlewares to respond to HTTP Requests.
 It defines a routing table which is used to perform different actions
based on HTTP method and URL.
 It allows to dynamically render HTML Pages based on passing
arguments to templates.
 Why use Express
 Ultra fast I/O
 Asynchronous and single threaded
 MVC like structure
 Robust API makes routing easy

R Vijayamn/Prof / SCORE / VIT


 npm install --save express
 To make our development process a lot easier, we will install a
tool from npm, nodemon.
 nodemon This tool restarts our server as soon as we make a
change in any of our files, otherwise we need to restart the server
manually after each file modification. To install nodemon, use the
following command −
 npm install -g nodemon

R Vijayamn/Prof / SCORE / VIT


C:\Users\admin\node_express1.js
const express = require('express')
const app = express()
[Link]('/', function(req, res){ [Link]('Hello Vijayan!')})
[Link](3000, function(){ [Link](‘Your Express Server is ready')})

R Vijayamn/Prof / SCORE / VIT


 [Link](route, callback)
 This function tells what to do when a get request at the given route is
called.
 The callback function has 2 parameters, request(req) and response(res).
 The request object(req) represents the HTTP request and has properties
for the request query string, parameters, body, HTTP headers, etc.
 the response object represents the HTTP response that the Express app
sends when it receives an HTTP request.
 [Link]()
 This function takes an object as input and it sends this to the requesting
client. Here we are sending the string "HelloWorld!".
 [Link](port, [host], [backlog], [callback]])
 This function binds and listens for connections on the specified host and
port. Port is the only required parameter here
 BacklogThe maximum number of queued pending connections. The
default is 511.
R Vijayamn/Prof / SCORE / VIT
Explanation
 First, we import the express package to the express value.
 We instantiate an application by calling its app() method. [Link](route, callback)
 Once we have the application object, we tell it to listen for GET requests on the /path,
using the get() method.
 There is a method for every HTTP verb: get(), post(), put(), delete(), patch().
 Those methods accept a callback function, which is called when a request is started, and we
need to handle it. An asynchronous function that is called when the server starts listening
for requests.
 Express sends us two objects in this callback, which we called req and res, that represent
the Request and the Response objects.
 Request is the HTTP request. It can give us all the info about that, including the request
parameters, the headers, the body of the request, and [Link] is the HTTP response
object that we’ll send to the client.
 What we do in this callback is to send the ‘Hello World!’ string to the client, using
the [Link]() method. This method sets that string as the body, and it closes the
connection.
 The last line of the/ SCORE
R Vijayamn/Prof example
/ VITactually starts the server, and tells it to listen on port 3000. We
pass in a callback that is called when the server is ready to accept new requests.
Node express_basics.js
var express = require('express');
var app = express();
[Link]('/', function (req, res) {
[Link]('Welcome to JavaTpoint!');
});
var server = [Link](8000, function () {
var host = [Link]().address;
var port = [Link]().port;
[Link]('Example app listening at [Link] host, port);
});

R Vijayamn/Prof / SCORE / VIT


Express routing
[Link](path, handler)
 Method get(), post() and all()
 Eg-
var express = require('express');
var app = express();
[Link]('/hello', function(req, res){ [Link]("Hello World!"); });
[Link]('/hello', function(req, res){
[Link]("You just called the post method at '/hello'!\n"); });
[Link](3000);
 A special method, all, is provided by Express to handle all types of http
methods at a particular route using the same function
 Eg-
[Link]('/test', function(req, res){
[Link]("HTTP method doesn't have any effect on this
route!"); });
R Vijayamn/Prof / SCORE / VIT
Express - Routers
 To separate the routes from our main [Link] file, we will
use [Link].
 Create a new file called [Link] and type the following in it.
var express = require('express');
var router = [Link]();
[Link]('/', function(req, res){ [Link]('GET route on things.');
});
[Link]('/', function(req, res){ [Link]('POST route on
things.'); });
//export this router to use in our [Link]
[Link] = router;
R Vijayamn/Prof / SCORE / VIT
Express - Routers
 Now to use this router in our [Link], type in the following before
the [Link] function call.
var express = require('Express');
var app = express();
var things = require('./[Link]');
//both [Link] and [Link] should be in same directory
[Link]('/things', things);
[Link](3000);

 The [Link] function call on route '/things' attaches the things router
with this route.
 Now whatever requests our app gets at the '/things', will be handled by
our [Link] router.
 The '/' route in [Link] is actually a subroute of '/things'. Visit
localhost:3000/things/
R Vijayamn/Prof / SCORE / VIT
[Link] Request Object - req
 The [Link] request object represents the HTTP request
and has properties for the request query string, parameters,
body, HTTP headers, and so on.
[Link]('/', function (req, res) {
// --
})

R Vijayamn/Prof / SCORE / VIT


Property REQUEST OBJECT PROPERTIES
Description
.app holds a reference to the Express app object
.baseUrl the base path on which the app responds
contains the data submitted in the request body (must be parsed and populated manually
.body
before you can access it)
.cookies contains the cookies sent by the request (needs the cookie-parser middleware)
.hostname the server hostname
.ip the server IP
.method the HTTP method used
.params the route named parameters
.path the URL path
.protocol the request protocol
.query an object containing all the query strings used in the request
.secure true if the request is secure (uses HTTPS)
.signedCookies contains the signed cookies sent by the request (needs the cookie-parser middleware)
.xhr true if the request is an XMLHttpRequest
R Vijayamn/Prof / SCORE / VIT
.route The currently-matched route, a string.
Express Request object methods
 [Link] (types)
 This method is used to check whether the specified content types are
acceptable, based on the request's Accept HTTP header field.
 [Link]('html'); //=>?html?
 [Link]('text/html'); // => ?text/html?
 [Link](field)
 This method returns the specified HTTP request header field.
 [Link](type)
 This method returns true if the incoming request's "Content-Type" HTTP
header field matches the MIME type specified by the type parameter.
 [Link]('html');
 [Link]('text/html');
 [Link]('text/*');
 [Link](name [, defaultValue])
 This method is used to fetch the value of param name when present.
 [Link]('name') // ?name=sasha
R Vijayamn/Prof / SCORE / VIT
Express Response object -res
 The Response object (res) specifies the HTTP response
which is sent by an Express app when it gets an HTTP
request.
 What it does
 It sends response back to the client browser.
 It facilitates you to put new cookies value and that will write to
the client browser (under cross domain rule).
 Once you [Link]() or [Link]() or [Link](), you
cannot do it again, otherwise, there will be uncaught error.

R Vijayamn/Prof / SCORE / VIT


Response Object Properties and methods

 [Link](field [, value]) This method appends the specified value to the


HTTP response header field.
 Eg
[Link]('Link', ['<[Link] '<[Link]
[Link]('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
 [Link]([filename]) This method is used to send a file as an
attachment in the HTTP response.
 examples −
[Link]('path/to/[Link]'); [Link](name, value [, options])

R Vijayamn/Prof / SCORE / VIT


Response Object methods
 [Link](name, value [, options]) This method is used to set
cookie name to value. The value parameter may be a string or object
converted to JSON.
 Eg. −
[Link]('name', 'tobi', { domain: '.[Link]', path: '/admin', secure:
true }); [Link]('cart', { items: [1,2,3] });
[Link]('cart', { items: [1,2,3] }, { maxAge: 900000 });
 [Link](name [, options]) This method is used to clear the
cookie specified by name. Following are a few examples −
 [Link]('name', 'tobi', { path: '/admin' }); [Link]('name', {
path: '/admin' });

R Vijayamn/Prof / SCORE / VIT


Response Object methods
 [Link](path [, filename] [, fn]) This method is used to transfer the
file at path as an "attachment". Typically, browsers will prompt the user for
download. Following are a few examples −
 [Link]('/[Link]');
 [Link]('/[Link]', '[Link]');
 [Link]([data] [, encoding])This method is used to end the response
process. Following are a few examples −
 [Link](); [Link](404).end();
 [Link](field) This method is used to return the HTTP response header
specified by field. Here is an examples −
 [Link]('Content-Type');
 [Link]([body]) This method is used to send a JSON response. Following
are a few examples −
 [Link](null)
 [Link]({ user: 'tobi' })
 [Link](500).json({ error: 'message' })
R Vijayamn/Prof / SCORE / VIT
Response Object methods
 [Link](links)This method is used to join the links provided as
properties of the parameter to populate the response’s Link HTTP
header field. Following are a few examples −
 [Link] ({ next: '[Link]
last: '[Link] });
 [Link](path) This method is used to set the response Location
HTTP header field based on the specified path parameter. Following
are a few examples −
 [Link]('/foo/bar');
[Link]('foo/bar'); [Link]('[Link]
 [Link]([status,] path) This method is used to redirect to the
URL dervied from the specified path, with specified HTTP status
code status. Following are a few examples −
 [Link]('/foo/bar'); [Link]('[Link]
[Link](301, '[Link]
R Vijayamn/Prof / SCORE / VIT
Response Object methods
 [Link]([body]) This method is used to send the HTTP response.
Following are a few examples −
 [Link](new Buffer('whoop')); [Link]({ some: 'json' });
[Link]('<p>some html</p>');[Link](path [, options] [, fn])
 [Link](path [, options] [, fn]) This method is used to transfer
the file at the given path. Sets the Content-Type response HTTP
header field based on the filename’s extension. Here is an example −
 [Link](fileName, options, function (err) { // ... });
 [Link](statusCode)This method is used to set the response
HTTP status code to statusCode and send its string representation as
the response body. Following are a few examples −
 [Link](200); // equivalent to [Link](200).send('OK')
[Link](403); // equivalent to [Link](403).send('Forbidden')

R Vijayamn/Prof / SCORE / VIT


Response Object methods
 [Link](field [, value]) This method is used to set the response’s HTTP
header field to value. Following are a few examples −
 [Link]('Content-Type', 'text/plain');
 [Link] ({ 'Content-Type': 'text/plain', 'Content-Length': '123', 'ETag':
'12345' })
 [Link](code)This method is used to set the HTTP status for the
response. Following are a few examples −
 [Link](403).end(); [Link](400).send('Bad Request');
[Link](404).sendFile('/absolute/path/to/[Link]');
 [Link](type) This method is used to set the Content-Type HTTP
header to the MIME type. Following are a few examples −
 [Link]('.html'); // => 'text/html' [Link]('html'); // => 'text/html'
[Link]('json'); // => 'application/json' [Link]('application/json'); //
=> 'application/json' [Link]('png'); // => image/png:

R Vijayamn/Prof / SCORE / VIT


Express GET request
 Fetch data in JSON format:
[Link]('/process_get', function (req, res) {
response = {
first_name:[Link].first_name,
last_name:[Link].last_name
};
[Link](response);
[Link]([Link](response));
})
 Fetch data in paragraph format
[Link]('/get_example2', function (req, res) {
[Link]('<p>Username: ' + [Link]['first_name']+'</p><p>Lastname
: '+[Link]['last_name']+'</p>');
})

R Vijayamn/Prof / SCORE / VIT


Express POST request
 we will first install the body-parser(for parsing JSON and url-encoded
data) and multer(for parsing multipart/form data) middleware.
 This body-parser module parses the JSON, buffer, string and
URL encoded data submitted using HTTP POST request.
 body-parser extract the entire body portion of an incoming
request stream and exposes it on [Link].

 To install the body-parser and multer, go to your terminal and use


 npm install --save body-parser multer

 After importing the body parser and multer, we will use


 the body-parser for parsing json and x-www-form-urlencoded
header requests,
 multer for parsing multipart/form-data.

R Vijayamn/Prof / SCORE / VIT


body-parser
 The bodyParser object exposes various factories to create
middlewares.(npm install body-parser)
 All middlewares will populate the [Link] property with the parsed
body when the Content-Type request header matches the type option,
or an empty object ({}) if there was no body to parse, the Content-
Type was not matched, or an error occurred.
 [Link]([options])Returns middleware that only
parses json
 [Link]([options])Returns middleware that parses all
bodies as a string.
 [Link]([options])Returns middleware that
only parses urlencoded bodies
 extended option allows to choose between parsing the URL-encoded
data with the querystring library (when false) or the qs library
(when true).
 The “extended” syntax allows for rich objects and arrays to be encoded into
the URL-encoded format, allowing for a JSON-like experience with URL-
encoded
R Vijayamn/Prof / SCORE / VIT
C:\Users\admin\node_express_form.js
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = [Link]({ extended: true });
// Running Server Details.
var server = [Link](8080, function () {
var host = [Link]().address
var port = [Link]().port
[Link]("Example app listening at %s:%s Port", host, port)});

R Vijayamn/Prof / SCORE / VIT


[Link]('/form', function (req, res) {
var html='';
html +="<body>";
html += "<form action='/thank' method='post' name='form1'>";
html += "Name:</p><input type= 'text' name='name'>";
html += "Email:</p><input type='text' name='email'>";
html += "address:</p><input type='text' name='address'>";
html += "Mobile number:</p><input type='text'
name='mobilno'>";
html += "<input type='submit' value='submit'>";
html += "<INPUT type='reset' value='reset'>";
html += "</form>";
html += "</body>";
[Link](html);});
R Vijayamn/Prof / SCORE / VIT
[Link]('/thank', urlencodedParser, function (req, res){
var reply='';
reply += "Your name is" + [Link];
reply += "Your E-mail id is" + [Link];
reply += "Your address is" + [Link];
reply += "Your mobile number is" + [Link];
[Link](reply); }); // response to the client browser window

R Vijayamn/Prof / SCORE / VIT


R Vijayamn/Prof / SCORE / VIT
Technologies\ITE1002\Programs\Node
JS\[Link]

 <html>
 <body>
 <h1>Hello</h1>
 <form action="/name" method="GET">
 <input type="text" name="t1">
 <button>SEND</button>
 </form>
 <form action="/add" method="GET">
 <input type="text" name="num1">
 <input type="text" name="num2">
 <button>ADD</button>
 </form>
 </body>
 </html>

R Vijayamn/Prof / SCORE / VIT


let express = require('express')
let server = express()
let path=require('path')
[Link]('/add', (req, res) => {
let n1=parseInt([Link].num1); let n2=parseInt([Link].num2);
let result=n1+n2; [Link]('Addition:'+result);});
[Link]('/home',(req,res)=>{
[Link]([Link](__dirname,'[Link]'))})
[Link](3000);
[Link]("Server is ready");

R Vijayamn/Prof / SCORE / VIT


In Visual Code

F:\Academic\Web Technologies\ITE1002\Programs\Node JS\[Link]


let express = require('express')
let app = express()
[Link]('/add', (req, res) =>
{ Run node [Link] in
let n1=parseInt([Link].num1); Terminal
let n2=parseInt([Link].num2); [Link]
let result=n1+n2; /add?num1=100&nu
[Link]('Addition:'+result); m2=20 in chrome
});
[Link](3000);

R Vijayamn/Prof / SCORE / VIT


R Vijayamn/Prof / SCORE / VIT
Handling Cookie
 Cookies are simple, small files/data that are sent to client with a
server request and stored on the client side. Every time the user
loads the website back, this cookie is sent with the request. This
helps us keep track of the user’s actions.
 The following are the numerous uses of the HTTP Cookies −
 Session management
 Personalization(Recommendation systems)
 User tracking
 To use cookies with Express, we need the cookie-parser middleware.
To install it, use the following code −
 npm install --save cookie-parser

R Vijayamn/Prof / SCORE / VIT


How does a Cookie work?

No Yes ->Updates
cookie value
No -> Creates new
cookie

R Vijayamn/Prof / SCORE / VIT


 Now to use cookies with Express, we will require the cookie-parser.
cookie-parser is a middleware which parses cookies attached to the client
request object. To use it, we will require it in our [Link] file; this can
be used the same way as we use other middleware. Here, we will use
the following code.
var cookieParser = require('cookie-parser');
[Link](cookieParser());
 cookie-parser parses Cookie header and populates [Link] with
an object keyed by the cookie names. To set a new cookie, let us define
a new route in your Express app like −
var express = require('express');
var app = express();
[Link]('/', function(req, res){
[Link]('name', 'express').send('cookie set'); //Sets name =express
}); [Link](3000);
R Vijayamn/Prof / SCORE / VIT
 To check if your cookie is set or not, just go to your browser, fire up
the console, and enter −
[Link]([Link]);
 You will get the output like (you may have more cookies set maybe
due to extensions in your browser) −
"name = express"
 The browser also sends back cookies every time it queries the server.
To view cookies from your server, on the server console in a route,
add the following code to that route.
[Link]('Cookies: ', [Link]);
 Next time you send a request to this route, you will receive the
following output.
Cookies: { name: 'express' }

R Vijayamn/Prof / SCORE / VIT


Adding Cookies with Expiration Time
 You can add cookies that expire. To add a cookie that expires, just pass
an object with property 'expire' set to the time when you want it to
expire. For example,
 //Expires after 360000 ms from the time it is set.
[Link](name, 'value', {expire: 360000 + [Link]()});
 Another way to set expiration time is using 'maxAge' property.
Using this property, we can provide relative time instead of absolute
time. Following is an example of this method.
 //This cookie also expires after 360000 ms from the time it is set.
[Link](name, 'value', {maxAge: 360000});

R Vijayamn/Prof / SCORE / VIT


Deleting Existing Cookies
 To delete a cookie, use the clearCookie function. For example, if you
need to clear a cookie named foo, use the following code.
var express = require('express');
var app = express();
[Link]('/clear_cookie_foo', function(req, res){
[Link]('foo');
[Link]('cookie foo cleared'); });
[Link](3000);

R Vijayamn/Prof / SCORE / VIT


C:\Users\admin\node_cookie_express.js
var express = require('express')
// npm install cookie-parser
var cookieParser = require('cookie-parser')
var app = express();
// need cookieParser middleware before we can do anything with
cookies
[Link](cookieParser());
// set a cookie
[Link](function (req, res, next) {
// check if client sent cookie
var cookie = [Link]; // RETRIEVE THE COOKIES
R Vijayamn/Prof / SCORE / VIT
if (cookie === undefined) {// no: set a new cookie
var randomNumber=[Link]().toString();
randomNumber=[Link](2,[Link]);
[Link]('cookieName',randomNumber, { maxAge: 900000, httpOnly:
true });
[Link]('cookie created successfully');
} else
{ // yes, cookie was already present
[Link]('cookie exists', cookie);
}next(); }); // <-- important!
[Link]('/', function(req, res) {
[Link]([Link]([Link]));
}) [Link](8081)
R Vijayamn/Prof / SCORE / VIT
Install cookie-parser, running server and
running client

R Vijayamn/Prof / SCORE / VIT


Sessions
 Cookies are both readable and on the client side.
 Sessions solve exactly this problem.
 assign the client an ID and it makes all further requests using that
ID. Information associated with the client is stored on the server
linked to this ID.
 need the Express-session, so install it using the following code.
npm install --save express-session
 put the session middleware handles all things for us, i.e.,
 creating the session,
 setting the session cookie and
 creating the session object in req object.

R Vijayamn/Prof / SCORE / VIT


var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var app = express();
[Link](cookieParser());
[Link](session({secret: "Shh, its a secret!"}));
[Link]('/', function(req, res){
if([Link].page_views){
[Link].page_views++;
[Link]("You visited this page " + [Link].page_views + " times");
} else {
[Link].page_views = 1;
[Link]("Welcome to this page for the first time!");
}
});[Link](3000);

R Vijayamn/Prof / SCORE / VIT


Express-session options
const oneDay = 1000 * 60 * 60 * 24;
[Link](sessions({ secret: "thisismysecrctekeyfhrgfgrfrty84fwir767",
saveUninitialized:true, cookie: { maxAge: oneDay }, resave: false }));
 secret - a random unique string key used to authenticate a session. The
key is usually long and randomly generated in a production environment.
 resave - takes a Boolean value. It enables the session to be stored back to
the session store, even if the session was never modified during the
request. The default value is true. false is a better alternative.
 saveUninitialized - this allows any uninitialized session to be sent to the
store. When a session is created but not modified, it is referred to
as uninitialized.
 cookie: { maxAge: oneDay } - this sets the cookie expiry time. The
browser will delete the cookie after the set duration elapses.

R Vijayamn/Prof / SCORE / VIT


const express = require("express");
const session = require('express-session');
const app = express()
// Port Number Setup
var PORT = [Link] || 3000
// Session Setup
[Link](session({
// It holds the secret key for session
//secret: 'Your_Secret_Key',
secret:'343ji43j4n3jn4jk3n',
// Forces the session to be saved
// back to the session store
resave: true,
// Forces a session that is "uninitialized"
// to be saved to the store
saveUninitialized: true
}))

R Vijayamn/Prof / SCORE / VIT


[Link]("/", function(req, res){
// [Link] = value
[Link] = 'GeeksforGeeks'
return [Link]("Session Set")
})
[Link]("/session", function(req, res){
var name = [Link]
return [Link](name)

/* To destroy session you can use this function


[Link](function(error){
[Link]("Session Destroyed")
})*/

})
[Link](PORT, function(error){
if(error) throw error
[Link]("Server created Successfully on PORT :", PORT)
})

R Vijayamn/Prof / SCORE / VIT


Send mail using [Link], [Link] with Nodemailer
 The Nodemailer Modulemakes it easy to send emails from your
computer.
 The Nodemailer module can be downloaded and installed using
npm:
>npm install –save nodemailer
 Include the module
var nodemailer = require('nodemailer’);
 Nodemailer needs a transport service to send emails.

R Vijayamn/Prof / SCORE / VIT


Send mail using [Link], [Link] with Nodemailer
 Nodemailer needs a transport service to send emails.
var transporter = [Link]({
service: 'gmail',
auth: {
user: 'youremail@[Link]',
pass: 'yourpassword’ // app password
}});

// Create a reusable transporter object using SMTP transport.


const transporter = [Link]({
host: [Link].SMTP_HOST,
port: 587,
secure: false, // use false for STARTTLS; true for SSL on port 465
auth: {
user: [Link].SMTP_USER,
pass: [Link].SMTP_PASS }
});
R Vijayamn/Prof / SCORE / VIT
Send mail using [Link], [Link] with Nodemailer
 Configuration object where we will be configuring our email details.
const mailData = {
from: 'youremail@[Link]', // sender address
to: 'myfriend@[Link]', // list of receivers
subject: 'Sending Email using [Link]',
text: 'That was easy!’,
html: '<b>Hey there! </b><br> This is our first message sent with
Nodemailer<br/>’,
// An array of attachments
attachments: [
{
filename: 'text [Link]',
path: '[Link]
},
]};
R Vijayamn/Prof / SCORE / VIT
Send mail using [Link], [Link] with Nodemailer
 sending the email we can do that by using the sendMail method
provided by the transporter object we created above.

[Link](mailOptions, function (err, info) {


if(err)
[Link](err)
else
[Link](info);
});
 sendMail takes two argument mailOptions and a callback function
which will be called when the mail is sent. The callback function will be
called when either email sent successfully our an error occurred.

R Vijayamn/Prof / SCORE / VIT


Send mail using [Link], [Link] with Nodemailer
const express = require("express");
const nodemailer = require('nodemailer');
const app = express();
const port = [Link] || 5000;
var transporter = [Link]({
service:'gmail',
auth: { user:'[Link]@[Link]’, pass:’apppassword’ } });
var mailOptions = { from: '[Link]@[Link]',
to: 'rvijayan@[Link]',
subject: 'Sending Email using [Link]',
text: 'That was easy!’ };
[Link](mailOptions, function(error, info){
if (error) { [Link](error); } else { [Link]('Email sent: ' +
[Link]); }});
[Link](port, () => { [Link]('Server listening on port '+port);});

R Vijayamn/Prof / SCORE / VIT


File Upload
 To handle file upload using express-fileupload npm package,
npm install –save express-fileupload
 The express-fileupload is passed to the app as the middleware.
const fileUpload = require('express-fileupload’)
[Link](fileUpload())
 Then to access the uploaded files inside POST request using:
[Link]
 It provides functions and values such as file name, mime type, data, and
size.
 It provides an important mv() function which is used to save the uploaded
file. It takes the upload path and an error-handling function as parameters.
[Link](<upload_path>, function(err) {
// statement(s)
})
R Vijayamn/Prof / SCORE / VIT
const express = require("express");
const fileUpload = require("express-fileupload");
const app = express();
[Link](fileUpload());
[Link]("/upload", function (req, res) {
if ([Link] && [Link]([Link]).length !== 0) {
const uploadedFile = [Link];
[Link](uploadedFile);
const uploadPath = __dirname + "/upload/" + [Link];
// To save the file using mv() function
[Link](uploadPath, function (err) {
if (err) { [Link](err);[Link]("Failed !!");
} else [Link]("Successfully Uploaded !!");}); } else [Link]("No file
uploaded !!");});
[Link]("/", function (req, res) {
[Link](__dirname + "/[Link]");});
[Link](3000, function (req, res) {
[Link]("Started listening to port 3000");});
R Vijayamn/Prof / SCORE / VIT
const express = require('express');
const app = express();
[Link]('/', (req, res) =>
[Link]('Hello Vijayan!'));
[Link]('/display', function(req, res){
[Link]('Hello Vijayan123!')})
[Link]('/display1', function(req, res){
[Link]('Hello display1')})
[Link](3000, () =>
[Link]('Your Express Server is ready'));
var express = require('express');
var app = express();
[Link]('/', function (req, res) {
[Link]('Welcome to ExpressJS!');
});
[Link]('/test', function (req, res) {
[Link]('test');
});
[Link]('/test2', function (req, res) {
[Link]('test2');
});
var server = [Link](8000, function () {
var host = [Link]().address;
var port = [Link]().port;
[Link]('Example app listening at [Link] host, port);
});
var express = require('express');
var app = express();
[Link]('/hello', function(req, res){ [Link]("Hello World!"); });
[Link]('/hello1', function(req, res){
[Link]("You just called the post method at '/hello'!\n"); });

[Link]('/test', function(req, res){


[Link]("HTTP method doesn't have any effect on this route!"); });
[Link](3000);
var express = require('express');
var app = express();
[Link]('/', function (req, res) {
[Link]("Got a GET request for the homepage");
[Link]('Welcome to JavaTpoint!');
})
[Link]('/', function (req, res) {
[Link]("Got a POST request for the homepage");
[Link]('I am Impossible! ');
})
[Link]('/del_student', function (req, res) {
[Link]("Got a DELETE request for /del_student");
[Link]('I am Deleted!');
})
[Link]('/enrolled_student', function (req, res) {
[Link]("Got a GET request for /enrolled_student");
[Link]('I am an enrolled student.');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
[Link]('/ab*cd', function(req, res) {
[Link]("Got a GET request for /ab*cd");
[Link]('Pattern Matched.');
})
var server = [Link](8000, function () {
var host = [Link]().address
var port = [Link]().port
[Link]("Example app listening at [Link] host, port)
})
//node_express_things.js
var express = require('express');
var router = [Link]();
[Link]('/', function(req, res){
[Link]('GET route on [Link]');
});
[Link]('/', function(req, res){ [Link]('POST route on things.'); });
//export this router to use in our [Link]
[Link] = router;
var express = require('Express');
var app = express();

var things = require('./node_express_things.js');

//both [Link] and [Link] should be in same directory


[Link]('/things', things);

[Link](3000);
var express = require('express');
var app = express();
var str="";
[Link]('/display', function(req, res){
[Link]('<p>'+[Link]+'<br>'+[Link]+'<br>'+[Link]+'<br>'+
[Link]+'<br>'+[Link]+'<br>'+[Link]+'<br>'+[Link]+
'<br>'+[Link]+'<br>methods'+'<br>'+ [Link]('text/html')+'<br>'+
[Link]('User-Agent')+'<br>'+[Link]('text/html')+'</p>')
});
[Link](3000, function(){ [Link]('Your Express Server is ready')});
var express = require('express');
var app = express();
var str="";
[Link]('/', function(req, res){
[Link]('<p>'+[Link]+'<br>'+[Link]+'<br>'+'methods'+
[Link]('Link', ['<[Link] '<[Link]
'<br>'+'<br>'+[Link]('Content-Type')+'<br>'+
[Link]({ name: 'ajeet' })+
'</p>')
});
[Link]('/down', function(req, res){
[Link]('./[Link]','[Link]')});
[Link]('/direct', function(req, res){
[Link]('[Link]

[Link](3000, function(){ [Link]('Your Express Server is ready')});


<!--node_express_getform1.html-->
<html>
<body>
<form action="[Link]
method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
var express = require('express');
var app = express();
[Link]([Link]('public'));
[Link](function(req, res, next) {
[Link]('%s %s', [Link], [Link]);
next();
});
[Link]('/', function (req, res) {
[Link](__dirname + "/"
+ "node_express_getform1.html" );})

[Link]('/process_get', function (req, res) {


response = {
first_name:[Link].first_name,
last_name:[Link].last_name
};
[Link](response);
[Link]([Link](response));
})
var server = [Link](8081, function () {

var host = [Link]().address


var port = [Link]().port
[Link]("Example app listening at [Link] host, port)

})
<!--node_express_getform2.html-->
<html>
<body>
<form action="[Link] method="GET">
First Name: <input type="text" name="first_name"/> <br/>
Last Name: <input type="text" name="last_name"/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
var express = require('express');
var app=express();
[Link]([Link]('public'));
[Link]('/[Link]', function (req, res) {
[Link](__dirname + "/"+"node_express_getform2.html" );
});
[Link]('/get_example2', function (req, res) {
[Link]('<p>Username: ' +
[Link]['first_name']+'</p><p>Lastname: '+[Link]['last_name']+'</p>');
})
var server = [Link](8000, function () {
var host = [Link]().address
var port = [Link]().port
[Link]("Example app listening at [Link] host, port)
})
<!--node_express_getform3.html-->
<!DOCTYPE html>
<html>
<body>
<form action="[Link]
<table>
<tr><td>Enter First Name:</td><td><input type="text" name="firstname"/><td></tr>
<tr><td>Enter Last Name:</td><td><input type="text" name="lastname"/><td></tr>
<tr><td>Enter Password:</td><td><input type="password" name="password"/></td></tr>
<tr><td>gender:</td><td>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female">Female
</td></tr>
<tr><td>About You :</td><td>
<textarea rows="5" cols="40" name="aboutyou" placeholder="Write about yourself">
</textarea>
</td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>
</body>
</html>
var express = require('express');
var app=express();
[Link]('/[Link]', function (req, res) {
[Link]( __dirname + "/" + "node_express_getform3.html" );

})
[Link]('/get_example3', function (req, res) {
[Link]('<p>Firstname: ' + [Link]['firstname']+'</p>'+
'<p>Lastname: '+[Link]['lastname']+'</p><p>Password: '+[Link]['password']+'</p>'+
'<p>AboutYou: '+[Link]['aboutyou']+'</p>'+'<p>gender:'+[Link]['gender']);
})

var server = [Link](8000, function () {


var host = [Link]().address
var port = [Link]().port
[Link]("Example app listening at [Link] host, port)
})
<!--node_express_postform.html-->
<html>
<body>
<form action="[Link]
method="POST">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = [Link]({ extended: false })
[Link]([Link]('public'));
[Link]('/[Link]', function (req, res) {
[Link](__dirname + "/"+"node_express_postform.html" );
})
[Link]('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
first_name:[Link].first_name,
last_name:[Link].last_name
};
[Link](response);
[Link]([Link](response));
})
var server = [Link](8000, function () {
var host = [Link]().address
var port = [Link]().port
[Link]("Example app listening at [Link] host, port)
})
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = [Link]({ extended: true });

// Running Server Details.


var server = [Link](8080, function () {
var host = [Link]().address
var port = [Link]().port
[Link]("Example app listening at %s:%s/form", host, port)
});

[Link]('/form', function (req, res) {


var html='';
html +="<body>";
html += "<form action='/thank' method='post' name='form1'>";
html += "<p>Name:<input type= 'text' name='name'></p>";
html += "<p>Email:<input type='text' name='email'></p>";
html += "<p>address:<input type='text' name='address'></p>";
html += "<p>Mobile number:<input type='text' name='mobilno'></p>";
html += "<p><input type='submit' value='submit'>";
html += "<input type='reset' value='reset'></p>";
html += "</form>";
html += "</body>";
[Link](html);
});

[Link]('/thank', urlencodedParser, function (req, res){


var reply='';
reply += "Your name is" + [Link]+"<br>";
reply += "Your E-mail id is" + [Link]+"<br>";
reply += "Your address is" + [Link]+"<br>";
reply += "Your mobile number is" + [Link];
[Link](reply);
});
// npm install express
var express = require('express')
// npm install cookie-parser
var cookieParser = require('cookie-parser')
var app = express();
// need cookieParser middleware before we can do anything with cookies
[Link](cookieParser());
//[Link]([Link]('my secret here'));
// set a cookie
[Link](function (req, res, next) {
// check if client sent cookie
var cookie = [Link]; // RETRIEVE THE COOKIES
if (cookie === undefined || [Link]==undefined)
{
// no: set a new cookie
var randomNumber=[Link]().toString();
randomNumber=[Link](2,[Link]);
[Link]('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
[Link]('monster', 'num1',{expire : 24 * 60 * 60 * 1000 });
//[Link]('signed_monster', 'nom nom', { signed: true });
[Link]('cookie created successfully');
}
else
{
// yes, cookie was already present
[Link]('cookie exists', cookie);
[Link]('cookieName');
[Link]('monster');
//[Link]('School');
//[Link]('cookie foo cleared');
}
next(); // <-- important!
});
[Link]('/', function(req, res) {
[Link]([Link]([Link]));
})
[Link](8081)
<html>
<head>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<form action="/user" method="post">
<h2>Login</h2>
<div class="input-field">
<input type="text" name="username" id="username" placeholder="Enter Username">
</div>
<div class="input-field">
<input type="password" name="password" id="password" placeholder="Enter Password">
</div>
<input type="submit" value="LogIn">
</form>
</body>
</html>
//Import all the [Link] libraries that we explained earlier
const express = require('express');
const cookieParser = require("cookie-parser");
const sessions = require('express-session');

//Initialize the express app


const app = express();
const PORT = 8081;

//Add the Express-session options


// creating 24 hours from milliseconds
const oneDay = 1000 * 60 * 60 * 24;

//session middleware
[Link](sessions({
secret: "thisismysecrctekeyfhrgfgrfrty84fwir767",
saveUninitialized:true,
cookie: { maxAge: oneDay },
resave: false
}));

// parsing the incoming data


[Link]([Link]());
[Link]([Link]({ extended: true }));

//serving public file


[Link]([Link](__dirname));

// cookie parser middleware


[Link](cookieParser());

//Set the authentication credentials


//username and password
const myusername = 'user1'
const mypassword = 'mypassword'

// a variable to save a session


var session;

[Link]('/',(req,res) => {
session=[Link];
if([Link]){
[Link]("Welcome User <a href=\'/logout'>click to logout</a>");
}else
[Link](__dirname + "/"+'[Link]')
});

[Link]('/user',(req,res) => {
if([Link] == myusername && [Link] == mypassword){
session=[Link];
[Link]=[Link];
[Link]([Link])
[Link]("Hey there, welcome <a href=\'/logout'>click to logout</a>");
}
else{
[Link]('Invalid username or password');
}
});

[Link]('/logout',(req,res) => {
[Link]();
[Link]('/');
});
[Link](PORT, () => [Link]('Server Running at port'+PORT));
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');

var app = express();

[Link](cookieParser());
[Link](session({secret: "Shh, its a secret!"}));

[Link]('/', function(req, res){


if([Link].page_views){
[Link].page_views++;
[Link]("You visited this page " + [Link].page_views + " times");
/* [Link](function(error){
[Link]("Session Destroyed")
})*/
} else {
[Link].page_views = 1;
[Link]("Welcome to this page for the first time!");
}
});
[Link](3000);
const express = require("express");
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const app = express();
const port = [Link] || 5000;
var transporter = [Link]({
service:'gmail',
auth: {
user:'your gmail id',
pass:'app password' //app password
}
});

var mailOptions = {
from: '[Link]@[Link]',
to: 'rvijayan@[Link]',
subject: 'Sending Email using [Link]',
text: 'That was easy!',
attachments:[
{
filename:'[Link]',
path:'[Link]'
},
{
filename:'[Link]',
path:'[Link]'
}]
};

[Link](mailOptions, function(error, info){


if (error) {
[Link](error);
} else {
[Link]('Email sent: ' + [Link]);
}
});

[Link](port, () => {
[Link]('Server listening on port '+port);
});
<!DOCTYPE html>
<html lang="en"><head><title>Files</title>
</head><body>
<!-- Upload section-->
<div><h3>Upload Section</h3> <br>
<!-- action to the /upload route-->
<form action="/upload"
method="post"
enctype="multipart/form-data">
File to be uploaded:
<input type="file" name="uploadFile" id="">
<br><br>
<button type="submit">Upload</button></form>
<br></div>
<!-- Download Section-->
<div>
</form></div></body></html>
// Requiring express to handle routing
const express = require("express");
// The fileUpload npm package for handling
// file upload functionality
const fileUpload = require("express-fileupload");
// Creating app
const app = express();
// Passing fileUpload as a middleware
[Link](fileUpload());
// For handling the upload request
[Link]("/upload", function (req, res) {
// When a file has been uploaded
if ([Link] && [Link]([Link]).length !== 0) {
// Uploaded path
const uploadedFile = [Link];

// Logging uploading file


[Link](uploadedFile);

// Upload path
const uploadPath = __dirname
+ "/upload/" + [Link];

// To save the file using mv() function


[Link](uploadPath, function (err) {
if (err) {
[Link](err);
[Link]("Failed !!");
} else [Link]("Successfully Uploaded !!");
});
} else [Link]("No file uploaded !!");
});

// GET request to the root of the app


[Link]("/", function (req, res) {

// Sending [Link] file as response to the client


[Link](__dirname + "/[Link]");
});

// Makes app listen to port 3000


[Link](3000, function (req, res) {
[Link]("Started listening to port 3000");
});
var http = require('http');
[Link](function (req, res)
{
[Link](200,{'Content-Type':'text/html'});
[Link]
('Hello students Your Node JS Server is ready welcome2! webtech winsem2024-25 D2 slot students');
}).listen(4000);
var http = require("http");
var server = [Link]();
[Link]("request", function (req, res) {
[Link]("this is the response");
});
[Link](3000);
var http = require('http');
[Link](function (req, res) {
[Link](200,{'Content-Type': 'text/html'});
[Link]([Link]);
[Link]();
}).listen(8080);
var http = require('http');
var url = require('url');
//var adr='[Link]
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
var q= [Link]([Link],true);
var qdata=[Link];
var txt=[Link]+ " " +[Link]+" "
+[Link]+" " +[Link]+ " " +[Link]+ " " +[Link];
[Link](txt);
}).listen(8080);
//[Link]
[Link] = function () {
return Date();
};
var http = require('http');
var dt = require('./datemodule');

[Link](function (req, res) {


[Link](200,{'Content-Type':'text/html'});
[Link]("<h1>Vijayan, The date and time are currently:</h1> " +
[Link]());
[Link]();
}).listen(8080);
<html>
<body>
<h1> My First Page</h1>
<p> Hi, everybody.....<br>I am Vijayan </p>VIT vellore
</body>
</html>
var http = require('http');
var fs = require('fs');
[Link](function (req, res) {
[Link]('[Link]',
function(err, data) {
[Link](200, {'Content-Type': 'text/html'});
[Link](data);
[Link]();
});
}).listen(8080);
var http = require('http');
var fs = require('fs');

[Link](function (req, res) {


[Link](200, {'Content-Type': 'text/html'});
[Link]('[Link]', function (err, data) {
if (err) {
[Link]([Link]);
return;
}
[Link]([Link]());
[Link](data);
[Link]();
});

}).listen(8080);
var http = require('http');
var uc = require('upper-case');
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]([Link]("Hello Vijayan! vellore vit katpadi"));
[Link]();
}).listen(8080);
var events = require("events");

var myEmitter=new [Link]();


[Link]("someEvent1", function () {
[Link]("event has occured"); });
[Link]("someEvent1");

[Link]("someEvent2", function () {
[Link]("event2 has occured"); });
[Link]("someEvent2");
var events=require('events');
var util=require('util');
var person=function(name){[Link]=name;};

[Link](person,[Link]);
var vijay=new person('vijay');
var raja=new person('raja');
var shri=new person('shri');

var people=[vijay,raja,shri];

[Link](function(person){
[Link]('speak',function(msg) {
[Link]([Link]+' said: '+msg);});});

[Link]('speak','hai students');
[Link]('speak','hello friends');
[Link]('speak','good evenning');
var fs = require("fs");
var buf = new Buffer(1024);

[Link]("Going to open an existing file");


[Link]('[Link]', 'r+', function(err, fd) {
if (err) {
return [Link](err);
}
[Link]("File opened successfully!");
[Link]("Going to read the file");

[Link](fd, buf, 0, [Link], 0, function(err, bytes) {


if (err) {
[Link](err);
}

// Print only read bytes to avoid junk.


if(bytes > 0) {
[Link]([Link](0, bytes).toString());
}

// Close the opened file.


[Link](fd, function(err) {
if (err) {
[Link](err);
}
[Link]("File closed successfully.");
});
});
});
var fs = require("fs");

[Link]("Going to delete an existing file");


[Link]('[Link]', function(err) {
if (err) {
return [Link](err);
}
[Link]("File deleted successfully!");
});
var fs = require("fs");

// Asynchronous - Opening File


[Link]("Going to open file!");
[Link]('[Link]', 'r+', function(err, fd) {
if (err) {
return [Link](err);
}
[Link]("File opened successfully!");
});
var fs = require("fs");
var buf = new Buffer(1024);

[Link]("Going to open an existing file");


[Link]('[Link]', 'r+', function(err, fd) {
if (err) {
return [Link](err);
}
[Link]("File opened successfully!");
[Link]("Going to read the file");

[Link](fd, buf, 0, [Link], 0, function(err, bytes){


if (err){
[Link](err);
}
[Link](bytes + " bytes read");

// Print only read bytes to avoid junk.


if(bytes > 0){
[Link]([Link](0, bytes).toString());
}
});
});
var fs = require("fs");

[Link]("Going to write into existing file");


[Link]('[Link]', 'Simply Easy Learning!', function(err) {
if (err) {
return [Link](err);
}

[Link]("Data written successfully!");


[Link]("Let's read newly written data");

[Link]('[Link]', function (err, data) {


if (err) {
return [Link](err);
}
[Link]("Asynchronous read: " + [Link]());
});
});
var fs = require("fs");
var data = [Link]('[Link]');
[Link]([Link]());
[Link]("Program Ended");
var http = require("http");
var server = [Link]();
[Link]("request", function (req, res) {
[Link]("this is the response");
});
[Link](3000);

You might also like