Imp Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

No.22/1,Opp.,ManyataTechParkRd,Nagawara,Bengaluru,Karnataka560045.

ApprovedbyAICTE&Afflictedto VTU

DEPT. OF COMPUTER SCIENCE &ENGINEERING

WEB TECHNOLOGY
MANUAL

AY: 2024–25
ODD Semester

SubName: WEBTECHNOLOGY LAB


SubCode: BCSL504

Designed by:
Prof. Krishna Meena
wee

WEB TECHNOLOGY LAB


Teaching Learning Plan

Course Code BCSL504 CIE Marks 50


Teaching Hours/Week(L:T:P:S) 0:0:2:0 SEE Marks 50
Total Hours of Pedagogy 50 Total Marks 100
Credits 01 Exam Hours 03

Pre-requisite:
Students need logical reasoning, programming in Object Oriented Concepts,
and high level languages Java.

Course Objectives:
 Learn HTML elements and their uses.
 Use of CSS for enhanced user interface presentation.
 Gain Knowledge of JavaScript, AJAX, and JQuery for dynamic presentation.
 Use of PHP to build web applications.
 Design and develop Websites and Web Applications.

Course Outcomes (Course Skill Set)

At the end of the course the student will be able to:

Sl. Course Description Bloom’s


No Outcome TaxonomyLevel
1. CO1 Design the experiment for the given problem using
HTML,Javascript and CSS
2. CO2 Develop the solution for the given real world problem using
Jquery,Ajax and PHP.
Analyze the results and produce substantial written
3. CO3 documentation.
wee

ProgrammeOutcomes(POs)andProgrammeSpecificOutcomes(PSOs)

PO 1 EngineeringKnowledge:Applyknowledgeofmathematics,science,engineeringfundamentalsanda
nengineeringspecializationtothesolutionofcomplexengineeringproblems.

PO 2 ProblemAnalysis:Identify,formulate,researchliteratureandanalyzecomplexengineeringproblems
reachingsubstantiatedconclusionsusingfirstprinciplesofmathematics,natural
sciencesandengineeringsciences.
PO 3 Design/DevelopmentofSolutions:Designsolutionsforcomplexengineeringproblemsanddesignsys
temcomponentsorprocessesthatmeetspecifiedneedswithappropriate
considerationforpublichealthandsafety,cultural,societalandenvironmentalconsiderations.
PO 4 Conduct investigations of complex problems using research-based knowledge and
researchmethods including design of experiments, analysis and interpretation of data and
synthesis ofinformationto provide valid conclusions.
PO 5 Modern Tool Usage: Create, select and apply appropriate techniques, resources and
modernengineeringandITtoolsincludingpredictionandmodelingtocomplexengineeringactivitieswit
hanunder-standingofthelimitations.
PO 6 The Engineer and Society: Apply reasoning informed by contextual knowledge to
assesssocietal, health, safety, legal and cultural issues and the consequent responsibilities
relevant toprofessionalengineeringpractice.
PO 7 EnvironmentandSustainability:Understandtheimpactofprofessionalengineeringsolutionsinsocie
talandenvironmentalcontextsanddemonstrateknowledgeofandneedfor
sustainabledevelopment.
PO 8 Ethics:Applyethicalprinciplesandcommittoprofessionalethicsandresponsibilitiesandnormsofengi
neering practice.
PO 9 Individual and Team Work: Function effectively as an individual, and as a member or
leaderindiverseteams and inmulti-disciplinary settings.
PO 10 Communication:Communicateeffectivelyoncomplexengineeringactivitieswiththeengineering
community and with society at large, such as being able to comprehend and writeeffective
reports and design documentation, make effective presentations and give and
receiveclearinstructions.
PO 11 Life-
longLearning:Recognizetheneedforandhavethepreparationandabilitytoengageinindependentan
d life-longlearning in thebroadest context oftechnological change.
PO 12 Project Management and Finance: Demonstrate knowledge and understandingof
engineeringandmanagementprinciplesandapplythesetoone’sownwork,asamemberandleaderin
ateam,to manageprojects andin multidisciplinary environments.
PSO1 Problem-Solving Skills: An ability to investigate and solve a problem by
analysis,interpretation of data, design and implementation through appropriate
techniques, toolsand skills.
PSO2 ProfessionalSkills:Anabilitytoapplyalgorithmicprinciples,computingskillsandcomputerscienceth
eory in the modelling anddesign of computer-based systems.
PSO3 EntrepreneurialAbility: Anabilitytoapplydesign,developmentprinciplesand
management skillsintheconstruction of softwareproductof varyingcomplexitytobecome
anentrepreneur.
wee

