Web Designing - II
Web Designing - II
SUCHIKA PATEL
[UNIT – 1: INTRODUCTION TO XML]
XML:
XML stands for Extensible Markup Language. It is a text-based markup
language derived from Standard Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than
specifying how to display it like HTML tags, which are used to display the data.
❖ XML carries the data does not present it − XML allows you to store the data
Irrespective of how it will be presented.
❖ XML is a public standard − XML was developed by an organization called the World
Wide Web Consortium (W3C) and is available as an open standard.
XML Usage:
❖ XML can work behind the scene to simplify the creation of HTML documents
for large web sites.
❖ XML can be used to exchange the information between organizations and systems.
❖ XML can be used to store and arrange the data, which can customize your data
handling needs.
❖ XML can easily be merged with style sheets to create almost any desired output.
What is Markup?
XML is a markup language that defines set of rules for encoding documents in a
format that is both human-readable and machine-readable.
More specifically, a markup language is a set of symbols that can be placed in the text of a
document to demarcate and label the parts of that document.
Following example shows how XML markup looks, when embedded in a piece of text −
<message>
<text>Hello, world!</text>
</message>
This snippet includes the markup symbols, or the tags such as <message>...</message> and
<text>... </text>.
The tags <message> and </message> mark the start and the end of the XML code fragment.
The tags <text> and </text> surround the text Hello, world!
These programs instruct the computer to perform specific tasks. XML does not qualify to be
a programming language as it does not perform any computation or algorithms.
It is usually stored in a simple text file and is processed by special software that is capable of
interpreting XML.
XML Declaration
The XML document can optionally have an XML declaration. It is written as follows −
Where version is the XML version and encoding specifies the character encoding used in the
document.
❖ The XML declaration is case sensitive and must begin with "<?xml>" where "xml"
is written in lower-case.
❖ If document contains XML declaration, then it strictly needs to be the first statement
of the XML document.
❖ An HTTP protocol can override the value of encoding that you put in the
XML declaration.
<element>
<element>. .. </element>
<element/>
<contact-info>
<company>Google
</contact-info>
</company>
<contact-info>
</contact-info>
Root Elements
Root Elements an XML document can have only one root element. For example, following
is not a correct XML document, because both the x and y elements occur at the top level
without a root element −
<x>. </x>
<y>. </y>
<root>
<x>. </x>
<y>...</y>
</root>
Case Sensitivity –
The names of XML-elements are case-sensitive. That means the name of the start and the
end elements need to be exactly in the same case.
An attribute specifies a single property for the element, using a name/value pair. An XML-
element can have one or more attributes. For example −
❖ Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href
are considered two different XML attributes.
❖ Same attribute cannot have two values in syntax. The following example shows
incorrect syntax because the attribute b is specified twice
❖ Attribute names are defined without quotation marks, whereas attribute values must
always appear in quotation marks. Following example demonstrates incorrect xml
syntax
In the above syntax, the attribute value is not defined in quotation marks.
XML References
References usually allow you to add or include additional text or markup in an XML
document. References always begin with the symbol "&" which is a reserved character and
end with the symbol ";". XML has two types of references −
❖ Entity References − an entity reference contains a name between the start and the
end delimiters. For example & where amp is name. The name refers to a
predefined string of text and/or markup.
XML Text
The names of XML-elements and XML-attributes are case-sensitive, which means the name
of start and end elements need to be written in the same case. To avoid character encoding
problems, all XML files should be saved as Unicode UTF-8 or UTF-16 files.
Whitespace characters like blanks, tabs and line-breaks between XML-elements and
between the XML-attributes will be ignored.
Some characters are reserved by the XML syntax itself. Hence, they cannot be used directly.
To use them, some replacement-entities are used, which are listed below −
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
❖ XML declaration
You can separate a document into multiple sections so that they can be rendered
differently, or used by a search engine.
The elements can be containers, with a combination of text and other elements.
8 Prepared By: SUCHIKA PATEL
SDJ International College, Palsana.
[UNIT – 1: INTRODUCTION TO XML]
Syntax
Following syntax shows XML declaration −
<?xml
version = "version_number"
encoding = "encoding_declaration"
standalone = "standalone_status"
?>
Each parameter consists of a parameter name, an equals sign (=), and parameter value
inside a quote. Following table shows the above syntax in detail −
Parameter Parameter_value Parameter_description
Rules:
An XML declaration should abide with the following rules −
❖ If the XML declaration is present in the XML, it must be placed as the first line in
the XML document.
❖ The order of placing the parameters is important. The correct order is: version,
encoding and standalone.
<?xml >
SUCHIKA PATEL
UNIT: 2 jQuery Fundamentals
jQuery Features
o HTML manipulation
o DOM manipulation
o DOM element selection
o CSS manipulation
o Effects and Animations
o Utilities
o AJAX
o HTML event methods
o JSON Parsing
o Extensibility through plug-ins
o Microsoft
o Google
o IBM
o Netflix
❖ Jquery History
o jQuery was first released in January 2006 by John Resig at BarCamp
NYC. It is currently headed by Timmy Wilson and maintained by a team
of developers.
o Nowadays, jQuery is widely used technology. Most of the websites are
using jQuery.
Advantages of JQuery
JQuery Syntax:
$(selector).action()
• jQuery selectors are used to "find" (or select) 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: $().
Example :
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
• 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.
• $("#test")
• Example
• When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
• $(".test")
Example
When a user clicks on a button, the elements with class="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
Syntax Description
$("ul li:first") Selects the first <li> element of the first <ul>
Examples:
$(selector).action()
$(“p”).click();
➢ The next step defines what should happen when the event fires. You must
pass a function to the event.
$("p").click(function(){
// action goes here!!
});
1. ready() :
$(document).ready(function(){
// jQuery methods go here...
});
$(function(){
// jQuery methods go here...
});
2. click()
• The click() method triggers the click event, or attaches a function to run
when a click event occurs.
Syntax
$(selector).click()
$(selector).click(function)
Example:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
alert("The Button was clicked.");
});
});
</script>
</head>
<body>
<p><input type="Button" id="btn" name="btn" value="Button"></p>
</body>
</html>
3. keypress()
• The keypress event is similar to the keydown event. The event occurs
when a button is pressed down.
• However, the keypress event is not fired for all keys (e.g. ALT, CTRL,
SHIFT, ESC).
Syntax
$(selector).keypress()
$(selector).keypress(function)
Example
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script><script src="js/jquery.js"></script>
i = 0;
$(document).ready(function(){
$("input").keypress(function(){
$("span").text(i += 1);
});
});
</script>
</head>
<body>
4. focus()
The focus event occurs when the <input> field gets focus:
• The focus event occurs when an element gets focus (when selected by a
mouse click or by "tab-navigating" to it).
• The focus() method triggers the focus event, or attaches a function to run
when a focus event occurs.
Syntax
$(selector).focus()
$(selector).focus(function)
Example
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$("span").css("display", "inline").fadeOut(2000);
});
});
</script>
<style>
span {
display: none;
SDJ INTERNATIONAL COLLEGE,PALSANA
}
</style>
</head>
<body>
<input>
</body>
</html>
5. blur()
• The blur event occurs when the <input> field loses focus
Syntax
$(selector).blur()
Attach a function to the blur event:
$(selector).blur(function)
Example
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("input").blur(function(){
alert("This input field has lost its focus.");
});
});
</script>
</head>
<body>
</body>
</html>
6. change()
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("input").change(function(){
alert("The text has been changed.");
});
});
</script>
</head>
<body>
<input type="text">
<p>Write something in the input field, and then press enter or click outside the
field.</p>
</body>
</html>
Syntax:
$(selector).hide(speed,callback);
$(selector).show(speed,callback);
• Speed: optional parameter. Specifies the speed of the hiding/showing,
and can take the following values: "slow", "fast", or milliseconds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of jQuery Show Hide Effects</title>
<script src="js/jquery.js"></script>
<style>
p{
padding: 15px;
background: #F0E68C;
}
</style>
<script>
$(document).ready(function(){
// Hide displayed paragraphs
$("#hide-btn").click(function(){
$("p").hide();
});
</head>
<body>
<!--button type="button" class="hide-btn" >Hide </button>
<button type="button" class="show-btn">Show</button -->
<p>India is my country.</p>
<p>I love my country.</p>
</body>
</html>
2.Fade
1.fadeIn()
Syntax:
$(selector).fadeIn(speed,callback);
2.fadeOut()
Syntax:
$(selector).fadeOut(speed,callback);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of jQuery Fade-In and Fade-Out Effects</title>
<script src="js/jquery.js"></script>
<style>
p{
padding: 15px;
background: #DDA0DD;
}
</style>
<script>
$(document).ready(function(){
// Fadeing out displayed paragraphs
$(".out-btn").click(function(){
$("p").fadeOut();
});
</head>
<body>
<button type="button" class="out-btn">Fade Out Paragraphs</button>
<button type="button" class="in-btn">Fade In Paragraphs</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
3.fadeToggle()
4.fadeTo()
Syntax:
$(selector).fadeTo(speed,opacity,callback);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
SDJ INTERNATIONAL COLLEGE,PALSANA
• Similarly, you can specify the duration parameter for the fadeToggle()
method like fadeIn()/fadeOut() method to control the duration or speed of
the fade toggle animation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of jQuery Fade-Toggle Effect with Different Speeds</title>
<script src="js/jquery.js"></script>
<style>
p{
padding: 15px;
background: #DDA0DD;
}
</style>
<script>
$(document).ready(function(){
// Fade Toggles paragraphs with different speeds
$(".toggle-btn").click(function(){
$("p.normal").fadeToggle();
$("p.fast").fadeToggle("fast");
$("p.slow").fadeToggle("slow");
$("p.very-fast").fadeToggle(50);
$("p.very-slow").fadeToggle(2000);
});
});
</script>
</head>
<body>
<button type="button" class="toggle-btn">Fade Toggle Paragraphs</button>
<p class="very-fast">This paragraph will fade in/out with very fast
speed.</p>
<p class="normal">This paragraph will fade in/out with default speed.</p>
<p class="fast">This paragraph will fade in/out with fast speed.</p>
<p class="slow">This paragraph will fade in/out with slow speed.</p>
<p class="very-slow">This paragraph will fade in/out with very slow
speed.</p>
</body>
</html>
4.fadeTo()
Syntax:
$(selector).fadeTo(speed,opacity,callback);
</body>
</html>
3.Slide
1.slideDown()
Syntax:
$(selector).slideDown(speed,callback);
• The optional speed parameter specifies the duration of the effect. It can
take the following values: "slow", "fast", or milliseconds.
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
SDJ INTERNATIONAL COLLEGE,PALSANA
display: none;
}
</style>
</head>
<body>
</body>
</html>
2.slideUp()
Syntax:
$(selector).slideUp(speed,callback);
• The optional speed parameter specifies the duration of the effect. It can
take the following values: "slow", "fast", or milliseconds.
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
}
</style>
</head>
<body>
</body>
</html>
3.slideToggle()
• If the elements have been slid down, slideToggle() will slide them up.
• If the elements have been slid up, slideToggle() will slide them down.
Syntax
$(selector).slideToggle(speed,callback);
• The optional speed parameter can take the following values: "slow",
"fast", milliseconds.
<!DOCTYPE html>
<html>
SDJ INTERNATIONAL COLLEGE,PALSANA
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
</body>
</html>
4.Stop
Syntax:
$(selector).stop(stopAll,goToEnd);
• By default, the stop() method kills the current animation being performed
on the selected element.
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></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>
</body>
</html>
5.Chaining
• Chaining allows us to run multiple jQuery methods (on the same element)
within a single statement.
• chaining is a technique that allows us to run multiple jQuery commands,
one after the other, on the same element(s).
• To chain an action, you simply append the action to the previous action.
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></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>
<button>Click here</button>
</body>
</html>
6.Callback
syntax:
$(selector).hide(speed,callback);
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
});
</script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
});
</script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</body>
</html>
1. text()
• This method is either used to get the combined text contents of the
selected elements, including their descendants, or set the text contents of
the selected elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Text Contents of the Elements</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$(".btn-one").click(function(){
var str = $("p").text();
alert(str);
});
$(".btn-two").click(function(){
var str = $("p:first").text();
alert(str);
});
$(".btn-three").click(function(){
var str = $("p.extra").text();
alert(str);
});
});
</script>
</head>
<body>
<button type="button" class="btn-one">Get All Paragraph's Text</button>
<button type="button" class="btn-two">Get First Paragraph's Text</button>
<button type="button" class="btn-three">Get Last Paragraph's Text</button>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
2. attr()
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get an Element's Attribute Value</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$(".btn-one").click(function(){
var str = $("a").attr("href");
alert(str);
});
$(".btn-two").click(function(){
var str = $("img#sky").attr("alt");
alert(str);
});
});
</script>
</head>
<body>
<button type="button" class="btn-one">Get Link's HREF Attribute</button>
<button type="button" class="btn-two">Get Image ALT Attribute</button>
<p><a href="https://www.google.com/">Google search engine</a></p>
<img id="sky" src="/examples/images/sky.jpg" alt="Cloudy Sky">
</body>
</html>
3. html()
• The jQuery html() method is used to get or set the HTML contents of the
elements.
• Get HTML Contents with html() Method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get HTML Contents of an Element</title>
<script src="js/jquery.js"></script>
<script>
SDJ INTERNATIONAL COLLEGE,PALSANA
$(document).ready(function(){
$(".btn-one").click(function(){
var str = $("p").html();
alert(str);
});
$(".btn-two").click(function(){
var str = $("#container").html();
alert(str);
});
});
</script>
</head>
<body>
<button type="button" class="btn-one">Get Paragraph's HTML
Contents</button>
<button type="button" class="btn-two">Get Container's HTML
Contents</button>
<div id="container">
<h1>Hello World!</h1>
<p>The quick <b>brown fox</b> jumps over the lazy dog.</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set HTML Contents of the Element</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("body").html("<p>Hello World!</p>");
});
SDJ INTERNATIONAL COLLEGE,PALSANA
});
</script>
</head>
<body>
<button type="button">Write Message</button>
</body>
</html>
The following example will show you how to set the checked attribute of
the checkbox.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set Element's Attribute Value</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('input[type="checkbox"]').attr("checked", "checked");
});
});
</script>
</head>
<body>
<p><label><input type="checkbox"></label> I agree with terms and
conditions.</p>
<button type="button">Check</button>
</body>
</html>
• The attr() method also allows you to set multiple attributes at a time.
• The following example will show you how to set the class and title
attribute for the <img> elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set Multiple Attribute for the Elements</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("img").attr({
"class" : "frame",
"title" : "Hot Air Balloons"
});
});
});
</script>
<style>
.frame{
border: 6px solid #000;
}
</style>
</head>
<body>
<button type="button">Set Attributes for Image</button>
<p>
<img src="/examples/images/balloons.jpg" alt="Hot Air Balloons">
</p>
</body>
</html>
• The jQuery val() method is mainly used to get or set the current value of
the HTML form elements such as <input>, <select> and <textarea>.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get a Form Field Value</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button.get-name").click(function(){
var name = $("#name").val();
alert(name);
});
$("button.get-comment").click(function(){
var comment = $("#comment").val();
alert(comment);
});
$("button.get-city").click(function(){
var city = $("#city").val();
alert(city);
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="name">
</td>
</tr>
<tr>
<td>Comments:</td>
<td>
<textarea rows="4" cols="30" id="comment"></textarea>
SDJ INTERNATIONAL COLLEGE,PALSANA
</td>
</tr>
<tr>
<td>City:</td>
<td>
<select id="city">
<option>London</option>
<option>Paris</option>
<option>New York</option>
</select>
</td>
</tr>
</table>
</form>
<p><strong>Note:</strong> Fill the above form and click the following
button to get the value.</p>
<button type="button" class="get-name">Get Name</button>
<button type="button" class="get-comment">Get Comment</button>
<button type="button" class="get-city">Get City</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set Form Fields Values</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var text = $(this).text();
$('input[type="text"]').val(text);
});
});
</script>
</head>
<body>
<button type="button">Discovery</button>
<button type="button">Atlantis</button>
<button type="button">Endeavour</button>
<p><strong>Note:</strong> Click the above buttons to set the value of
following input box.</p>
<p>
<input type="text">
</p>
</body>
</html>
Syntax
$(selector).append(content,function(index,html))
Parameter Description
Possible values:
• HTML elements
• jQuery objects
• DOM elements
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
$("#btn2").click(function(){
$("ol").append("<li>Appended item</li>");
});
});
</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>
</body>
</html>
SDJ INTERNATIONAL COLLEGE,PALSANA
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").append(function(n){
return "<b>This p element has index " + n + ".</b>";
});
});
});
</script>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
2. prepend()
Parameter Description
Possible values:
• HTML elements
• jQuery objects
• DOM elements
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").prepend("<b>Prepended text</b>. ");
});
$("#btn2").click(function(){
$("ol").prepend("<li>Prepended item</li>");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
SDJ INTERNATIONAL COLLEGE,PALSANA
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").prepend(function(n){
return "<b>This p element has index " + n + "</b>. ";
});
});
});
</script>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
3. text()
• Get the combined text contents of each element in the set of matched
elements, including their descendants.
• This method does not accept any arguments.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>text demo</title>
<style>
p{
color: blue;
margin: 8px;
}
b{
color: red;
}
</style>
<script src="js/jquery.js"></script>
</head>
<body>
<p><b>Test</b> Paragraph.</p>
<p></p>
<script>
var str = $( "p" ).first().text();
$( "p" ).last().html( str );
</script>
</body>
</html>
4. before()
Syntax
$(selector).before(content,function(index))
Parameter Description
Possible values:
• HTML elements
• jQuery objects
• DOM elements
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
function beforeText() {
var txt1 = "<b>I </b>"; // Create element with HTML
var txt2 = $("<i></i>").text("love "); // Create with jQuery
var txt3 = document.createElement("b"); // Create with DOM
txt3.innerHTML = "jQuery!";
$("img").before(txt1, txt2, txt3); // Insert new elements before img
}
</script>
</head>
<body>
</body>
</html>
Example 2 :
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").before(function(n){
return "<div>The p element below has index " + n + ".</div>";
});
});
});
</script>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
5. after()
The after() method inserts specified content after the selected elements.
Syntax
$(selector).after(content,function(index))
Parameter Description
Possible values:
• HTML elements
• jQuery objects
• DOM elements
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").after("<p>Hello world!</p>");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
6. wrap()
Syntax
$(selector).wrap(wrappingElement,function(index))
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").wrap("<div></div>");
});
});
</script>
<style>
div{background-color: yellow;}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
1. remove()
The remove() method removes the selected elements, including all text and
child nodes.
This method also removes data and events of the selected elements.
Syntax
$(selector).remove(selector)
Parameter Description
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").remove();
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
2. empty()
• The empty() method removes all child nodes and content from the
selected elements.
Syntax
$(selector).empty()
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").empty();
});
});
</script>
</head>
<body>
<div style="height:100px;background-color:yellow">
This is some text
<p>This is a paragraph inside the div.</p>
</div>
</body>
</html>
3. unwrap()
The unwrap() method removes the parent element of the selected elements.
Syntax
$(selector).unwrap()
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").unwrap();
});
});
</script>
<style>
div{background-color: yellow;}
article{background-color: pink;}
</style>
</head>
<body>
<div>
<p>This is a paragraph inside a div element.</p>
</div>
<article>
<p>This is a paragraph inside an article element.</p>
</article>
</body>
</html>
2.3.4 jQuery Get and Set CSS properties using css() method.
• The css() method sets or returns one or more style properties for the
selected elements.
syntax:
css("propertyname");
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("p").css("background-color"));
});
SDJ INTERNATIONAL COLLEGE,PALSANA
});
</script>
</head>
<body>
<h2>This is a heading</h2>
</body>
</html>
syntax:
css("propertyname","value");
The following example will set the background-color value for ALL matched
elements:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
SDJ INTERNATIONAL COLLEGE,PALSANA
<p>This is a paragraph.</p>
</body>
</html>
syntax:
css({"propertyname":"value","propertyname":"value",...});
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
</body>
</html>
Prof.SUCHIKA PATEL
Unit - 3 [JSON]
JSON:
JSON or JavaScript Object Notation is a lightweight text-based open standard
designed for human-readable data interchange. Conventions used by JSON are known to
programmers, which include C, C++, Java, Python, Perl, etc.
Uses of JSON
• JSON format is used for serializing and transmitting structured data over network
connection.
• Web services and APIs use JSON format to provide public data.
Characteristics of JSON
The following example shows how to use JSON to store information related to books based
on their topic and edition.
"book": [
"id":"01",
"language": "Java",
"edition": "third",
},
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
Json.html
<html>
<head>
<title>JSON example</title>
<script language = "javascript" >
var object1 = { "language" : "Java", "author" :
"herbert schildt" };
document.write("<h1>JSON with JavaScript
example</h1>");
document.write("<br>");
document.write("<h3>Language = " +
object1.language+"</h3>");
document.write("<h3>Author = " +
Prepared By: SUCHIKA PATEL 3
SDJ International College,Palsana.
Unit - 3 [JSON]
object1.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming
language can be studied " + "from book written by " +
object2.author);
document.write("<hr />");
</script>
</head>
<body>
</body>
</html>
o Self-describing: Both json and xml are self-describing as both xml data and json data
are human-readable text.
o Hierarchical: Both json and xml support hierarchical structure. Here hierarchical
means that the values within values.
o Data interchange format: JSON and XML can be used as data interchange formats by
many different programming languages.
o Retrieve: Both formats can be retrieved by using HTTP requests. The methods used
for retrieving the data are GET, PUT, POST.
JSON XML
JSON stands for javascript object XML stands for an extensible markup
notation. language.
The extension of json file is .json. The extension of xml file is .xml.
The object created in JSON has XML data does not have any type.
some type.
It does not have any capacity to XML is a markup language, so it has the
display the data. capacity to display the content.
JSON has no tags. XML data is represented in tags, i.e., start tag
and end tag.
JSON is quicker to read and XML file takes time to read and write
write. because the learning curve is higher.
JSON can use arrays to represent XML does not contain the concept of arrays.
the data.
JSON Objects
This is a JSON string:
Keys must be strings, and values must be a valid JSON data type:
• string
• number
• object
• array
• boolean
• null
The data is only JSON when it is in a string format. When it is converted to a JavaScript
variable, it becomes a JavaScript object.
JavaScript Objects
You can create a JavaScript object from a JSON object literal:
Example
Example
Example
You can also access object values by using bracket ([]) notation:
Example
Looping an Object
Example
In a for-in loop, use the bracket notation to access the property values:
Example
Json Arrays
Arrays in JSON are almost the same as arrays in JavaScript.
In JSON, array values must be of type string, number, object, array, boolean or null.
In JavaScript, array values can be all of the above, plus any other valid JavaScript expression,
including functions, dates, and undefined.
JavaScript Arrays
Example
Example
Example
myArray[0];
Arrays in Objects
Example
{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
}
Example
myObj.cars[0];
Example
Example
{"employees":[
]}
JSON Comments
JSON doesn't support comments. It is not a standard.
But you can do some tricks such as adding extra attribute for comment in JSON object, for
example:
"employee": {
"name": "Bob",
"salary": 56000,
AJAX:
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new
technique for creating better, faster, and more interactive web applications with
the help of XML, HTML, CSS, and Java Script.
Ajax uses XHTML for content, CSS for presentation, along with
Document Object Model and JavaScript for dynamic content display.
With AJAX, when you hit submit, JavaScript will make a request to
the server, interpret the results, and update the current screen. In the
purest sense, the user would never know that anything was even
transmitted to the server.
XML is commonly used as the format for receiving server data, although
any format, including plain text, can be used.
JavaScript
DOM
CSS
• Allows for a clear separation of the presentation style from the content
and may be changed programmatically by JavaScript
XMLHttpRequest
As you can see in the above image, full page is refreshed at request time and user
is blocked until request completes.
As you can see in the above image, full page is not refreshed at request time
Prepared By: Prof. SUCHIKA PATEL 4
SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]
4.2 XMLHttpRequest
An object of XMLHttpRequest is used for asynchronous
communication between client and server.
Property Description
Method Description
As you can see in the above example, XMLHttpRequest object plays a important role.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
Example:
<!DOCTYPE html>
<html>
<body>
<div id="demo">
</div>
<script>
function loadDoc() {
xhttp.onreadystatechange = function() {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt",
true); xhttp.send();
}
</script>
</body>
</html>
Prepared By: Prof. SUCHIKA PATEL 8
SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]
Example 2:
<html>
<body>
<div id="demo">
</button>
</div>
<script>
function loadDoc(url,
xhttp.onreadystatechange = function() {
if (this.readyState == 4 &&
};
xhttp.open("GET", url,
true); xhttp.send();
Prepared By: Prof. SUCHIKA PATEL 9
SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]
function myFunction(xhttp) {
document.getElementById("demo").innerHTML =
xhttp.responseText;
</script>
</body>
</html>
5. Node.js
Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used to run
real-time server applications.
“Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications. Node.js uses an event-driven, non-blocking I/O model that
makes it lightweight and efficient, perfect for data-intensive real-time applications that run
across distributed devices.”
Node.js also provides a rich library of various JavaScript modules to simplify the
development of web applications.
1 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
Features of Node.JS
Following is a list of some important features of Node.js that makes it the first choice of
software architects.
1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its library is
very fast in code execution.
2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are asynchronous i.e.
non-blocking. So a Node.js based server never waits for an API to return data. The server
moves to the next API after calling it and a notification mechanism of Events of Node.js
helps the server to get a response from the previous API call. It is also a reason that it is very
fast.
3. Single threaded: Node.js follows a single threaded model with event looping.
4. Highly Scalable: Node.js is highly scalable because event mechanism helps the server to
respond in a non-blocking way.
5. No buffering: Node.js cuts down the overall processing time while uploading audio and
video files. Node.js applications never buffer any data. These applications simply output the
data in chunks.
6. Open source: Node.js has an open source community which has produced many excellent
modules to add additional capabilities to Node.js applications.
To install and setup an environment for Node.js, you need the following two software
available on your computer:
1. Text Editor.
You can download the latest version of Node.js installable archive file from
https://nodejs.org/en/.
There are various installers available on https://nodejs.org/en/. The installation files are
available for Windows, Linux, Solaris, MacOS.
2 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
Download the installer for windows by clicking on LTS or Current version button. Here, we
will install the latest version LTS for windows that has long time support. However, you can
also install the Current version which will have the latest features.
After you download the MSI, double-click on it to start the installation as shown below.
3 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
4 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
Ready to install:
5 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
Verify Installation
Once you install Node.js on your computer, you can verify it by opening the command
prompt and typing node -v. If Node.js is installed successfully then it will display the version
of the Node.js installed on your machine, as shown below.
6 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
5.2.2 Components
1. Import required modules: The "require" directive is used to load a Node.js module.
2. Create server: You have to establish a server which will listen to client's request similar to
Apache HTTP Server.
3. Read request and return response: Server created in the second step will read HTTP
request made by client which can be a browser or console and return the response.
Require Modules: Method require() is used to consume modules. It allows you to include
modules in your app. You can add built-in core Node.js modules, community-based modules
(node_modules), and local modules too.
Node.js follows the CommonJS module system, and the built-in require function is the
easiest way to include modules that exist in separate files. The basic functionality of require
is that it reads a JavaScript file, executes the file, and then proceeds to return the exports
object.
As per above syntax, specify the module name in the require() function. The require()
function will return an object, function, property or any other JavaScript type, depending on
what the specified module returns.
We use the require directive to load the http module and store the returned HTTP instance
into an http variable as follows -block1
In the above example, require() function returns an object because http module returns its
functionality as an object, you can then use its properties and methods using dot notation
e.g. http.createServer().
7 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
Create server: In the second component, you have to use created http instance and call
http.createServer() method to create server instance and then bind it at port 8081 using
listen method associated with server instance. Pass it a function with request and response
parameters and write the sample implementation to return "Hello World". Check the
example below: block2
response.end('Hello World\n');
}).listen(8081);
Now combine the block 1 and block 2 and save the file as check.js; while executing the
above it will just create an HTTP server which listens to the port mentioned as 8081 on the
local machine.
8 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
For starting the server, we need to start the command prompt as follows:
Click the start menu and type node.js command prompt. Once the command prompt is
open just move the location where the check.js file is stored.
Once you get the message like server is running at ͙.. , We can just open any browser and
check for the http://127.0.0.1:8081/
Now, if you make any changes in the " check.js" file, you need to again run the "node
check.js" command.
This is how the http server is created and request which are sent over https server are
responded from the port 8081.
9 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
In Node.js, Modules are the blocks of encapsulated code that communicates with an
external application on the basis of their related functionality. Modules can be a single file or
a collection of multiples files/folders. The reason programmers are heavily reliant on
modules is because of their re-usability as well as the ability to break down a complex piece
of code into manageable chunks.
Node.js has many built-in modules that are part of the platform and comes with Node.js
installation. Node Js Core Modules comes with its installation by default. You can use them
as per application requirements. These modules can be loaded into the program by using
the require function.
The require () function will return a JavaScript type depending on what the particular
module returns.
The following example demonstrates how to use the Node.js Http module to create a web
server.
res.end();
}).listen(3000);
In the above example, the require() function returns an object because the Http module
returns its functionality as an object. The function http.createServer() method will be
executed when someone tries to access the computer on port 3000. The res.writeHead()
method is the status code where 200 means it is OK, while the second argument is an object
containing the response headers.
Module Description
10 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
var os = require("os")
Modules are the collection of JavaScript codes in a separate logical file that can be used in
external applications on the basis of their related functionality. Modules are popular as they
are easy to use and are reusable. Sometimes it is required that, when you are implementing a
Node.js application for a use case, you might want to keep your business logic separately. In
such cases you create a Node.js module with all the required functions in it.
The module.exports is a special object which is included in every JavaScript file in the
Node.js application by default. The module is a variable that represents the current module,
11 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
and exports is an object that will be exposed as a module. So, whatever you assign to
module.exports will be exposed as a module.
To create a module in Node.js, the exports keyword is used. This keyword tells Node.js that
the function can be used outside the module. A Node.js Module is a .js file with one or more
functions.
};
• exports - is a keyword which tells Node.js that the function is available outside the
module.
• function_name - is the function name using which we can access this function in
other programs.
Node.js follows the CommonJS module system, and the built-in require function is the
easiest way to include modules that exist in separate files. The basic functionality of require
is that it reads a JavaScript file, executes the file, and then proceeds to return the exports
object. An example module:
console.log(msg);
Run the above example and see the result, as shown below.
12 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
Export Object
The exports is an object. So, you can attach properties or methods to it. The following
example exposes an object with a string property in Message.js file.
//or
In the above example, we have attached a property SimpleMessage to the exports object.
Now, import and use this module, as shown below: app.js
console.log(msg.SimpleMessage);
In the above example, the require() function will return an object { SimpleMessage : 'Hello
World'} and assign it to the msg variable. So, now you can use msg.SimpleMessage.
Run the above example by writing node app.js in the command prompt and see the output
as shown below.
Hello World
In the same way as above, you can expose an object with function. The following example
exposes an object with the log function as a module: Log.js
console.log(msg); };
The above module will expose an object- { log : function(msg){ console.log(msg); } } . Use the
above module as shown below: app.js
msg.log('Hello World');
module.exports = {
13 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
firstName: 'James',
lastName: 'Bond'
app.js
Run the above example and see the result, as shown below.
To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer
data over the HTTP. To use the HTTP server in node, we need to require the HTTP module.
The HTTP module creates an HTTP server that listens to server ports and gives a response
back to the client. The HTTP core module is a key module to Node.js networking. It is
designed to support many features of the HTTP protocol.
We can create a HTTP server with the help of http.createServer() method. (Ex:testing.js)
response.write('Hello World!');
// Signals the server that all of the response headers and body have been sent
response.end();
})
Above code will start the webserver by running the command node testing.js
var options = {
host: 'www.amrolicollege.org',
path: '/sports2122',
14 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
method: 'GET'
};
console.log(`STATUS: ${response.statusCode}`);
}).end();
Above example will display the status code of the request made on server.
The HTTP module provides some properties and methods, and some classes.
http.METHODS
> require('http').METHODS
[ 'ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LINK', 'LOCK', 'M-
SEARCH', 'MERGE', 'MKACTIVITY', 'MKCALENDAR', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS',
'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REBIND', 'REPORT', 'SEARCH',
'SUBSCRIBE', 'TRACE', 'UNBIND', 'UNLINK', 'UNLOCK', 'UNSUBSCRIBE']
http.STATUS_CODES
This property lists all the HTTP status codes and their description:
'100': 'Continue',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
15 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
'207': 'Multi-Status',
'302': 'Found',
'401': 'Unauthorized',
'403': 'Forbidden',
'409': 'Conflict',
'410': 'Gone',
16 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
'Expectation Failed',
'423': 'Locked',
17 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
http.globalAgent
The http.globalAgent is a global object of the http.Agent class, which is utilized for all the
HTTP client requests by default. It is used to control connections persistence, and reuse for
HTTP clients. Moreover, it is a significant constituent in Node.js HTTP networking.
When you view a webpage in your browser, you are making a request to another computer
on the internet, which then provides you the webpage as a response. That computer you
are talking to via the internet is a web server. A web server receives HTTP requests from a
client, like your browser, and provides an HTTP response, like an HTML page or JSON from
an API. To access web pages of any web application, you need a web server. The web server
will handle all the http requests for the web application e.g IIS is a web server for ASP.NET
web applications and Apache is a web server for PHP or Java web applications.
A lot of software is involved for a server to return a webpage. This software generally falls
into two categories: frontend and backend. Front-end code is concerned with how the
content is presented, such as the color of a navigation bar and the text styling. Back-end
code is concerned with how data is exchanged, processed, and stored. Code that handles
network requests from your browser or communicates with the database is primarily
managed by back-end code.
Node.js allows developers to use JavaScript to write back-end code, even though
traditionally it was used in the browser to write front-end code. Having both the frontend
and backend together like this reduces the effort it takes to make a web server, which is a
major reason why Node.js is a popular choice for writing back-end code.
There are a variety of modules such as the “http” and “request” module, which helps in
processing server related requests in the webserver space. We will have a look at how we
can create a basic web server application using Node js.
Node.js provides capabilities to create your own web server which will handle HTTP
requests asynchronously. You can use IIS or Apache to run Node.js web application but it is
recommended to use Node.js web server.
18 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the
Hyper Text Transfer Protocol (HTTP). The HTTP module can create an HTTP server that
listens to server ports and gives a response back to the client. Refer the code below to
understand the concept; filename:helloserver.js
var http=require('http')
var server=http.createServer((function(request,response)
response.writeHead(200,
{"Content-Type" : "text/plain"});
response.end("Hello World\n");
}));
server.listen(8081);
1. The basic functionality of the require function is that it reads a JavaScript file, executes
the file, and then proceeds to return the exports object. So in our case, since we want to use
the functionality of the http module, we use the require function to get the desired
functions from the http module so that it can be used in our application.
2. In this 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. The
request object can be used to get information about the current HTTP request e.g., url,
request header, and data. The response object can be used to send a response for a current
HTTP request.
3. When a request is received, we are saying to send a response with a header type of ‘200.’
This number is the normal response which is sent in an http header when a successful
response is sent to the client.
5. We are then using the server.listen function to make our server application listen to client
requests on port no 8081. You can specify any available port over here.
Run the above web server by writing node helloserver.js command in command prompt or
terminal window and it will display message of node.js is running of port no. 8081.
19 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
res.end();
res.end();
res.end();
else
res.end('Invalid Request!');
});
20 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
In Node.js, functionality to aid in the accessing of URL query string parameters is built into
the standard library. The built-in url.parse method takes care of most of the heavy lifting for
us. Here is an example script using this handy function and an explanation on how it works:
console.log(queryObject);
}).listen(8080);
To test this code run node app.js (app.js is name of the file) on the terminal and then go to
your browser and type http://localhost:8080/app.js?foo=bad&baz=foo on the URL bar.
The key part of this whole script is this line: const queryObject =
url.parse(req.url,true).query;. Let's take a look at things from the inside-out. First off, req.url
will look like /app.js?foo=bad&baz=foo. This is the part that is in the URL bar of the browser.
Next, it gets passed to url.parse which parses out the various elements of the URL (NOTE: the
second parameter is a boolean stating whether the method should parse the query
string, so we set it to true). Finally, we access the .query property, which returns us a nice,
friendly JavaScript object with our query string data.
The url.parse() method returns an object which have many key value pairs one of which is
the query object. Some other handy information returned by the method include host,
pathname, search keys.
21 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
Another way to access query string parameters is parsing them using the querystring builtin
Node.js module.
This method, however, must be passed just a querystring portion of a url. Passing it the
whole url, like you did in the url.parse example, won't parse the querystrings.
const qs = "code=string&key=12&id=false";
console.log(querystring.parse(qs));
console.log(querystring.parse(url));
This module, as the name suggests, enables developers to work with the file system on its
computers. The require() method is used to include the File System module. Some of the
most common uses of this module is to create, read, update, delete, rename or read files.
For example, the function fs.readFile() is used to read files on the computer.
The Node.js file system module (fs module) allows you to work with the files. The
fs.readFile() is used to read from file.
var fs = require('fs');
if (err){
throw err;
}else{
22 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
});
var fs = require('fs');
There are a bunch of methods used for creating new files are: fs.appendFile (), fs.open (),
fs.writeFile ().
The append method is used to, as the name suggests, append the given file. Also, if one
particular file is appended but does not exist then a file of the same name will be created.
The syntax of fs.appendFile () would look something like -
console.log('Done!');
});
The next method to discuss is the fs.open() method. This method takes a "flag" as the
second argument. If the flag is "w", the specified file is opened for writing and if the called
file does not exist then an empty file is created. The syntax of the fs.open() method will look
like
console.log('Done!');
});
If you want to replace a particular file and its contents then the fs.writeFile() method is
used. lso, if the file doesn’t already exist, a new one will be created.
23 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
console.log('Saved!');
});
Apart from these methods included in the file system module of Nodejs, there are a couple
of other methods included too. Let’s look at some of them and understand the concept in
detail.
The methods generally used to update files in a system are fs.appendFile() and fs.writeFile().
fs.appendFile() is a method that appends particular content at the end of the file mentioned
in the code. The syntax for the method fs.appendFile() would look like -
console.log('Updated!');
});
This code would append the text "This is my text." to the end of the file that goes by the
name "newfile1.txt".
Another method is the fs.writeFile() one which replaces the file and content mentioned in
the code. The syntax of the method is:
console.log('Replaced!');
});
The code above replaces the content of the file "newfile3.txt": There are methods to delete
files too.
The fs.unlink() method is used to delete a particular file with the File System module. The
syntax of this method will look like -
24 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]
});
In Nodejs, developers can also upload files to their computer. Apart from this, the file
system module can also be used to rename files. The fs.rename() method is used to rename
a file. This method renames the file mentioned in the code, the syntax for the same will look
like -
console.log('File Renamed!');
});
Also keep in mind that all the methods mentioned above is prefixed with a variable fs. In
these examples above, we took the variable to be ‘fs’, while executing your code, you would
have to explicitly mention it in your code. The code will look something like - var fs =
require('fs');
25 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana