0% found this document useful (0 votes)
9 views65 pages

Web Tech Lab Manual 5th Sem

The document is a manual for the Web Technology Laboratory course at CMR Institute of Technology, detailing various lab experiments for students. It includes tasks such as creating HTML pages, developing CSS styles, implementing JavaScript functions, and using PHP and jQuery for web applications. Additionally, it provides explanations of HTML elements, document structure, and styling techniques essential for web development.

Uploaded by

gowdasrinidhi11
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)
9 views65 pages

Web Tech Lab Manual 5th Sem

The document is a manual for the Web Technology Laboratory course at CMR Institute of Technology, detailing various lab experiments for students. It includes tasks such as creating HTML pages, developing CSS styles, implementing JavaScript functions, and using PHP and jQuery for web applications. Additionally, it provides explanations of HTML elements, document structure, and styling techniques essential for web development.

Uploaded by

gowdasrinidhi11
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

Web Technology Laboratory-BCSL504

CMR INSTITUTE OF TECHNOLOGY


#132 AECS Layout, ITPL Main Road, Kundalahalli, Bengaluru – 37

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING LAB

MANUAL
WEB TECHNOLOGY LABORATORY

SEMESTER – V

Subject Code: BCSL504

Lab Experiments:

1. Develop the HTML page named as “[Link]”. Add the following tags with relevant
content.
1. Set the title of the page as “My First Web Page”
2. Within the body use the following tags:
a) Moving text = “Basic HTML Tags”
b) Different heading tags (h1 to h6)
c) Paragraph
d) Horizontal line
e) Line Break
f) Block Quote
g) Pre tag
h) Different Logical Style (<b>, <u>, <sub>, <sup> etc.)

2. Develop the HTML page named as “[Link]” to display your class time table.
a) Provide the title as Time Table with table header and table footer, row-span and col-span etc.
b) Provide various colour options to the cells (Highlight the lab hours and elective hours with different
colours.)
c) Provide colour options for rows.

3. Develop an external style sheet named as “[Link]” and provide different styles for h2, h3, hr, p, div,
span, time, img & a tags. Apply different CSS selectors for tags and demonstrate the significance of
each.

4. Develop HTML page named as “[Link]” having variety of HTML input elements with
background colors, table for alignment & provide font colors & size using CSS styles.
Web Technology Laboratory-BCSL504

5. Develop HTML page named as “[Link]” having variety of HTML semantic elements with
background colors, text-colors & size for figure, table, aside, section, article, header, footer… etc.

6. Apply HTML, CSS and JavaScript to design a simple calculator to perform the following operations:
sum, product, difference, remainder, quotient, power, square-root and square.

7. Develop JavaScript program (with HTML/CSS) for:


a) Converting JSON text to JavaScript Object
b) Convert JSON results into a date
c) Converting From JSON To CSV and CSV to JSON
d) Create hash from string using [Link]() method

8. a. Develop a PHP program (with HTML/CSS) to keep track of the number of visitors visiting the web
page and to display this count of visitors, with relevant headings.
b. Develop a PHP program (with HTML/CSS) to sort the student records which are stored in the
database using selection sort.

9. Develop jQuery script (with HTML/CSS) for:


a. Appends the content at the end of the existing paragraph and list.
b. Change the state of the element with CSS style using animate() method
c. Change the color of any div that is animated.

10. Develop a JavaScript program with Ajax (with HTML/CSS) for:


a. Use ajax() method (without Jquery) to add the text content from the text file by sending ajax request.
b. Use ajax() method (with Jquery) to add the text content from the text file by sending ajax request.
c. Illustrate the use of getJSON() method in jQuery
d. Illustrate the use of parseJSON() method to display JSON values.
Web Technology Laboratory-BCSL504

1) Explanation :

• HTML is defined as a markup language.


• Allow users to control how text and visual elements will be laid out and displayed
• XHTML in 1990’s had stricter syntax rules
• HTML validators verified a web page’s markup
• HTML 5 – 2009
• Specify unambiguously how browsers should deal with invalid markup.
• Provide an open, nonproprietary programming framework (via JavaScript) for
creating rich web applications.
• Be backwards compatible with the existing web.
• HTML documents are composed of textual content and HTML elements
• HTML element is often used interchangeably with the term tag.
• A tag consists of the element name within angle brackets
• The element name appears in both the beginning tag and the closing tag
• An empty element does not contain any text content; instead, it is an instruction to the browser
to do something

DOM (Document Object Model) - It is nested


It is used by CSS and Javascript for parsing the HTML pages

HEADINGS

• HTML provides six levels of heading (h1 through h6), with the higher heading number
indicating a heading of less importance
• Headings are also used by the browser to create a document outline for the page.
• The browser has its own default styling for each heading level. However, these are easily
modified and customized via CSS
• specify a heading level that is semantically accurate
• choose the heading level because it is
• appropriate (e.g., choosing <h3> because it is a third-level heading and not a primary or
secondary heading).

Structure of HTML Documents

• <title> element plays an important role in search engine optimization (SEO), that is, in
improving a page’s rank (its position in the results page after a search) in most search engines.
• DOCTYPE (short for Document Type Definition)
• HTML pages are divided into two sections: the head and the body, which correspond to the
<head> and <body> element
• <meta> character encoding for the document is UTF-8.

<marquee> Lets Move this text.</marquee> Headings


• HTML provides six levels of heading (h1 through h6), with the higher heading number
indicating a heading of less importance

Headings are also used by the browser to create a document outline for the page

• The browser has its own default styling for each heading level. However, these are easily modified
and customized via CSS
• specify a heading level that is semantically accurate
• choose the heading level because it is
• appropriate (e.g., choosing <h3> because it is a third-level heading and not a primary or secondary
heading).
Web Technology Laboratory-BCSL504

Paragraphs, Divisions, Line breaks


• <p> tag is a container and can contain HTML and other inline HTML elements - refers to HTML
elements that do not cause a paragraph break but are part of the regular “flow” of the text
• <br/> : The line break element forces a line break. It is suitable for text whose content belongs in
a single paragraph but which must have specific line breaks:
• The <div> element has no intrinsic presentation; it is frequently used in contemporary CSS-based
layouts to mark out sections.
• Use the <hr> tag to define thematic changes in the content:

Blockquote
• The <blockquote> tag specifies a section that is quoted from another source.
• Browsers usually indent <blockquote> elements
• Tip: Use <q> for inline (short) quotations.
• Cite URL Specifies the source of the quotation

<pre>
• The <pre> tag defines preformatted text.
• Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and
line breaks. The text will be displayed exactly as written in the HTML source code.
• Defaults :
pre {
display: block;
font-family: monospace;
white-space: pre;
margin: 1em 0;
}
• The <code> tag is used to define a piece of computer code. The content inside is displayed
in the browser's default monospace font.