CO-PO/PSO Mapping:

Distribution of CIE Marks is a follows(Total50Marks):


20 Marks through IA Tests
30 Marks(Conduction and Execution) through practical assessment
wee

Program List

1 Develop the HTML page named as “Myfirstwebpage.html”. 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 “Table.html” 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 “style.css” 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 “registration.html” having variety of HTML input elements with
background

colors, table for alignment & provide font colors & size using CSS styles.

5 Develop HTML page named as “newpaper.html” 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


wee

b) Convert JSON results into a date


c) Converting From JSON To CSV and CSV to JSON
d) Create hash from string using crypto.createHash() 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.
Web Technology- BCSL504

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- BCSL504
Web Technology- BCSL504

PROGRAM -1
Develop the HTML page named as "Myfirstwebpage.html".Add the following tags with
relevant content.
a. Set the title of the page as "My First Web Page"
b. Within the body use the following tags:
i. Moving text="Basic HTML Tags"
ii. Different Heading tags(h1 to h6)
iii. Paragraph
iv. Horizontal line
v. Line break
vi. Block quote
vii. Pre tag
viii.Different Logical Style(<b>,<u>,<sub><sup>etc.)

SOURCE CODE

<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>Heading Level 1</h1>
<p>It is the largest and typically represents the most important section of your content.</p>
<h2>Heading Level 2</h2>
<p>It is used for subsections under the main heading.</p>
<h3>Heading Level 3</h3>
<p>It is used for subsections under the level 2 heading.</p>
<h4>Heading Level 4</h4>
<p>It provides further subdivision under the level 3 heading.</p>
<h5>Heading Level 5</h5>
<p>It is used for more specific sections under the level 4 heading.</p>
<h6>Heading Level 6</h6>
Web Technology- BCSL504

<p>It is the smallest heading and typically represents the least important section of your
content.</p>
<h1>Horizontal Line and Line Break Example</h1>
<hr>
<p>HELLO</p>
<p><b><u>WELCOME TO HKBK COLLEGE OF
ENGINEERING</u></b><sup>Estd:1997</sup><br>
<p>WELCOME TO CSE DEPARTMENT</p>
<blockquote>HKBK College of Engineering is affiliated to Visvesvaraya Technological
University and approved by All India Council for Technical Education,
New Delhi.
</blockquote>
</body>
</html>
Web Technology- BCSL504

OUTPUT
Web Technology- BCSL504

PROGRAM-2
Develop the HTML page named as "Table.html" to display your class timetable.
a. Provide the title as Time Table with table header and table footer,row-span and
col-span
b. Provide various color options to the cells (Highlight the lab hours and elective
hours with different colours.)
c. Provide colour options for rows.

SOURCE CODE

<html>
<head>
<title>Timetable</title>
</head>
<header>w.e.f 10-08-2024</header>
<body>
<h1 align="center"><font color="ORANGE">Timetable of III
CSE</font></h1><br>
<table align="center" border="2" cellspacing="0" cellpadding="15">
<tr align="center" valign=="middle">
<th>DAY</th>
<th>I</th>
<th>II</th>
<th
rowspan="7"><b>T<br>E<br>A<br><br>B<br>R<br>E<br>A<br>K</b></th>
<th>III</th>
<th>IV</th>
<th
rowspan="7"><b>L<br>U<br>N<br>C<br>H<br><br>B<br>R<br>E<br>A<br>K</
b></th>
<th>V</th>
<th>VI</th>
<th>VII</th>
</tr>
<tr align="center">
<th><font color="BLUE">MON</th>
<td colspan="2"><b><font color="PURPLE">DS LAB</td>
<td>MATHS</td>
<td>OS</td>
<td>OOPS</td>
<td colspan="2">SPORTS</td>
</tr>
<tr align="center">
Web Technology- BCSL504

<th><font color="MAGENTA">TUE</th>
<td>CO</td>
<td>DS</td>
<td colspan="2"><b><font color="PURPLE">DS LAB</td>
<td colspan="2">SCR</td>
<td>MENTORING</td>
</tr>
<tr align="center">
<th><font color="PURPLE">WED</th>
<td>MATHS</td>
<td>DS</td>
<td>OS</td>
<td>CO</td>
<td colspan="2"><b><font color="PURPLE">DS LAB</td>
<td>REMEDIAL</td>
</tr>
<tr align="center">
<th><font color="GREEN">THU</th>
<td>CO</td>
<td>MATHS</td>
<td>DS</td>
<td>OOPS</td>
<td colspan="2">Skill enhancement</td>
<td>LIBRARY</td>
</tr>
<tr align="center">
<th><font color="BROWN">FRI</th>
<td>OS</td>
<td>CO</td>
<td>MATHS</td>
<td>OOPS</td>
<td colspan="2"><b><font color="RED">OS LAB</td>
<td>VAC</td>
</tr>
<tr align="center">
<th><font color="BLACK">SAT</th>
<td colspan="2">AS PER COE</td>
<td colspan="2">AS PER COE</td>
<td colspan="3">AS PER COE</td>
</tr>
</table>
</body>
</html>
Web Technology- BCSL504

OUTPUT
Web Technology- BCSL504

PROGRAM-3
Develop an external style sheet named as "style.css" 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.

SOURCE CODE
/* externalstyles.html */
<!DOCTYPE html>
<html lang="en">
<head>
<title>External Stylesheet Demo</title>
<link rel="stylesheet" href="styles3.css">
</head>
<body>
<header>
<h1>Welcome to the Styling Demo</h1>
<h2>Subheading Level 2</h2>
<h3>Subheading Level 3</h3>
</header>
<p>This is a paragraph element. It demonstrates how external styles can change text
color, font, and spacing.</p>
<div>
<span>This is a span element inside a div. It can be styled differently from other
text.</span>
</div>
<date todaysdate="2024-09-11">September 11, 2024</date>
<img src="rose.jpg" alt="roseflower Image">
</body>
</html>
Web Technology- BCSL504

/*styles3.css */
/* General styles for body */
body {
font-family: Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 20px;
}

/* Styling for h2 elements */


h2 {
color: #007BFF;
font-size: 1.5em;
border-bottom: 2px solid #007BFF;
padding-bottom: 5px;
}

/* Styling for h3 elements */


h3 {
color: #6C757D;
font-size: 1.2em;
margin-top: 10px;
font-style: italic;
}
/* Styling for p elements */
p{
Web Technology- BCSL504

font-size: 1em;
color: #444;
margin: 10px 0;
}
/* Styling for div elements */
div {
background-color:YELLOW;
padding: 10px;
border-radius: 5px;
}
/* Styling for span elements */
span {
color: #28A745;
font-weight: bold;
}
/* Styling for time elements */
date {
font-style:bold italic;
color: BLUE;
}
/* Styling for img elements */
img {
max-width: 50%;
height: auto;
border: 2px;
border-radius: 5px;
display: block;
Web Technology- BCSL504

margin-top: 10px;
}

OUTPUT
Web Technology- BCSL504

PROGRAM-4
Develop HTML page named as "registration.html" having variety of HTML input
elements with background colors,table for alignment and provide font colors and sizes
using CSS styles.

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>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
text-align: center;
}
table {
width: 100%;
max-width: 600px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
td {
padding: 10px;
}
label {
color: #555;
Web Technology- BCSL504

font-weight: bold;
}
input[type="text"], input[type="email"], input[type="password"],
select, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
font-size: 16px;
}
input[type="radio"], input[type="checkbox"] {
margin-right: 5px;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 18px;
}
input[type="submit"]:hover {
background-color: #45a049;
}
.error {
color: #ff0000;
font-size: 14px;
}
</style>
</head>
<body>
<h1>Registration Form</h1>
<form action="#" method="post">
<table>
<tr>
<td><label for="fullname">Full Name:</label></td>
<td><input type="text" id="fullname" name="fullname"
required></td>
Web Technology- BCSL504