Styles
• The <b> tag specifies bold text without any extra importance.
• The <strong> tag is used to define text with strong importance. The content inside is typically
displayed in bold.
• The <i> tag defines a part of text in an alternate voice or mood. The content inside is typically
displayed in italic.
• The <em> tag is used to define emphasized text. The content inside is typically displayed
in italic.
• The <sup> tag defines superscript text.
• The <sub> tag defines subscript text.
• The <u> tag represents some text that is unarticulated and styled differently from normal text. The
content inside is typically displayed with an underline.

Source code :

<html>
<title>My First Web Page</title>
<body>
<marquee>Basic HTML tags</marquee>
<h1>1st level heading</h1>
<h2>I am in Bengaluru</h2>
<h3>I am in CMRIT</h3>
<h4>We are 5th sem students</h4>
<h5>Bengaluru is the capital city of Karnataka</h5>
<h6>Jai Hind</h6>
<p>
India plays many games like cricket, hockey, football, badminton and many more but our national
game is Hockey. Dhanraj Pillai is considered one of the best hockey players team India has seen.
Web Technology Laboratory-BCSL504
</p>
<hr/>
<br/>
<blockquote cite="[Link] <!-- This HTML element defines an indented
block of text -->
The lion is a large cat of the genus Panthera, native to Africa and India. It has a muscular, broad-
chested body; a short, rounded head; round ears; and a dark hairy tuft at the tip of it's tail. Adult male
lions are larger than females and have a prominent mane. It is a social species, forming groups called
prides.
</blockquote>
<pre> <!-- This HTML element defines pre-formatted text to preserve spaces & line breaks-->
Jack and Jill went up the hill
To fetch a pail of water.
Jack fell down and broke his crown,
And Jill came tumbling after
</pre>
<b>Who are you</b>
<u>Some underlined text</u>
H<sub>2</sub>O
a<sup>2</sup>+b<sup>2</sup> = c<sup>2</sup>
</body>
</html>

Output :

2) Explanation :

To create a table in HTML, we use the below syntax

<table>
<tr>
<th></th>
Web Technology Laboratory-BCSL504

<th></th>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>

Here,

The <table> tag is used to create a table


<tr> tag is used to create a row in a table
<th> tag is used to add headings to a table
<td> tag is used to add data to a table cell
</table> is the closing table tag

Referring to the below code,


- rowspan is an attribute of the td tag inside of the table tag which is used to merge multiple
rows into a single column. In the below code, we have used rowspan for Short break and
Lunch break to merge 6 rows into 1 column.
- colspan is another attribute of the td tag inside of the table tag which does the opposite,
meaning it is used to merge multiple columns into a single row. In the below code, we
have used colspan for 1 hr 45 mins continuous lab on a particular day to merge 2 columns
into 1 row (and) to indicate Sunday is a holiday.

Source code :

<!DOCTYPE html>
<html>
<head>
<title>Time Table</title>
<style>
table {
border:solid 1pt black;
border-collapse: collapse;
}

td,th {
border:solid 1pt black;
padding: 5pt;
text-align: center;
}

.lab {
background-color: azure;
}

thead, th{
background-color: lightgray;
}
Web Technology Laboratory-BCSL504

caption{
border: solid 1pt black;
padding: 5pt;
background-color: aliceblue;
color:crimson;
font-weight: bold;
}

tfoot {
background-color: lavender;
color:brown;
font-weight:bolder;
}
</style>
</head>
<body>
<h1> Timetable </h1>
<table>
<caption>My class timetable</caption>

<thead>
<!--<tr style="background-color:lavender">
<td colspan="10">My class timetable</td>
</tr>-->
<tr>
<th>Time/Day</th>
<th>8:30 am - 9:30 am</th>
<th>9:30 am - 10:30 am</th>
<th></th>
<th>10:45 am - 11:30 am</th>
<th>11:30 am - 12:30 pm</th>
<th></th>
<th>1:15 pm - 2:15 pm</th>
<th>2:15 pm - 3 pm</th>
<th>3 pm - 4 pm</th>
</tr>
</thead>
<tbody>
<tr>
<th>Monday</th>
<td>Maths</td> <td>DMS</td><td rowspan="6">Short Break (10:00 - 10:20 am)</td>
<td colspan="2">Unix</td><td rowspan="6">Lunch Break
(12:20 - 1:15 pm)</td><td>Electronic Circuits</td>
<td colspan="2">DS</td>
</tr>
<tr>
<th>Tuesday</th>
<td>Electronic Circuits</td> <td>DS</td><td class="lab">DS</td>
<td>Unix</td><td>Logic Design</td>
<td colspan="2">DS</td>
</tr>
<tr>
<th>Wednesday</th>
<td colspan="2">Unix</td>
<td colspan="2" class="lab">EC & LD</td>
<td>Maths</td>
Web Technology Laboratory-BCSL504

<td colspan="2">DMS</td>
</tr>
<tr>
<th>Thursday</th>
<td>Maths</td> <td>Unix</td>
<td colspan="2" class="lab">DS</td>
<td>DMS</td>
<td colspan="2">Electronic Circuits</td>
</tr>
<tr>
<th>Friday</th>
<td colspan="2">DMS</td>
<td colspan="2">Unix</td><td>Electronic Circuits</td>
<td colspan="2" class="lab">EC & LD</td>
</tr>
<tr>
<th>Saturday</th>
<td colspan="2">Maths</td> <td colspan="2">Electronic Circuits</td>
<td>DMS</td><td colspan="2" class="lab">DS</td>
</tr>
<tr>
<th>Sunday</th>
<td colspan="10">Holiday</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="10">&copy; 2024-2025 Department of CSE</td>
</tr>
</tfoot>
</table>

</body>
</html>
Web Technology Laboratory-BCSL504

Output :

3) Explanation :

<h2> and <h3> are the 2nd level and 3rd level heading tags which displays the text in bold. h2 has a
bigger font size than h3.
<hr> tag is used to draw a horizontal line on the browser
<p> tag is used to create a paragraph having some text.
<div> tag is used to create a division in the document, meaning divide the document into multiple
parts.
<span> tag is used to highlight a particular word in a sentence or a paragraph
<time> tag is used to display the time.
<img> tag is used to display an image according to the specified attributes.
<link> tag is used to link your HTML file with a stylesheet
<a> tag is used to create a hyperlink to navigate to another page on the browser.

HTML file source code :

<html>
<title>Demo of different HTML Tags</title>
<link rel="stylesheet" href="[Link]" />
<body>
<h2 id="a1">Windows, Linux and Mac are examples of OSs</h2>
<h3 class="b2">Blood group O+ is called universal donor</h3>
<hr id="lineprop">
<p id="paras">This is the 1st para. This is the 2nd para.</p>
<div id="myDiv">
<h2>Formula 1</h2>
<p>Michael Schumacher - Ferrari</p>
</div>
There are approx <span class="elephnum">30,000</span> elephants in India<br/>
I need to meet my friend @ <time class="meeting">12:15</time> pm<br>
<img src="C:\\Users\\prateek\\Pictures\\Saved Pictures\\[Link]" width="200"
height="100" id="pic" alt='Image absent' /><br/><br>
Watch Youtube videos <a href="[Link] target="_blank"
id="remunder">here</a>
Web Technology Laboratory-BCSL504