</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="email" id="email" name="email"
required></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" id="password" name="password"
required></td>
</tr>
<tr>
<td><label for="confirm_password">Confirm
Password:</label></td>
<td><input type="password" id="confirm_password"
name="confirm_password" required></td>
</tr>
<tr>
<td><label>Gender:</label></td>
<td>
<input type="radio" id="male" name="gender" value="male"
required>
<label for="male">Male</label>
<input type="radio" id="female" name="gender"
value="female" required>
<label for="female">Female</label>
<input type="radio" id="other" name="gender" value="other"
required>
<label for="other">Other</label>
</td>
</tr>
<tr>
<td><label for="birthdate">Date of Birth:</label></td>
<td><input type="date" id="birthdate" name="birthdate"
required></td>
</tr>
<tr>
<td><label for="country">Country:</label></td>
<td>
<select id="country" name="country" required>
Web Technology- BCSL504

<option value="">Select a country</option>


<option value="usa">India</option>
<option value="uk">United Kingdom</option>
<option value="canada">Canada</option>
<option value="australia">Australia</option>
<option value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td><label for="interests">Interests:</label></td>
<td>
<input type="checkbox" id="sports" name="interests[]"
value="sports">
<label for="sports">Sports</label>
<input type="checkbox" id="music" name="interests[]"
value="music">
<label for="music">Music</label>
<input type="checkbox" id="reading" name="interests[]"
value="reading">
<label for="reading">Reading</label>
<input type="checkbox" id="travel" name="interests[]"
value="travel">
<label for="travel">Travel</label>
</td>
</tr>
<tr>
<td><label for="bio">Bio:</label></td>
<td><textarea id="bio" name="bio" rows="4"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" value="Register">
</td>
</tr>
</table>
</form>
</body>
</html>
Web Technology- BCSL504

OUTPUT
Web Technology- BCSL504

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

SOURCE CODE

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Chronicle</title>
<style>
body {
font-family: 'Georgia', serif;
line-height: 1.6;
color: #333;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f4f4f4;
}
header {
background-color: #1a1a1a;
color: #fff;
padding: 20px;
text-align: center;
}
header h1 {
margin: 0;
font-size: 2.5em;
}
nav {
Web Technology- BCSL504

background-color: #333;
color: #fff;
padding: 10px;
}
nav ul {
list-style-type: none;
padding: 0;
margin: 0;
display: flex;
justify-content: center;
}
nav ul li {
margin: 0 10px;
}
nav ul li a {
color: #fff;
text-decoration: none;
}
main {
display: flex;
margin-top: 20px;
}
section {
flex: 2;
margin-right: 20px;
}
article {
background-color: #fff;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
article h2 {
color: #1a1a1a;
font-size: 1.8em;
}
aside {
flex: 1;
background-color: #e6e6e6;
padding: 20px;
Web Technology- BCSL504

box-shadow: 0 0 10px rgba(0,0,0,0.1);


}
figure {
margin: 0;
text-align: center;
}
figure img {
max-width: 100%;
height: auto;
}
figcaption {
font-style: italic;
color: #666;
font-size: 0.9em;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 10px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
footer {
background-color: #1a1a1a;
color: #fff;
text-align: center;
padding: 10px;
margin-top: 20px;
}
</style>
</head>
<body>
<header>
<h1>The Chronicle</h1>
Web Technology- BCSL504

</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Politics</a></li>
<li><a href="#">Technology</a></li>
<li><a href="#">Sports</a></li>
<li><a href="#">Entertainment</a></li>
</ul>
</nav>
<main>
<section>
<article>
<h2>Breaking News: Major Technological Breakthrough</h2>
<p>Scientists have announced a groundbreaking discovery in the
field of quantum computing, potentially revolutionizing the tech industry.</p>
<figure>
<img
src="https://www.cnet.com/a/img/resize/c7cb26e927bebaa784fb55a01e71d7fec
b15d2e3/hub/2019/06/26/3f76e99d-8055-46f3-8f27-558ee276b665/20180405-
ibm-q-quantum-computer02.jpg?auto=webp&fit=crop&height=675&width=1200"
alt="Quantum
Computer">
<figcaption>A state-of-the-art quantum computer at the research
facility</figcaption>
</figure>
</article>
<article>
<h2>Local Sports Team Wins Championship</h2>
<p>In a thrilling match, our local team secured victory in the
national championship, bringing pride to our city.</p>
<table>
<tr>
<th>Team</th>
<th>Score</th>
</tr>
<tr>
<td>Local Heroes</td>
<td>3</td>
</tr>
Web Technology- BCSL504

<tr>
<td>Visiting Challengers</td>
<td>2</td>
</tr>
</table>
</article>
</section>
<aside>
<h3>Weather Update</h3>
<p>Expect sunny skies with a high of 75°F (24°C) today.</p>
<h3>Upcoming Events</h3>
<ul>
<li>City Festival - This Weekend</li>
<li>Tech Conference - Next Month</li>
<li>Charity Run - In Two Weeks</li>
</ul>
</aside>
</main>
<footer>
<p>&copy; 2023 The Chronicle. All rights reserved.</p>
</footer>
</body>
</html>
Web Technology- BCSL504

OUTPUT
Web Technology- BCSL504

PROGRAM-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.

SOURCE CODE

/* index.html */
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<div class="display">
<input type="text" id="display" readonly>
</div>
<div class="buttons">
<button onclick="clearDisplay()">C</button>
<button onclick="appendToDisplay('1')">1</button>
<button onclick="appendToDisplay('2')">2</button>
<button onclick="appendToDisplay('+')">+</button>
<button onclick="appendToDisplay('3')">3</button>
<button onclick="appendToDisplay('4')">4</button>
<button onclick="appendToDisplay('-')">-</button>
Web Technology- BCSL504

<button onclick="appendToDisplay('5')">5</button>
<button onclick="appendToDisplay('6')">6</button>
<button onclick="appendToDisplay('*')">*</button>
<button onclick="appendToDisplay('7')">7</button>
<button onclick="appendToDisplay('8')">8</button>
<button onclick="appendToDisplay('/')">/</button>
<button onclick="appendToDisplay('%')">%</button>
<button onclick="appendToDisplay('**')">^</button>
<button onclick="calculate()">=</button>
<button onclick="appendToDisplay('sqrt(')">√</button>
<button onclick="appendToDisplay('^2')">x²</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>

/* styles.css */
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
font-family: Arial, sans-serif;
}
Web Technology- BCSL504

.calculator {
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
background-color: #fff;
padding: 20px;
}

.display {
margin-bottom: 10px;
}

#display {
width: 100%;
height: 40px;
text-align: right;
font-size: 20px;
padding: 10px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
}

.buttons {
display: grid;
Web Technology- BCSL504

grid-template-columns: repeat(4, 1fr);


gap: 10px;
}

button {
padding: 15px;
font-size: 18px;
border: none;
border-radius: 5px;
background-color: #007bff;
color: #fff;
cursor: pointer;
transition: background-color 0.3s ease;
}

button:hover {
background-color: #0056b3;
}
// script.js
function clearDisplay() {
document.getElementById('display').value = '';
}

function appendToDisplay(value) {
const display = document.getElementById('display');
display.value += value;
}
Web Technology- BCSL504

function calculate() {
let expression = document.getElementById('display').value;

// Replace square root and square with appropriate JavaScript operations


expression = expression.replace(/sqrt\(/g, 'Math.sqrt(').replace(/\^2/g, '**2').replace(/\^/g, '**');

try {
let result = eval(expression);
if (result === undefined || result === Infinity || isNaN(result)) {
throw new Error('Invalid operation');
}
document.getElementById('display').value = result;
} catch (e) {
document.getElementById('display').value = 'Error';
}
}
Web Technology- BCSL504

OUTPUT
Web Technology- BCSL504

PROGRAM-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 crypto.createHash() method

SOURCE CODE

json_operations.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON and Hash Operations</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f2f2f2;
}
h2 {
color: #333;
}
textarea, input, button {
width: 100%;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: 1px solid #ccc;
font-size: 16px;
}
pre {
Web Technology- BCSL504

background-color: #333;
color: #fff;
padding: 15px;
border-radius: 5px;
}
</style>
</head>
<body>

<h2>Convert JSON Text to JavaScript Object</h2>


<textarea id="jsonText" placeholder='Enter JSON text, e.g. {"name": "John", "age":
30}'></textarea>
<button onclick="convertJSONtoObject()">Convert to Object</button>
<pre id="objectResult"></pre>

<h2>Convert JSON to Date</h2>


<textarea id="jsonWithDate" placeholder='Enter JSON with date, e.g. {"date": "2024-09-
12T10:20:30Z"}'></textarea>
<button onclick="convertJSONToDate()">Convert to Date</button>
<pre id="dateResult"></pre>

<h2>Convert JSON to CSV</h2>


<textarea id="jsonForCSV" placeholder='Enter JSON for CSV, e.g. [{"name": "John", "age":
30}, {"name": "Jane", "age": 25}]'></textarea>
<button onclick="convertJSONToCSV()">Convert to CSV</button>
<pre id="csvResult"></pre>