</body>
</html>

CSS file source code :

#a1
{
color: blue;
}

.b2 { text-decoration: underline; }

#paras
{
color: #00c400;
}

#myDiv
{
border: 3px outset yellow;
background-color: green;
text-align: center;
}

.elephnum {
color: red;
}

.meeting
{
margin-left: 20px;
}

#pic
{
margin-left: 100px;
}

#remunder
{
text-decoration: none;
}

#lineprop
{
width: 300px;
border-color: #fedcba;
}
Web Technology Laboratory-BCSL504

Output :

4) Explanation :

We can use the <form> tag to create a form in HTML. Inside the <form> tag, we use different input
types like textbox, calendar, dropdown etc etc to take inputs from the user.

We also provide validations to prevent the user from submitting an invalid form.
Web Technology Laboratory-BCSL504

Source code :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form </title>
<style>
#container{
background-color: #E2F1E7;
color:#243642;
width: 95%;
border: solid 1pt black;
margin:auto;
padding: 10px;
}

form{
background-color:#629584;
padding: 10px;
}
Web Technology Laboratory-BCSL504

label{
color: #E2F1E7;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-weight: 200px;
}

input{
padding: 10px;
width:200px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
border-radius:10px;
}

input[type=checkbox]{
width:30px;
}

input[type=submit],input[type=reset] {
margin:10px;
background-color:#DA8359;
color:#030303;
}

input:focus{
background-color: #FCFAEE;
}

select{
border-color:#243642;
background-color:#E2F1E7;
}

</style>
</head>
<body>
<div id="container">

<h1>Registration Form</h1>
<form name="registration" action="#" method="get">
<table>
<tr>
<td><label for="usn">USN</label></td>
<td><input id="usn" type="text" required /></td>
</tr>
<tr>
<td><label for="uname">User Name</label></td>
<td><input id="uname" name="uname" type="text" required /></td>
</tr>
<tr>
<td><label for="pswd">Password</label></td>
<td><input id="pswd" name="pswd" type="password" required /></td>
</tr>
<tr>
<td><label for="bday">Birthday</label></td>
<td><input name="bday" type="date" required /></td>
</tr>
Web Technology Laboratory-BCSL504

<tr>
<td><label for="city">Select city</label></td>
<td><select id="city" name="city" required>
<option value=''>Select a city</option>
<optgroup label="Karnataka">
<option>Bengaluru</option>
<option>Ballari</option>
<option>Hassan</option>
<option>Raichur</option>
<option>Hubballi</option>
</optgroup>
<optgroup label="Tamil Nadu">
<option>Chennai</option>
<option>Trichy</option>
<option>Madhurai</option>
<option>Vellore</option>
<option>Salem</option>
</optgroup>
</select>
</td>
</tr>
<tr>
<td><label for="plang">Select programming languages you know</label></td>
<td><input name="plang" type="checkbox" value="C" />C<br/>
<input name="plang" type="checkbox" value="Java" />Java<br/>
<input name="plang" type="checkbox" value="Python" />Python<br/></td>
</tr>
<tr>
<td><label for="mypic">Upload a Photo</label></td>
<td><input id="mypic" name="mypic" type=file required /></td>
</tr>
<tr>
<td><label for="pskill">Rate your programming skills in Web Technology</label></td>
Web Technology Laboratory-BCSL504

<td><input id="pkill" name="pskill" type="range" required min="1" max="10" step="1" /></td>


</tr>

<tr>
<td><label for="fcolor">Choose your favorite color</label></td>
<td><input id="fcolor" name="fcolor" type="color" /></td>
</tr>

<tr>
<td colspan="2"><input name="submit" type="submit" /><input type="reset" /></td>
</tr>
</table>
</form>
</div>

</body>
</html>
Web Technology Laboratory-BCSL504

Outputs :

(Trying to submit an empty form)

(After entering the first 2 fields)


Web Technology Laboratory-BCSL504

(On clearing the form by pressing the “Reset” button)

(On entering a form with necessary data)


Web Technology Laboratory-BCSL504

(On submitting the form by pressing the “Submit” button)

5) Explanation :

<figure> tag is used to specify self-contained content.


<table> tag is used to create a 2d matrix of rows and columns with headings (if required).
<aside> tag is used to define content apart from the page content.
<section> tag is used to define a section in the document. There can be any number of
sections in a document.
<article> tag is used to define an article. One article can have multiple sections.
<header> tag is used to define a header for a document or a section.
<footer> tag is used to define a footer for a document or a section.

Source code :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Newspaper</title>
<style>
#container{
width:95%;
overflow: auto;
margin:auto;
background-image: linear-gradient(#AB886D, #E4E0E1);
}