<h2>Convert CSV to JSON</h2>


<textarea id="csvText" placeholder='Enter CSV text, e.g.
name,age\nJohn,30\nJane,25'></textarea>
<button onclick="convertCSVToJSON()">Convert to JSON</button>
<pre id="jsonFromCSVResult"></pre>

<h2>Create Hash from String (Node.js)</h2>


<input type="text" id="hashString" placeholder="Enter string to hash">
<button onclick="createHash()">Generate Hash</button>
<pre id="hashResult"></pre>

<script>
// 1. Convert JSON Text to JavaScript Object
Web Technology- BCSL504

function convertJSONtoObject() {
const jsonText = document.getElementById("jsonText").value;
try {
const jsObject = JSON.parse(jsonText);
document.getElementById("objectResult").textContent = JSON.stringify(jsObject,
null, 2);
} catch (error) {
document.getElementById("objectResult").textContent = "Invalid JSON format";
}
}

// 2. Convert JSON to Date


function convertJSONToDate() {
const jsonText = document.getElementById("jsonWithDate").value;
try {
const jsObject = JSON.parse(jsonText);
const date = new Date(jsObject.date);
document.getElementById("dateResult").textContent = date.toString();
} catch (error) {
document.getElementById("dateResult").textContent = "Invalid JSON or Date
format";
}
}

// 3. Convert JSON to CSV


function convertJSONToCSV() {
const jsonText = document.getElementById("jsonForCSV").value;
try {
const jsonArray = JSON.parse(jsonText);
const csv = jsonArray.map(row => Object.values(row).join(",")).join("\n");
const headers = Object.keys(jsonArray[0]).join(",");
document.getElementById("csvResult").textContent = headers + "\n" + csv;
} catch (error) {
document.getElementById("csvResult").textContent = "Invalid JSON format";
}
}

// 4. Convert CSV to JSON


function convertCSVToJSON() {
const csvText = document.getElementById("csvText").value;
Web Technology- BCSL504

const [headers, ...rows] = csvText.split("\n");


const headerArray = headers.split(",");
const jsonArray = rows.map(row => {
const values = row.split(",");
return headerArray.reduce((object, header, index) => {
object[header] = values[index];
return object;
}, {});
});
document.getElementById("jsonFromCSVResult").textContent =
JSON.stringify(jsonArray, null, 2);
}

// 5. Create Hash from String using crypto.createHash() (Node.js)


function createHash() {
const input = document.getElementById("hashString").value;
fetch('hash_generator', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input })
})
.then(response => response.json())
.then(data => {
document.getElementById("hashResult").textContent = data.hash;
})
.catch(error => {
document.getElementById("hashResult").textContent = "Error generating hash";
});
}
</script>
</body>
</html>

Backend for Hash Generation (Node.js - Server-side script)

The hash generation part requires server-side logic using Node.js. Here is a simple Node.js
server that responds to the hash creation request:
server.js
const express = require('express');
const crypto = require('crypto');
const bodyParser = require('body-parser');
Web Technology- BCSL504

const app = express();


app.use(bodyParser.json());