header{

text-align: center;
Web Technology Laboratory-BCSL504

nav ul{
list-style-type:none;
margin:0;padding:0;
background-color: #333;
overflow: hidden;
}

nav li{
float:left;
}

nav li a {
display: block;
text-decoration: none;
color:white;
padding: 15px 13px;
text-align:center;
}

nav li a:hover{
background-color: #888;
}

section{
width:68%;
margin:5px;
float:left;
padding: 5px;
border: solid 1pt black;
background-color: #AB886D;
}

aside{
display: inline-block;
margin:5px;
padding: 5px;
width:28%;
position:inherit;
border:solid 1pt black;
vertical-align: top;
}

footer{
margin-top:10px;
width:95%;
margin:auto;
height:30px;
background-color:#E2BFB3;
text-align: center;
}

figure{
float:left;
Web Technology Laboratory-BCSL504

margin-top:0;
margin-right:10px;
border-radius:5px;
border: solid 1pt black;
background-color:#AB886D;
}

figcaption{
text-align: center;
color:#EDDFE0;
font-weight:bold;
}

article{
height:200px;
overflow: auto;
text-align: justify;
background-color: #E4E0E1;
margin:5px;
padding: 5px;
}

h1, h2,h3{
color:#493628;
text-shadow: 1px 1px #D6C0B3;
}

aside{
border: dotted 2px #D6C0B3;
background-image: radial-gradient(#E2BFB3,#AB886D );
}

a{
text-shadow: none;
}

ul{
list-style: square;
}

hgroup {
background-color: #EDDFE0;
}
</style>
</head>
<body>
<div id="container">
<header>
<img src="[Link]" alt="The times of India" width="500px"/>
<nav role="navigation">
<ul>
<li><a href="#">City</a></li>
<li><a href="#">World</a></li>
<li><a href="#">Business</a></li>
<li><a href="#">Tech</a></li>
<li><a href="#">Cricket</a></li>
Web Technology Laboratory-BCSL504

</ul>

</nav>
</header>

<section>
<h2>Latest News</h2>
<article>
<h3>How Cyclone Dana, expected to hit Odisha, got its name</h3>
<figure>
<img src="[Link]" alt="cyclone" width=200px />
<figcaption>Cyclone Dana</figcaption>
</figure>
Named by Saudi Arabia, Dana means 'generosity.' The cyclone is predicted to
intensify and approach the Odisha-West Bengal coast by October [Link] Dana, a tropical
cyclone that formed in the Indian Ocean, is expected to cause heavy rains in Odisha in the coming
days. But have you ever wondered how cyclones get their names?
</article>
<article>

<h3>‘I won the Oscars, but now, who cares?’: AR Rahman no longer feels the need to
prove himself</h3>
<figure>
<img src="[Link]" alt="ar rahman" width="200px" />
<figcaption>A R Rahman</figcaption>
</figure>
Music composer AR Rahman has delivered numerous hits in Tamil, Hindi, Telugu,
Malayalam, English, and other languages since the 1990s. In an interview with The Week, he says
that he’s not only prioritising projects that ‘bring him joy’.
Rahman told the publication that he ‘no longer feels the need to prove himself’ and
that he’s selecting big-budget films and non-film projects that ‘satisfy his creative instincts.’ He said,
“I won the Oscars (Jai Ho, Slumdog Millionaire) a long time ago, but now, who cares? I am doing
work that is close to me and will inspire future generations.” The music composer who once had the
drive to set himself apart seems to have slowed down.
</article>

</section>
<section id="tech">
<h2>Technology</h2>
<article>
<h3>Can artificial intelligence rescue customer service?</h3>
<figure>
<img src="[Link]" alt="AI" width="200px"/>
<figcaption>Artificial Intelligence</figcaption>
</figure>
It’s not easy being a customer service agent—particularly when those customers are
so angry with a product that they want to yell at you on the phone. That’s the sort of rage that Sonos,
a maker of home audio systems, encountered in May when it released an app update so full of
glitches it caused its share price to plunge.
</article>
<article>
<h3>Best smart locks for main door: Top 10 options to enhance security and
convenience for your home</h3>
<figure>
<img src="[Link]" alt="Smart Locks" width="200px"/>
<figcaption>Smart Locks</figcaption>
Web Technology Laboratory-BCSL504

</figure>
Smart locks offer advanced security features for your main door, providing keyless
entry, app control, and fingerprint access. With a variety of options available, it's essential to find the
best smart lock that suits your specific requirements. In this article, we'll explore the top 10 smart
locks on the market, comparing their features, pros, and cons to help you make an informed decision
for your home security needs.
</article>

</section>
<section id="Entertainment">
<h2>Entertainment</h2>
<article>
<h3>Why was Liam Payne dropped by his music label just days before his death?
Shocking details emerge</h3>
<figure>
<img src="[Link]" alt="liam" width="200px" />
<figcaption>Liam Payne</figcaption>
</figure>
Earlier it was reported that Liam Payne was quietly dropped by his music label,
Universal just a day before his tragic death. The sources claimed that the label dropped him as they
were under the fear that the kind of music he wanted to produce would not be loved by his one-
direction fan base. Payne died at the age of 31 on Wednesday, October 16 after an unfortunate fall
from the third-floor balcony of his hotel room in Buenos Aires, Argentina.
</article>

<article>
<h3>Gladiator 2 early reactions: Critics single out Denzel Washington's performance
worthy of another Oscar
</h3>
<figure>
<img src="[Link]" alt="Gladiator" width="200px" />
<figcaption>Gladiator</figcaption>
</figure>
The first reactions to Gladiator 2- one of the most anticipated films of the year- are
here and they are overwhelmingly positive. Lead actor Paul Mescal- who plays Lucius, the son of
Lucilla in the film, introduced the screening at Los Angeles which was attended by a selected few
critics. Most of them gave favourable reviews of the film and predicted that it would play very well
at the awards season- with special note for Denzel Washington's supporting turn.
</article>

</section>
<aside>
<hgroup>

<h3><a href="#">TOI Exclusive Stories</a></h3>


<h3><a href="#tech">Technology</a></h3>
<h3><a href="#Entertainment">Entertainment</a></h3>
</hgroup>

<figure>
<img src="[Link]" alt="success quote" width="250px"/>
</figure>
<figure>
<img src="[Link]" alt="quotes" width="250px"/>
</figure>
Web Technology Laboratory-BCSL504

<figure>
<img src="quotes [Link]" alt="quotes" width="250px" />
</figure>

</aside>
</div>

<footer>
@psh | Department of CSE | 2024-2025
</footer>

</body>
</html>

Outputs :
Web Technology Laboratory-BCSL504
Web Technology Laboratory-BCSL504

(On clicking the Technology link from the right side of the page, jump to the “Technology”
section)

(On clicking the Entertainment link from the right side of the page, jump to the
“Entertainment” section)
Web Technology Laboratory-BCSL504

6) Explanation :

In this program, we are creating 2 textboxes to enter 2 numbers and 8 buttons to perform 8 different
operations like sum, difference, etc etc. Validations are done to ensure that if both numbers are
entered, only then the operation is performed (Except for square and square root operations, which
require only 1 input).

onclick is an attribute/event for button which is fired on clicking the button.

<input type=”text”> is used to create a textbox


<input type=”button”> is used to create a button

parseFloat() - is a Javascript function which converts a String to a floating-point value

toFixed(n) - is a Javascript function which is used to limit the number of digits n after the decimal
point.

HTML file source code :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple calculator</title>

<style type="text/css">
#number1, #number2
{
font-family: Verdana;
font-size: 14px;
color: blueviolet;
}

#btn1,#btn2,#btn3,#btn4,#btn5,#btn6,#btn7,#btn8
{
font-family: Georgia;
font-size: 15px;
background-color: turquoise;
}

#res
{
display: none;
}
</style>
<script type="text/javascript" src="[Link]"></script>
</head>
<body>
<h1>Simple calculator demo</h1>
<input id="number1" placeholder="Enter the 1st number" autofocus /><br><br>
<input id="number2" placeholder="Enter the 2nd number" /><br><br><br>

<input type="button" id="btn1" value="Sum" onclick="find_sum()" />&emsp;


<input type="button" id="btn2" value="Difference" onclick="find_diff()" />&emsp;
<input type="button" id="btn3" value="Product" onclick="find_product()" />&emsp;
Web Technology Laboratory-BCSL504

<input type="button" id="btn4" value="Quotient" onclick="find_quot()" /><br><br>


<input type="button" id="btn5" value="Remainder" onclick="find_rem()" />&emsp;
<input type="button" id="btn6" value="Power" onclick="find_power()" />&emsp;
<input type="button" id="btn7" value="Square root" onclick="find_sqrt()" />&emsp;
<input type="button" id="btn8" value="Square" onclick="find_sq()" />

<br><br><br>

<div id="res"></div>
</body>
</html>

Javascript file [Link] source code

function find_sum()
{
var num1 = parseFloat([Link]("number1").value);
var num2 = parseFloat([Link]("number2").value);

if([Link]("number1").value == "")
{
alert("Hey, enter the 1st number");
[Link]("number1").focus();
}

else if([Link]("number2").value == "")


{
alert("Hey, enter the 2nd number");
[Link]("number2").focus();
}

else
{
var sum = num1+num2;

[Link]("res").[Link] = "block";

[Link]("res").innerHTML = [Link]("number1").value + " + " +


[Link]('number2').value + " = " + sum;
}
}

function find_diff()
{
var num1 = parseFloat([Link]("number1").value);
var num2 = parseFloat([Link]("number2").value);

if([Link]("number1").value == "")
{
alert("Hey, enter the 1st number");
[Link]("number1").focus();
}

else if([Link]("number2").value == "")


{
Web Technology Laboratory-BCSL504

alert("Hey, enter the 2nd number");


[Link]("number2").focus();
}

else
{
var minus = num1-num2;

[Link]("res").[Link] = "block";

[Link]("res").innerHTML = [Link]("number1").value + " - " +


[Link]('number2').value + " = " + minus;
}
}

function find_product()
{
var num1 = parseFloat([Link]("number1").value);
var num2 = parseFloat([Link]("number2").value);

if([Link]("number1").value == "")
{
alert("Hey, enter the 1st number");
[Link]("number1").focus();
}

else if([Link]("number2").value == "")


{
alert("Hey, enter the 2nd number");
[Link]("number2").focus();
}

else
{
var prod = num1*num2;

[Link]("res").[Link] = "block";

[Link]("res").innerHTML = [Link]("number1").value + " * " +


[Link]('number2').value + " = " + prod;
}
}

function find_quot()
{
var num1 = parseFloat([Link]("number1").value);
var num2 = parseFloat([Link]("number2").value);

if([Link]("number1").value == "")
{
alert("Hey, enter the 1st number");
[Link]("number1").focus();
}
Web Technology Laboratory-BCSL504

else if([Link]("number2").value == "")


{
alert("Hey, enter the 2nd number");
[Link]("number2").focus();
}

else if([Link]("number2").value == 0)
{
alert("Hey, enter a non-zero denominator to calculate quotient");
[Link]("number2").focus();
}

else
{
var quot = (num1/num2).toFixed(4);

[Link]("res").[Link] = "block";

[Link]("res").innerHTML = [Link]("number1").value + " / " +


[Link]('number2').value + " = " + quot;
}
}

function find_rem()
{
var num1 = parseInt([Link]("number1").value);
var num2 = parseInt([Link]("number2").value);

if([Link]("number1").value == "")
{
alert("Hey, enter the 1st number");
[Link]("number1").focus();
}

else if([Link]("number2").value == "")


{
alert("Hey, enter the 2nd number");
[Link]("number2").focus();
}

else if([Link]("number2").value == 0)
{
alert("Hey, enter a non-zero denominator to calculate remainder");
[Link]("number2").focus();
}

else
{
var remainder = num1%num2;

[Link]("res").[Link] = "block";

[Link]("res").innerHTML = [Link]("number1").value + " % "


+ [Link]('number2').value + " = " + remainder;
}
Web Technology Laboratory-BCSL504

function find_power()
{
var num1 = [Link]("number1").value;
var num2 = [Link]("number2").value;

if([Link]("number1").value == "")
{
alert("Hey, enter the 1st number");
[Link]("number1").focus();
}

else if([Link]("number2").value == "")


{
alert("Hey, enter the 2nd number");
[Link]("number2").focus();
}

else
{
var powres = [Link](num1,num2).toFixed(4);

[Link]("res").[Link] = "block";

[Link]("res").innerHTML = [Link]("number1").value +
"<sup>" + [Link]('number2').value + "</sup> = " + powres;
}
}

function find_sqrt()
{
var num1 = [Link]("number1").value;

if([Link]("number1").value == "")
{
alert("Hey, enter the 1st number");
[Link]("number1").focus();
}

else
{
var sqrtres = [Link](num1).toFixed(4);

[Link]("res").[Link] = "block";

[Link]("res").innerHTML = "Square root of " +


[Link]("number1").value + " = " + sqrtres;
}
}
Web Technology Laboratory-BCSL504

function find_sq()
{
var num1 = [Link]("number1").value;

if([Link]("number1").value == "")
{
alert("Hey, enter the 1st number");
[Link]("number1").focus();
}

else
{
var squareres = num1 * num1;

[Link]("res").[Link] = "block";

[Link]("res").innerHTML = [Link]("number1").value + "


<sup>2</sup> = " + squareres;
}
}

Outputs :

Initial screen
Web Technology Laboratory-BCSL504

On entering only the 1st number

On entering only the 2nd number


Web Technology Laboratory-BCSL504

After calculating sum

After calculating difference


Web Technology Laboratory-BCSL504

After calculating quotient

After calculating square root of a negative number

7) Explanation :

 JSON is a data serialization format


 Represent object data in a text format so that it can be transmitted from one computer to another
 Many REST web services encode their returned data in the JSON data format instead of XML
Web Technology Laboratory-BCSL504

 While JSON stands for JavaScript Object Notation, its use is not limited to JavaScript
 Provides a more concise format than XML to represent data
 Advantage of generally requiring significantly fewer bytes to represent data than XML
JSON information will be contained within a string, and the [Link]() function can be used to transform the
string containing the JSON data into a JavaScript object

 the [Link]() method is used to create output to the HTML page from JavaScript.

 Element node object : represents the HTML element in the hierarchy.


getElementById(id) Returns the element node whose id attribute matches the passed id parameter

Parsing dates
Date objects are not allowed in JSON. To parse dates, use the below code

const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';


const obj = [Link](text);
[Link] = new Date([Link]);

[Link]("demo").innerHTML = [Link] + ", " + [Link];

Formatting dates in Javascript – options

 day:
The representation of the day.
Possible values are "numeric", "2-digit".

 year:
The representation of the year.
Possible values are "numeric", "2-digit".

 month:
The representation of the month.
Possible values are "numeric", "2-digit", "narrow", "short", "long".
 "en-US": For American English
 "en-GB": For British English
 "hi-IN": For Hindi

The toLocaleString() method of Date instances returns a string with a language-sensitive representation of this date
in the local timezone
Web Technology Laboratory-BCSL504

JSON to CSV and CSV to JSON


CSV stands for Comma-Separated Values

 var, const, let

 var – can be global scoped or function scoped, can be redclared.


 let – improvement of var. It is block scoped and cannot be redeclared
 const – it cannot be updated and required a value to be assigned.
 [Link]() – static method that returns objects own enumerable string-keyed property names.
 map() – holds key like objects
 join() - converts an array to a string, default separator is “,”

 push() - appends item to end of the array.

JSON to CSV
Example

var jsonData=[{
"id":1,
"usn":"1RN21EC001",
"sname":"Sharan",
"semester":5,
"dept":"ECE"
},
{"id":2,
"usn":"1RN21EC002",
"sname":"Kashyap",
"semester":5,
"dept":"ECE"
}
];

1. Create a sample jsonData


2. Create a variable csv.
3. Pass the first record (jsonData[0]) to [Link]() to obtain the headers.

4. Convert the array to a comma separated string using join(), store in csv
5. Loop through each records and map the value to each of the keys in the headers variable and store in values.
Convert the values array to a comma separated string using join(), store in csv
Web Technology Laboratory-BCSL504

CSV to JSON

Example

[{"id":"1","usn":"1RN21EC001","sname":"Sharan","semester":"5","dept":"ECE"},{"id":"2","usn":"1RN21E
C002","sname":"Kashyap","semester":"5","dept":"ECE"}]

1. Split on new lines


2. Set headers to the first row

3. For each of the rows with data


1. Obtain the key and value pair for each key in the header and store it in an object
2. Push each object to an array holding the jsonData

Create hash from string using [Link]() Nodejs method

 Hashing is often used to store passwords, create digital signatures and verify data integrity
 Crypto can be used to generate various types of hashes like SHA1 (Secure Hash Algorithm), MD5 (Message
Digest), SHA256
 Syntax: [Link]( algorithm, options )

 Using Javascript:
 [Link](index)

HTML file source code (Using [Link]() method)


<html>
<head>
<title>Create hash from string in JS</title>
<style>
#str, .genhashbtn
{
font-family: Tahoma;
font-size: 18px;
}

#result
{
display: none;
}
</style>
</head>
<body>
<h2>Create hash from the input string</h2>
<input type="text" id="str" autofocus placeholder="Enter a string">&emsp;
<input type="button" class="genhashbtn" value="Create Hash" onclick="genHash()" /><br/><br>

<p id="result"></p>
</body>
</html>
Web Technology Laboratory-BCSL504

<script type="text/javascript">
function genHash()
{
var inp = [Link]('str').value

if(inp == "")
{
alert("Please enter a string")
[Link]("str").focus()
return false
}

else
{
[Link]("result").[Link] = "block"
createHash(inp).then(hash=>[Link]("result").innerHTML = "<b>64-length hash for string
"+inp+" created using the 256 bits Secure Hash Algorithm : </b>" + hash)

//createHash(inp).then(hash => [Link](hash));


}
}

async function createHash(input) {


const encoder = new TextEncoder();
const data = [Link](input);
const hashBuffer = await [Link]('SHA-256', data);
const hashArray = [Link](new Uint8Array(hashBuffer));
const hashHex = [Link](b => [Link](16).padStart(2, '0')).join('');
return hashHex;
}
</script>

HTML file source code (Without using [Link]() method)


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS, JSON, Date, CSV, Create hash from string</title>
<style>
div
{
width:600px;
height:150px;
border:solid 1pt burlywood;
padding: 15px;
margin:10px;
}
</style>
</head>
<body>
<h1>JS, JSON, CSV</h1>
<h2>Converting JSON text to Javascript Object </h2>
<div id="jsonToJS"></div>
Web Technology Laboratory-BCSL504

<h2>Converting JSON result to Date </h2>


<div id="jsonDate"></div>

<h2>Converting JSON to CSV</h2>


<button style="margin-left: 10px" onclick="jsonToCSV()">Convert JSON TO CSV </button>
<button onclick="CSVtojson()" disabled id="btnCsvToJson"> Convert CSV to JSON</button>
<div id="jsonCSV"></div>

<h2>Generating hash using Crypto</h2>

<label for="ipStr">Enter a string to hash: </label>


<input type="text" id="ipStr" />&emsp;
<button onclick="hash()">Generate Hash</button><br>
<div id="taHash"></div>

<script>
var text = '{"course":{"code":"BCSL504","cname":"Web Tech Lab"}}';
var a = [Link](text);

[Link]("jsonToJS").innerHTML=[Link];
[Link]("jsonToJS").innerHTML+="<br>"+[Link];

var text='{"cname":"Driver License Validity","start_date":"2007-03-10","end_date":"2017-03-10"}';


var c = [Link](text);

c.start_date = new Date(c.start_date);


c.end_date = new Date(c.end_date);

var options = { year: "numeric", month: 'long', day: 'numeric' };

[Link]("jsonDate").innerHTML=c.start_date.toLocaleDateString("en-gb",options);
[Link]("jsonDate").innerHTML+="<br>"+c.end_date.toLocaleDateString("en-us",options);

function jsonToCSV (){


var jsonData=[{
"id":1,
"usn":"1CR21CS001",
"sname":"Anna",
"semester":5,
"dept":"CSE"
},

{
"id":2,
"usn":"1CR21EC003",
"sname":"Max",
"semester":5,
"dept":"ECE"
},

{
"id":3,
"usn":"1PE21EC010",
Web Technology Laboratory-BCSL504

"sname":"Shankar",
"semester":3,
"dept":"ECE"
}
];

let csv='';
const headers = [Link](jsonData[0]);
csv+=[Link]()+"\n";

[Link](obj => {
const values = [Link](header =>obj[header]);
csv+=[Link]() +"\n";
});
[Link]("jsonCSV").innerHTML=csv;
[Link]("btnCsvToJson").disabled = false;
}

function CSVtojson()
{
csv = [Link]("jsonCSV").[Link]();
const rows = [Link]("\n");
const headers = rows[0].split(",");
const jsonData=[];
for(let i=1;i<[Link];i++){
const values=rows[i].split(",");
const obj={};
for(let j=0; j<[Link];j++ ){
const key = headers[j];
const value=values[j];
obj[key]=value;
}

[Link](obj);
}
[Link]("jsonCSV").innerHTML=[Link](jsonData);
[Link]("btnCsvToJson").disabled = true;
}

function hash(){
const a = [Link]("ipStr").value;

if(a == "")
{
alert("Enter a string first");
[Link]("ipStr").focus();
}

else
{
let hash=0;
for(i=0;i<[Link];i++){
char = [Link](i)
hash=((hash<<5) - hash) + char;
Web Technology Laboratory-BCSL504

hash=hash&hash;
}
[Link]("taHash").innerHTML=hash;
}
}
</script>
</body>
</html>

Outputs :

Initial screen (Part 1)


Web Technology Laboratory-BCSL504

Initial screen (Part 2)

On converting JSON to CSV


Web Technology Laboratory-BCSL504

On converting CSV to JSON

Generate hash for string “ac” (without using [Link]() method)


Web Technology Laboratory-BCSL504

Generate hash for string “ac” (using [Link]() method)

8) Explanation of Program 8a

PHP

o A server-side script can access any resources made available to it by the server
o Data storage resources, web services, and software applications
o Apache runs as a daemon on the server
Web Technology Laboratory-BCSL504

Apache, Linux and PHP

Lampp server

Click on Files
Go to Other locations
Select My computer
Double click on the “opt” directory  then double click on “lampp” directory” 
Then double click on the “htdocs” directory
Open a new terminal and go to the path /opt/lampp/htdocs

Create a text file (for example [Link]) using the below command
- sudo touch [Link]

Give write permissions to the above mentioned text file using the below command
- sudo chmod 777 [Link]

Open the text file [Link] and enter a value 0. Save and close the file

Create a PHP file (for example [Link]) using the below command
- sudo touch [Link]

Give write permissions to the above mentioned PHP file using the below command
- sudo chmod 777 [Link]

Open the file [Link] in a text editor like VS Code and type the following code
Web Technology Laboratory-BCSL504

PHP file source code (8a)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visitors count</title>
</head>
<body>
<h1>Welcome to my page</h1>
<hr>
<footer>
<?php
$counter_name = "[Link]";

$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
$counterVal+=1;
$f = fopen($counter_name,"w");
fwrite($f,$counterVal);
fclose($f);
?>
<em style='color:blue; font-size:30px'>No. of visitors: <?php echo $counterVal; ?> </em>
</footer>
</body>
</html>

To start the Lampp server, use the below command


- sudo /opt/lampp/lampp start

Outputs

Initital screen
Web Technology Laboratory-BCSL504

Text file current count

On refreshing the page, visitor count gets increased


Web Technology Laboratory-BCSL504

Text file current count

Explanation of Program 8b

Database Connection

Go to any browser and type the URL [Link]

 phpMyAdmin allows developers to access management tools through a web portal


 Create database – sample
 Create table - tblstudent

Insert some data into the table tblstudent in mixed USN order.

PHP, MySQL

1. Connect to the database.

2. Handle connection errors.


3. Execute the SQL query.
4. Process the results.
5. Free resources and close connection.

mysqli_connect() function opens a new connection to the MySQL server.


Web Technology Laboratory-BCSL504

Parsing records

 mysqli_query(connection, query) - Perform query against a database

 mysqli_fetch_all – with argument MYSQLI_ASSOC


 Fetch all rows and return the result-set as an associative array
$query=mysqli_query($con,"select * from tblstudent");
$students= mysqli_fetch_all ($query, MYSQLI_ASSOC);
 mysqli connect_errno()
 Return an error code from the last connection error, if any
 To fetch row by row
$result=mysqli_query($con,“select * from tblstudent");
while($result=mysqli_fetch_array($result))
{ …}

Selection Sort
Time Complexity = O(n2)

 First we find the smallest element and swap it with the first element. This way we get the smallest element at its
correct position.

 Then we find the smallest among remaining elements (or second smallest) and move it to its correct position by
swapping.

 We keep doing this until we get all elements moved to correct position.

PHP file source code (8b)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sort student records</title>
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME','sample');

$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
Web Technology Laboratory-BCSL504
// Check connection
if (mysqli_connect_errno())
{
echo "<h2 style='color:red'>Failed to connect to MySQL: " . mysqli_connect_error()."</h2>";
}
?>
<style>
table {
border-collapse:collapse;
}

table, td,th {
border:solid 1pt black;
padding:5px;
}
th{
background-color:#e3e3e3;
}
</style>
</head>
<body>
<h1>Student Records</h1>
<h2>Before sorting </h2>
<?php
$query=mysqli_query($con,"select * from tblstudent");
$students= mysqli_fetch_all ($query, MYSQLI_ASSOC);
?>
<table>
<tr>
<th> Sl. No. </th>
<th> USN </th>
<th> Name</th>
<th> Department </th>
</tr>

<?php for($i=0; $i<sizeof($students);$i++){ ?>


<tr>
<td><?php echo $i+1; ?></td>
Web Technology Laboratory-BCSL504
<td><?php echo $students[$i]["USN"]; ?></td>
<td><?php echo $students[$i]["Name"]; ?></td>
<td><?php echo $students[$i]['department']; ?></td>
</tr>
<?php } ?>
</table>

<?php
for($i=0; $i<sizeof($students);$i++){
$minUSN = $i;
for($j=$i+1;$j<sizeof($students);$j++){
if($students[$j]["USN"] < $students[$i]["USN"]) {
$minUSN = $j;
}
} // end inner for loop
//swap
$temp = $students[$i];
$students[$i] = $students[$minUSN];
$students[$minUSN] = $temp;
}
?>
<h2>After sorting - Selection Sort </h2>
<table>
<tr>
<th> Sl. No. </th>
<th> USN </th>
<th> Name</th>
<th> Department </th>
</tr>

<?php
$query2=mysqli_query($con,"select * from tblstudent order by 2 asc");
$students2= mysqli_fetch_all ($query2, MYSQLI_ASSOC);

for($i=0; $i<sizeof($students2);$i++){ ?>


<tr>
<td><?php echo $i+1; ?></td>
<td><?php echo $students2[$i]["USN"]; ?></td>
Web Technology Laboratory-BCSL504

<td><?php echo $students2[$i]["Name"]; ?></td>


<td><?php echo $students2[$i]["department"]; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>

Outputs :
(Records before sorting and after sorting)
Web Technology Laboratory-BCSL504

(Table structure in phpMyAdmin database)

(Data stored in phpMyAdmin database)


Web Technology Laboratory-BCSL504

9) Explanation :

jQuery :

 Dates back to 2005, founder- John Resig

 Initially started to combine CSS selectors with succinct JS notation


 It added more libraries
 The jQuery library contains the following features:
 HTML/DOM manipulation
 CSS manipulation
 HTML event methods
 Effects and animations
 AJAX
 Utilities

How to use jQuery ?

 Download [Link]

 <head>
<script src="[Link]"></script>
</head> (as a file)

 [OR]
 <head>
<script src="[Link]
</head> (as a CDN or Content Delivery Network)
 $(document).ready() – ensures the page is loaded before attaching listeners to them.

jQuery selectors

 Basic selectors
 $("*") Universal selector
 $("tag") Element selector
 $(".class") Class selector
$("#id") Id selector

Creating DOM (Document Object Model) and text nodes

 To create a <div> element, var element = $("<div></div>");


 append() adds to the end of the selected element
 prepend() adds to the beginning of the selected element
Web Technology Laboratory-BCSL504

 An event represents the precise moment when something happens. Examples:


 moving a mouse over an element
 selecting a radio button
 clicking on an element
 $(document).ready() method allows us to execute a function when the document is fully loaded.
$("p").click(function(){
$(this).hide();
});

animate()

 performs a custom animation of a set of CSS properties

 changes an element from one state to another with CSS styles


 (selector).animate({styles},speed,easing,callback)
 Styles - Specifies one or more CSS properties/values to animate.
 Eg. margin, padding, borderWidth, fontSize

 Speed – default: 400 ms, “slow”, “fast”


 Easing – optional
 default: “swing” moves slower at the beginning/end, but faster in the middle
 linear" - moves in a constant speed
 Callback – optional, a function that is executed

HTML file source code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="[Link]"></script>

<script src="[Link]"></script>
<title>Append content, change the state and change the colour</title>
Web Technology Laboratory-BCSL504

</head>
<body>
<h1> JQuery </h1>
<h2>Append content to end of paragraph and list</h2>
<button id="btnAppend">Append Demo</button>
<p id="aboutjq"> jQuery dates back to 2005</p>
<ul id="featuresjq">
<li>HTML/DOM manipulation</li>
<li> CSS manipulation</li>
</ul>
<script>
$("#btnAppend").click(function(){
$("#aboutjq").append("<br> Prime minister of India: ");
$("#featuresjq").append("<li>Shri Narendra Modi</li>");
});

</script>
<h2>Change the state of CSS style element </h2>
<button id="btnGrow">Animate Text - Increase Size</button>
<button id="btnShrink">Animate Text - Decrease Size</button>
<div id="animText">Shark</div>
<script>
$("#btnGrow").click(function() {
$("#animText").animate({
"opacity":0.25,
"fontSize":"+=4px"
});
});
$("#btnShrink").click(function() {
$("#animText").animate({
"opacity":1,
"fontSize":"-=4px"
});
});
</script>
<h2>Change the color of any div that is animated</h2>
<input type="color" id="ipColor" />
<button id="btnColor">Change color</button>
<div id="foo" style="width:200px; height:150px; border:solid 1pt black;margin:10px; margin-left: 1px"></div>
<script>
$("#btnColor").click(function() {
$("#foo").animate({ backgroundColor: $("#ipColor").val()},"slow");
});
</script>
</body>
</html>
Web Technology Laboratory-BCSL504

Outputs :

Initial screen

(On clicking the “Append Demo” button)


Web Technology Laboratory-BCSL504

(On clicking the “Animate Text – Increase Size” button)

(On clicking the “Animate Text – Decrease Size” button)


Web Technology Laboratory-BCSL504

(On selecting a color and clicking the “Change color” button)

(On selecting another color and clicking the “Change color” button)
Web Technology Laboratory-BCSL504

10) Explanation :

AJAX

 Asynchronous JavaScript with XML (AJAX)

 allows a web browser to send messages back to the server without interrupting the flow of what’s being shown
in the browser

UML Sequence diagram


Web Technology Laboratory-BCSL504

Illustration of jQuery call

Reading file from a server

By sending asynchronously, 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 after the response is ready

 var xhr = new XMLHttpRequest();

 Creates an instance of XMLHttpRequest


 open(method, url, async) - Specifies the type of request
 method: the type of request: GET or POST
 url: the server (file) location
 async: true (asynchronous) or false (synchronous)
 The readystatechange event is fired whenever the readyState property of the XMLHttpRequest changes.
 readyState: 4: request finished and response is ready status: 200: "OK“
 When readyState is 4 and status is 200, the response is ready

 send() Sends the request to the server (used for GET)


Web Technology Laboratory-BCSL504

 send(string) Sends the request to the server (used for POST)

jQuery Listeners

 An event represents the precise moment when something happens. Examples:


 moving a mouse over an element
 selecting a radio button
 clicking on an element
 $(document).ready() method allows us to execute a function when the document is fully loaded.
 $("p").click(function(){
$(this).hide();
});

Meaning of $.ajax

 $.ajax({name:value, name:value, ... })


 url - Specifies the URL to send the request to. Default is the current page
 success(result,status,xhr) - A function to be run when the request succeeds
xhr - function used for creating the XMLHttpRequest object

getJSON()

 The getJSON() method in jQuery fetches JSON-encoded data from the server using a GET HTTP request.

 $(selector).getJSON(url,data,success(data,status,xhr))
 Parameters: This method accepts three parameters as mentioned above and described below:
 url: It is a required parameter. It is used to specify the URL in the form of a string to which the request is
sent
 data: It is an optional parameter that specifies data that will be sent to the server.
 callback: It is also an optional parameter that runs when the request succeeds.

 Return Value: It returns XMLHttpRequest object.

parseJSON()

 parseJSON() method in jQuery takes a well-formed JSON string and returns the resulting JavaScript value.

 Return Value:
 It returns the following:
 String
 Number

 Object
 Array
Web Technology Laboratory-BCSL504

 Boolean

HTML file source code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="[Link]"></script>
<title>Last program</title>
<style type="text/css">
div
{
border: solid 1pt brown;
width: 500px;
height: 150px;
margin: 10px;
padding: 10px;
}
</style>
</head>
<body>
<!-- Use ajax() method (without Jquery) to add the text content from the text file by sending ajax request. -->
<h1>AJAX & jQuery</h1>
<h2>Load Text file using AJAX without jQuery</h2>
<button onclick="loadDoc()">Change Content</button>
<div id="loadText"></div>

<script>
function loadDoc() {
var xhr = new XMLHttpRequest();
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
[Link]("loadText").innerHTML = [Link];
}
};

[Link]("get", "[Link]", false);


[Link]();
}
</script>

<h2>Load Text file using AJAX with jQuery</h2>


<button id="btnLoad">Change Content using jQuery</button>
<div id="loadjqText"></div>
<script>
$("#btnLoad").click(function(){
$.ajax({url: "[Link]", success: function(result){
$("#loadjqText").html(result);
}});
});
</script>
<h2>getJSON in jQuery</h2>
<button id="btnGetJson">GetJSON content </button>
Web Technology Laboratory-BCSL504

<div id="studentInfo"></div>

<script>
$("#btnGetJson").click(function(){
$.getJSON('[Link]',function(result) {
$("#studentInfo").html("<b>Name:</b> "+result[0].sname);
$("#studentInfo").append("<br> <b>USN:</b> "+result[0].usn);
$("#studentInfo").append("<br> <b>Department:</b> "+result[4].department);
});
});
</script>

<h2>parseJSON in jQuery</h2>
<button id="btnParseJson">ParseJson </button>
<div id="courseInfo"></div>

<script>
$("#btnParseJson").click(function(){
let txt = '[{"name":"Web Technologies Lab", "code":"BCSL504"}, {"name":"CG Lab", "code":"CGL501"}]'
let obj = [Link](txt);
$("#courseInfo").html("Name: "+obj[1].name);
$("#courseInfo").append("<br> Code: "+obj[1].code);
});
</script>
</body>
</html>

Outputs :

Initial screen (Part 1)


Web Technology Laboratory-BCSL504

Initial screen (Part 2)

(On clicking the “Change Content” button)


Web Technology Laboratory-BCSL504

(On clicking the “Change Content using jQuery” button)

(On clicking the “GetJSON content” button)


Web Technology Laboratory-BCSL504

(On clicking the “ParseJson” button)

-------------------------------------------------- THE END--------------------------------------------------------

You might also like