app.post('/hash_generator', (req, res) => {


const { input } = req.body;
const hash = crypto.createHash('sha256').update(input).digest('hex');
res.json({ hash });
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

OUTPUT
Web Technology- BCSL504

PROGRAM-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.

SOURCECODE

<?php

$counterFile = "counter.txt";

if (!file_exists($counterFile)) {

file_put_contents($counterFile, "0");

$currentCount = file_get_contents($counterFile);

$newCount = $currentCount + 1;

file_put_contents($counterFile, $newCount);

?>

<!DOCTYPE html>

<html lang="en">

<head>
Web Technology- BCSL504

<title>Visitor Counter | vtucode</title>

<style>

body {

font-family: Arial, sans-serif;

text-align: center;

margin: 0;

padding: 0;

display: flex;

flex-direction: column;

justify-content: center;

height: 100vh;

background-color: #f4f4f9;

color: #333;

.container {

background: #fff;

padding: 20px;

box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

border-radius: 8px;

margin: 0 auto;

width: 60%;

h1 {
Web Technology- BCSL504

font-size: 2.5em;

margin: 0;

p{

font-size: 1.2em;

color: #555;

</style>

</head>

<body>

<div class="container">

<h1>Welcome to Our Website!</h1>

<p>You are visitor number: <strong><?php echo $newCount; ?></strong></p>

</div>

</body>

</html>

Instructions: How to Run?

 Create a file name called track.php, copy the below code and paste it and save it.

 Copy track.php file and open XAAMP directory

 There you’ll find a folder named “htdocs”.

 Inside the “htdocs” folder, paste track.php file.

 After then open your XAAMP and start the Apache server.

 Open your favorite browser; we recommend using Google Chrome or Mozilla Firefox.
Web Technology- BCSL504

 Then, go to the URL “http://localhost/track.php“.

OUTPUT

(b) Develop a PHP program to sort the student records which are stored in

the database using selection sort.

This example demonstrates sorting student records stored in a MySQL database


using the Selection Sort algorithm in PHP.

Steps:

1. Create a Database and Table: First, create a database and a table to store
student records.
2. Fetch Records from Database: Fetch the records from the database.
3. Sort Records: Sort the records using the Selection Sort algorithm.
4. Display Sorted Records: Display the sorted records on the webpage.
Web Technology- BCSL504

SQL: Create the Database and Table


CREATE DATABASE student_db;

USE student_db;

CREATE TABLE students (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(50),

grade FLOAT

);

INSERT INTO students (name, grade) VALUES

('John Doe', 85.5),

('Jane Smith', 90.0),

('Bob Johnson', 78.5),

('Alice Williams', 88.0),

('Tom Brown', 91.5);

sort_students.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sorted Student Records</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
background-color: #f2f2f2;
}
table {
width: 100%;
border-collapse: collapse;
Web Technology- BCSL504

}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 12px;
text-align: center;
}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>

<h1>Sorted Student Records</h1>

<?php
// Database connection
$conn = new mysqli("localhost", "root", "", "student_db");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Fetch records from database


$result = $conn->query("SELECT * FROM students");

if ($result->num_rows > 0) {
$students = [];

// Store fetched records in an array


while ($row = $result->fetch_assoc()) {
$students[] = $row;
}

// Selection Sort Algorithm to sort students by grade


$n = count($students);
Web Technology- BCSL504

for ($i = 0; $i < $n - 1; $i++) {


$minIndex = $i;
for ($j = $i + 1; $j < $n; $j++) {
if ($students[$j]['grade'] < $students[$minIndex]['grade']) {
$minIndex = $j;
}
}
// Swap the elements
$temp = $students[$i];
$students[$i] = $students[$minIndex];
$students[$minIndex] = $temp;
}

// Display sorted records in a table


echo "<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Grade</th>
</tr>";

foreach ($students as $student) {


echo "<tr>
<td>{$student['id']}</td>
<td>{$student['name']}</td>
<td>{$student['grade']}</td>
</tr>";
}

echo "</table>";
} else {
echo "No records found!";
}

// Close connection
$conn->close();
?>

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

How to Run:

1. Save the code as sort_students.php.


2. Set up your MySQL database with the given SQL commands.
3. Run the PHP script on a local server (like XAMPP or WAMP) to see the
sorted student records.

OUTPUT
Web Technology- BCSL504

PROGRAM-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.

Program

1. Append Content to Existing Paragraph and List

This script will demonstrate how to append content to an existing paragraph and
an unordered list.

2. Change the State of an Element with CSS Style Using animate()

We will use the animate() method to change the CSS properties of an element.

3. Change the Color of a Div That Is Animated

In this part, we will change the color of a div while animating it.

Full Example: index.html


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Examples</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f2f2f2;
Web Technology- BCSL504

padding: 20px;
}
p, ul {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.animated-div {
width: 200px;
height: 200px;
background-color: #4CAF50;
margin: 20px auto;
border-radius: 10px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
margin: 10px;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>

<h1>jQuery Animation Examples</h1>

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


<button id="appendText">Append Text to Paragraph</button>

<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
Web Technology- BCSL504

</ul>
<button id="appendList">Append Item to List</button>

<button id="animateDiv">Animate Div</button>


<div id="myDiv" class="animated-div"></div>

<!-- jQuery Library -->


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function() {
// a. Append content to paragraph and list
$("#appendText").click(function() {
$("#myParagraph").append(" This text was appended.");
});

$("#appendList").click(function() {
$("#myList").append("<li>New Item</li>");
});

// b. Change the state of the element using animate()


$("#animateDiv").click(function() {
$("#myDiv").animate({
width: "300px",
height: "300px",
opacity: 0.5
}, 1000, function() {
// This callback is executed after the animation is complete
$(this).css("background-color", "#ff5722"); // c. Change color after animation
});
});
});
</script>
</body>
</html>

Explanation:

1. Appending Content:
Web Technology- BCSL504

o Paragraph: When the "Append Text to Paragraph" button is clicked, the text
"This text was appended." is added to the existing paragraph.
o List: When the "Append Item to List" button is clicked, a new list item is added
to the unordered list.
2. Animating an Element:
o Animate: The animate() method is used to change the width, height, and opacity
of the div with ID myDiv. The animation duration is set to 1000 milliseconds (1
second).
3. Changing Color:
o After the animation is complete, a callback function is executed to change the
background color of the div to #ff5722 (an orange shade).
How to Use:

1. Save the code as index.html.


2. Open the file in a web browser.
3. Click the buttons to see the effects:
o Append text to the paragraph and list.
o Animate the div and change its color after the animation.

OUTPUT
Web Technology- BCSL504

PROGRAM-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.

Solution

Setup

1. Create a text file (sample.txt) that contains some text.


2. Create a JSON file (data.json) for JSON-related examples.
1. HTML Structure
Create an index.html file with buttons for AJAX operations and placeholders to display the results.
Web Technology- BCSL504

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Examples</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f2f2f2;
padding: 20px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
margin: 10px;
}
button:hover {
background-color: #45a049;
}
.result {
margin-top: 20px;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
display: inline-block;
text-align: left;
}
</style>
</head>
<body>
Web Technology- BCSL504

<h1>AJAX Examples</h1>

<button onclick="loadText()">Load Text (Vanilla JavaScript)</button>


<button onclick="loadTextJQuery()">Load Text (jQuery)</button>
<button onclick="loadJSON()">Load JSON with jQuery</button>

<div id="result" class="result"></div>

<!-- jQuery Library -->


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
// a. AJAX using Vanilla JavaScript
function loadText() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'sample.txt', true);
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('result').textContent = xhr.responseText;
} else {
document.getElementById('result').textContent = 'Error loading text file.';
}
};
xhr.send();
}

// b. AJAX using jQuery


function loadTextJQuery() {
$.ajax({
url: 'sample.txt',
method: 'GET',
success: function(data) {
$('#result').text(data);
},
error: function() {
$('#result').text('Error loading text file.');
}
});
}
Web Technology- BCSL504

// c. Using getJSON() method in jQuery


function loadJSON() {
$.getJSON('data.json', function(data) {
$('#result').html('<pre>' + JSON.stringify(data, null, 2) + '</pre>');
}).fail(function() {
$('#result').text('Error loading JSON file.');
});
}
</script>
</body>
</html>

2. Text File (sample.txt)

Create a file named sample.txt with some content:

This is sample text loaded from a text file.

3. JSON File (data.json)

Create a file named data.json with sample JSON content:

"name": "John Doe",

"age": 30,

"email": "[email protected]",

"address": {

"street": "123 Main St",

"city": "Anytown",

"state": "CA",

"zip": "12345"

Explanation

a. AJAX using Vanilla JavaScript


Web Technology- BCSL504

 Function: loadText()
 Process: Uses XMLHttpRequest to send an AJAX request to sample.txt and display the
response text in the result div.
b. AJAX using jQuery

 Function: loadTextJQuery()
 Process: Uses jQuery’s $.ajax() method to send an AJAX request to sample.txt and
display the response text in the result div.
c. Using getJSON() method in jQuery

 Function: loadJSON()
 Process: Uses jQuery’s $.getJSON() method to fetch JSON data from data.json and
displays it in a pretty-printed format in the result div.
d. Using parseJSON() method (optional)

Note: The parseJSON() method is actually deprecated in newer versions of jQuery. Instead, you
can use JSON.parse() in vanilla JavaScript.

How to Use

1. Save the index.html, sample.txt, and data.json files in the same directory.
2. Open index.html in a web browser.
3. Click the buttons to see the different AJAX functionalities:
o Load text using Vanilla JavaScript.
o Load text using jQuery.
o Load and display JSON data using jQuery.
Web Technology- BCSL504

You might also like