0% found this document useful (0 votes)
23 views44 pages

Web Technology Manual - Lab-BCSL504-HKBK

The document is a lab manual for Web Technology at Vivesvaraya Technological University, detailing various programming assignments. It includes instructions for creating HTML pages with specific content and styling, such as a personal webpage, a class timetable, and a registration form, along with explanations of the code. Each program demonstrates different HTML and CSS concepts, including semantic elements, styling, and layout techniques.

Uploaded by

vijay763026
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)
23 views44 pages

Web Technology Manual - Lab-BCSL504-HKBK

The document is a lab manual for Web Technology at Vivesvaraya Technological University, detailing various programming assignments. It includes instructions for creating HTML pages with specific content and styling, such as a personal webpage, a class timetable, and a registration form, along with explanations of the code. Each program demonstrates different HTML and CSS concepts, including semantic elements, styling, and layout techniques.

Uploaded by

vijay763026
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
You are on page 1/ 44

Vivesvaraya Technological University

Belagavi

Department of CSE

Web Technology-Lab Manual


BCSL504

NAME :

USN :

BRANCH & SEC:

Program1
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.)

Source code
<!DOCTYPE html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>

<!-- Moving text -->


<marquee>Basic HTML Tags</marquee>

<!-- Different heading tags -->


<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>

<!-- Paragraph -->


<p>This is a sample paragraph to demonstrate basic HTML tags.</p>

<!-- Horizontal line -->


<hr>

<!-- Line break -->


This is before the line break.<br>
This is after the line break.

<!-- Block quote -->


<blockquote>This is a block quote. It is used to indicate a section that is quoted from
another source.</blockquote>

<!-- Preformatted text -->


<pre>
This text is displayed exactly as it is written, with all the spaces and line breaks intact.
</pre>

<!-- Different logical styles -->


<p>This is <b>bold</b> text.</p>
<p>This is <i>italic</i> text.</p>
<p>This is <u>underlined</u> text.</p>
<p>This is <sup>superscript</sup> text (for example, exponents).</p>
<p>This is <sub>subscript</sub> text (for example, chemical formulas).</p>

</body>
</html>

Explanation:
1. The <title> tag sets the title of the page as "My First Web Page."
2. Inside the <body>, the following tags are used:
o <marquee> creates the moving text "Basic HTML Tags."
o <h1> to <h6> represent headings in different sizes.
o <p> defines paragraphs of text.
o <hr> creates a horizontal line.
o <br> inserts a line break.
o <blockquote> is used for a block quote.
o <pre> preserves whitespace formatting.
o <b>, <i>, <u>, <sup>, and <sub> are used to style text with bold,
italics, underline, superscript, and subscript respectively.

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

Source code
<!DOCTYPE html>
<html>
<head>
<title>Time Table</title>
<style>
/* Table styling */
table {
width: 100%;
border-collapse: collapse;
}

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

/* Row background colors */


tr:nth-child(even) {
background-color: #f2f2f2; /* Light gray for even rows */
}

tr:nth-child(odd) {
background-color: #e6f7ff; /* Light blue for odd rows */
}

/* Special colors for lab and elective hours */


.lab-hours {
background-color: #ffcccb; /* Light red for lab hours */
}

.elective-hours {
background-color: #ffff99; /* Light yellow for elective hours */
}
/* Header and Footer */
thead {
background-color: #4CAF50; /* Green header */
color: white;
}

tfoot {
background-color: #333; /* Dark footer */
color: white;
}
</style>
</head>
<body>

<!-- Table with header, footer, and various color options -->
<h1>Class Time Table</h1>

<table>
<thead>
<tr>
<th>Day</th>
<th>9:00 - 10:00</th>
<th>10:00 - 11:00</th>
<th>11:00 - 12:00</th>
<th>12:00 - 1:00</th>
<th colspan="2">2:00 - 4:00</th>
</tr>
</thead>

<tbody>
<tr>
<td>Monday</td>
<td>Math</td>
<td>Physics</td>
<td>Chemistry</td>
<td rowspan="5">Lunch Break</td>
<td class="lab-hours" colspan="2">Physics Lab</td>
</tr>
<tr>
<td>Tuesday</td>
<td>English</td>
<td class="elective-hours">Elective 1</td>
<td>History</td>
<td>Computer Science</td>
<td class="lab-hours">CS Lab</td>
</tr>
<tr>
<td>Wednesday</td>
<td>Math</td>
<td>Biology</td>
<td>Chemistry</td>
<td class="elective-hours">Elective 2</td>
<td>Free Hour</td>
</tr>
<tr>
<td>Thursday</td>
<td>English</td>
<td>Physics</td>
<td>Biology</td>
<td>Math</td>
<td>Library</td>
</tr>
<tr>
<td>Friday</td>
<td>History</td>
<td class="lab-hours" colspan="2">Chemistry Lab</td>
<td>Physical Education</td>
<td>Elective 1</td>
</tr>
</tbody>

<tfoot>
<tr>
<td colspan="6">Note: Labs and electives are highlighted with different colors.</td>
</tr>
</tfoot>
</table>

</body>
</html>
Explanation:
1. Title: The title of the page is set to "Time Table."
2. Table structure:
o The timetable includes a header (<thead>) and footer (<tfoot>),
with the header showing the time slots and the footer displaying a
note.
o colspan="2" is used to merge two columns for the 2-hour lab
classes.
o rowspan="5" is used to span the lunch break row over multiple
rows.
3. Coloring:
o Even rows have a light gray background, and odd rows have a light
blue background.
o Lab hours are highlighted in light red (.lab-hours), and elective
hours are highlighted in light yellow (.elective-hours).
4. CSS Styling:
o Custom styles are applied to the header, footer, and different table
sections using CSS.

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.
style.css
/* Styling h2 with a class selector */
h2.title {
color: #4CAF50; /* Green color */
font-family: Arial, sans-serif;
text-align: center;
}

/* Styling h3 with an ID selector */


#subheading {
color: #FF5733; /* Orange color */
font-style: italic;
text-align: left;
}

/* Styling hr (universal tag selector) */


hr {
border: 0;
height: 2px;
background: #333; /* Dark color */
}

/* Styling p using a descendant selector (inside div) */


div p {
font-size: 16px;
line-height: 1.6;
color: #666;
}

/* Styling div with a class */


div.box {
border: 1px solid #ddd;
padding: 15px;
margin: 20px 0;
background-color: #f9f9f9;
}

/* Styling span with an inline style and a pseudo-class */


span.highlight {
background-color: yellow;
font-weight: bold;
}

/* Styling time with a universal selector */


time {
font-family: "Courier New", monospace;
font-size: 14px;
color: #007BFF;
}

/* Styling img with an attribute selector */


img[src] {
border-radius: 10px;
max-width: 100%;
}

/* Styling anchor (a) tag with pseudo-classes */


a{
text-decoration: none;
color: #0066cc;
}

/* Anchor pseudo-classes */
a:hover {
color: #ff6600;
text-decoration: underline;
}

a:visited {
color: #9933cc;
}

HTML Example to use style.css

<!DOCTYPE html>
<html>
<head>
<title>Styled Webpage</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<h2 class="title">This is an H2 Title</h2>


<h3 id="subheading">This is an H3 Subheading</h3>

<hr>

<div class="box">
<p>This is a paragraph inside a styled div. <span class="highlight">This text is
highlighted</span>.</p>
</div>

<p>The current time is: <time>2024-09-12</time></p>


<img src="image.jpg" alt="Sample Image">

<p>Here is a <a href="https://example.com">link</a> to an external website.</p>

</body>
</html>
Explanation:
1. The external style sheet style.css is linked using the <link> tag.
2. The various CSS selectors are applied to style elements such as headings,
paragraphs, divs, spans, time elements, images, and anchor tags.
3. The different types of selectors demonstrate flexibility in how to target
and style elements, showing how class, ID, pseudo-classes, and
descendant selectors work.

Program 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.
registration.html
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<style>
/* General styles */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}

/* Table styles */
table {
width: 50%;
margin: auto;
border-collapse: collapse;
background-color: #fff;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

th, td {
padding: 15px;
text-align: left;
}

th {
background-color: #4CAF50;
color: white;
font-size: 18px;
}

/* Form element styling */


input[type="text"], input[type="email"], input[type="password"], input[type="date"],
select {
width: 100%;
padding: 10px;
margin: 8px 0;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}

input[type="radio"], input[type="checkbox"] {
margin-right: 10px;
}
textarea {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}

/* Button styles */
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 18px;
}

input[type="submit"]:hover {
background-color: #45a049;
}

/* Background color for even table rows */


tr:nth-child(even) {
background-color: #f2f2f2;
}

/* Style for error messages */


.error {
color: red;
font-size: 14px;
}
</style>
</head>
<body>

<h2 style="text-align:center; color:#333;">User Registration Form</h2>

<form action="/submit_registration" method="post">


<table>
<tr>
<th colspan="2">Personal Information</th>
</tr>
<tr>
<td>Full Name:</td>
<td><input type="text" name="fullname" required></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="email" name="email" required></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" required></td>
</tr>
<tr>
<td>Date of Birth:</td>
<td><input type="date" name="dob"></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
</td>
</tr>
<tr>
<td>Hobbies:</td>
<td>
<input type="checkbox" name="hobby" value="Reading"> Reading
<input type="checkbox" name="hobby" value="Sports"> Sports
<input type="checkbox" name="hobby" value="Music"> Music
</td>
</tr>
<tr>
<td>Country:</td>
<td>
<select name="country">
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="Australia">Australia</option>
</select>
</td>
</tr>
<tr>
<td>Bio:</td>
<td><textarea name="bio" rows="4" placeholder="Tell us something about
yourself..."></textarea></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Register">
</td>
</tr>
</table>
</form>

</body>
</html>

Features Explained:
1. Table for Alignment:
o The form is structured using an HTML table to align the input fields
with labels for a clean layout.
2. CSS Styles:
o Font and color styles: General font family is set to Arial, with
background colors and text colors customized for headers, table
rows, and form fields.
o Even row coloring: tr:nth-child(even) adds a light background
color to every even row, improving readability.
o Form elements: Inputs, text areas, and buttons are styled with
padding, font size, and border radiuses for a modern look.
o Hover effect: The submit button has a hover effect, changing the
background color when the mouse hovers over it.
3. Input Elements:
o Text fields, email, password, radio buttons (for gender),
checkboxes (for hobbies), a dropdown (for country selection), and
a textarea for a bio section.

Program 5

Develop HTML page named as “newpaper.html” having variety of HTML semantic


elements withbackground colors, text-colors & size for figure, table, aside, section,
article, header, footer… etc.
newspaper.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Newspaper Layout</title>
<style>
/* General styles */
body {
font-family: 'Arial', sans-serif;
background-color: #f2f2f2;
margin: 0;
padding: 0;
}

/* Header styles */
header {
background-color: #333;
color: white;
padding: 20px;
text-align: center;
}

header h1 {
margin: 0;
font-size: 36px;
}

/* Section styles */
section {
background-color: #fff;
padding: 20px;
margin: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

/* Article styles */
article {
background-color: #e6e6e6;
padding: 20px;
margin-bottom: 20px;
border-left: 5px solid #4CAF50;
}

article h2 {
font-size: 24px;
color: #333;
}

article p {
font-size: 16px;
line-height: 1.6;
color: #666;
}

/* Aside styles */
aside {
background-color: #f4f4f4;
padding: 15px;
margin: 20px;
font-size: 14px;
color: #333;
float: right;
width: 30%;
}

/* Footer styles */
footer {
background-color: #333;
color: white;
text-align: center;
padding: 10px;
position: fixed;
bottom: 0;
width: 100%;
}

/* Table styles */
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}

table, th, td {
border: 1px solid #ddd;
padding: 8px;
}

th {
background-color: #4CAF50;
color: white;
}
td {
background-color: #f9f9f9;
color: #333;
}

/* Figure styles */
figure {
margin: 20px;
text-align: center;
}

figure img {
width: 100%;
max-width: 400px;
border-radius: 10px;
}

figure figcaption {
font-size: 14px;
color: #555;
margin-top: 5px;
}
</style>
</head>
<body>

<!-- Header -->


<header>
<h1>Daily News</h1>
<p>Your Source for the Latest News</p>
</header>

<!-- Main content section -->


<section>
<!-- Main article -->
<article>
<h2>Breaking News: Technology Revolution in 2024</h2>
<p>In 2024, the world of technology has seen a groundbreaking shift with the advent
of new AI-driven innovations, quantum computing, and more. The future of technology is
here, and it is changing the way we live and work.</p>
<p>Stay tuned for more updates as we cover the latest in tech developments.</p>
</article>

<!-- Second article -->


<article>
<h2>Sports: Major League Finals</h2>
<p>The final match of the Major League Championship took place today, with fans
on the edge of their seats. Team X pulled off a stunning victory over Team Y in a thrilling
match that kept the audience captivated.</p>
</article>

<!-- News table -->


<table>
<thead>
<tr>
<th>Category</th>
<th>Headline</th>
<th>Published Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Technology</td>
<td>AI Developments</td>
<td>September 12, 2024</td>
</tr>
<tr>
<td>Sports</td>
<td>Major League Finals</td>
<td>September 12, 2024</td>
</tr>
<tr>
<td>World</td>
<td>Climate Change Talks</td>
<td>September 11, 2024</td>
</tr>
</tbody>
</table>

<!-- Figure with image -->


<figure>
<img src="news-image.jpg" alt="News image">
<figcaption>Image from the news story.</figcaption>
</figure>
</section>

<!-- Sidebar content -->


<aside>
<h3>Related Articles</h3>
<ul>
<li><a href="#">AI Innovations in Healthcare</a></li>
<li><a href="#">Top Sports Events in 2024</a></li>
<li><a href="#">Global Politics: What to Expect</a></li>
</ul>
</aside>

<!-- Footer -->


<footer>
<p>Copyright &copy; 2024 Daily News. All rights reserved.</p>
</footer>

</body>
</html>

Explanation:
1. Header (<header>): The header contains the title of the newspaper and
a brief description. It has a dark background and white text.
2. Section (<section>): This element wraps the main content of the page,
including the articles, table, and figure.
3. Article (<article>): Each article is styled with a light gray background and
has a green border on the left side. It contains a title and text content.
4. Aside (<aside>): The aside element is used as a sidebar for related
articles, placed on the right with a light background.
5. Table: A table is used to list news headlines, with alternating colors for
rows and a styled header.
6. Figure (<figure>) and Figcaption (<figcaption>): A figure element is used
to display an image related to the news, with a caption below it.
7. Footer (<footer>): The footer is styled with a fixed position at the bottom
of the page, displaying copyright information.
CSS Features:
• Background colors: Used in the header, footer, and various content areas
to differentiate sections.
• Font colors and sizes: Adjusted for titles, paragraphs, and links for
readability and aesthetic appeal.
• Layout styles: Padding and margin provide spacing, and a box-shadow is
applied to sections for a subtle depth effect.
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.

calculator.html
<!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>
/* General styles */
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}

/* Calculator container */
.calculator {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}

/* Title */
h2 {
text-align: center;
color: #333;
}

/* Input fields */
input[type="number"] {
width: calc(50% - 10px);
padding: 10px;
margin: 10px 5px;
border-radius: 5px;
border: 1px solid #ccc;
font-size: 16px;
}

/* Buttons */
button {
width: calc(33.33% - 10px);
padding: 10px;
margin: 10px 5px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}

button:hover {
background-color: #45a049;
}

/* Result display */
#result {
margin: 20px 0;
text-align: center;
font-size: 20px;
color: #333;
}
</style>
</head>
<body>

<div class="calculator">
<h2>Simple Calculator</h2>

<!-- Input fields -->


<input type="number" id="num1" placeholder="Enter 1st number">
<input type="number" id="num2" placeholder="Enter 2nd number">

<!-- Calculator buttons -->


<button onclick="calculate('sum')">Sum (+)</button>
<button onclick="calculate('diff')">Difference (-)</button>
<button onclick="calculate('prod')">Product (×)</button>
<button onclick="calculate('quot')">Quotient (÷)</button>
<button onclick="calculate('rem')">Remainder (%)</button>
<button onclick="calculate('pow')">Power (^)</button>
<button onclick="calculate('sqrt')">Square Root (√)</button>
<button onclick="calculate('square')">Square (x²)</button>

<!-- Result display -->


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

<!-- JavaScript for calculator -->


<script>
function calculate(operation) {
const num1 = parseFloat(document.getElementById('num1').value);
const num2 = parseFloat(document.getElementById('num2').value);
let result = 0;

// Perform calculations based on the operation


switch (operation) {
case 'sum':
result = num1 + num2;
break;
case 'diff':
result = num1 - num2;
break;
case 'prod':
result = num1 * num2;
break;
case 'quot':
result = num1 / num2;
break;
case 'rem':
result = num1 % num2;
break;
case 'pow':
result = Math.pow(num1, num2);
break;
case 'sqrt':
result = `√${num1} = ${Math.sqrt(num1)}, √${num2} = ${Math.sqrt(num2)}`;
break;
case 'square':
result = `${num1}² = ${num1 * num1}, ${num2}² = ${num2 * num2}`;
break;
default:
result = 'Invalid operation';
}

// Display the result


document.getElementById('result').innerHTML = `Result: ${result}`;
}
</script>

</body>
</html>

Explanation:
1. HTML:
o There are two input fields (<input>) to accept numbers from the
user.
o Eight buttons represent operations: Sum, Difference, Product,
Quotient, Remainder, Power, Square Root, and Square.
o A <div> with the ID result is used to display the result of the
calculation.
2. CSS:
o The calculator is styled with a white background, centered on the
screen, and uses simple padding, border-radius, and box-shadow
for a modern look.
o Buttons are styled to change color when hovered over, providing a
nice user interface.
o The input fields are styled for consistent width and alignment.
3. JavaScript:
o The calculate function takes an argument operation to determine
which operation to perform.
o Based on the operation, it calculates and displays the result using
JavaScript's mathematical functions like Math.pow() and
Math.sqrt().
o If the square root or square button is pressed, it calculates the
result for both numbers separately.
Operations Supported:
• Sum (+): Adds the two input numbers.
• Difference (-): Subtracts the second number from the first.
• Product (×): Multiplies the two numbers.
• Quotient (÷): Divides the first number by the second.
• Remainder (%): Computes the remainder of the division.
• Power (^): Raises the first number to the power of the second.
• Square Root (√): Finds the square root of both input numbers.
• Square (x²): Squares both input numbers.
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
Solution
1. Converting JSON Text to JavaScript Object
This section will demonstrate how to convert a JSON string into a JavaScript
object using the JSON.parse() method.
2. Convert JSON Results into a Date
This will show how to extract a date from JSON and format it into a human-
readable form.
3. Convert JSON to CSV and CSV to JSON
This part will involve converting a JSON object to CSV format and vice versa
using JavaScript.
4. Create a Hash from a String using crypto.createHash()
This example uses Node.js's built-in crypto module to create a hash.
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 {
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
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;
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');

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');
});

Explanation:
1. Converting JSON Text to JavaScript Object:
o The user inputs a JSON string, and the JSON.parse() function
converts it to a JavaScript object, which is then displayed.
2. Converting JSON to Date:
o The input JSON object with a date field is parsed, and the date is
formatted using JavaScript’s Date object.
3. Converting JSON to CSV:
o A JSON array is converted into CSV format by mapping over the
array, extracting the values, and joining them by commas.
4. Converting CSV to JSON:
o The CSV text is split into headers and rows, and each row is
converted into an object with the headers as keys.
5. Creating Hash from String:
o On the client side, an input string is sent to the server where
crypto.createHash() generates a SHA-256 hash, and the result is
returned to the client.
How to Run the Project:
1. Save the json_operations.html file as your front end.
2. Install Node.js and create a backend file server.js.
3. Run the Node.js backend with node server.js.
4. Open the HTML file in a browser and test the features.

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.
b. Develop a PHP program (with HTML/CSS) to sort the student records which are stored
in the database using selection sort.
Part A: PHP Program to Track Visitors Count
Here’s a PHP program that keeps track of the number of visitors visiting a
webpage and displays the count of visitors.
Steps:
1. Store Visitor Count in a File: We'll use a text file (counter.txt) to store the
number of visitors.
2. Display the Visitor Count: Every time a user visits the page, the visitor
count is updated and displayed.
visitor_count.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visitor Count</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f2f2f2;
padding-top: 50px;
}
h1 {
color: #333;
}
.counter {
font-size: 2rem;
color: #4CAF50;
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
display: inline-block;
margin-top: 20px;
}
</style>
</head>
<body>

<h1>Welcome to My Web Page!</h1>


<h2>Total Visitors:</h2>

<?php
// File to store visitor count
$file = 'counter.txt';

// Check if the file exists


if (!file_exists($file)) {
// If the file doesn't exist, create it with an initial value of 0
file_put_contents($file, '0');
}

// Read the current count from the file


$count = (int) file_get_contents($file);

// Increment the count by 1


$count++;

// Write the new count back to the file


file_put_contents($file, $count);

// Display the visitor count


echo "<div class='counter'>$count</div>";
?>

</body>
</html>
Explanation:
• Visitor Count Storage: The visitor count is stored in a file named
counter.txt. Each time the page is accessed, the counter is incremented
and displayed on the page.
• File Handling: PHP functions file_get_contents() and file_put_contents()
are used to read and write the counter.
• CSS Styling: The counter is displayed using simple CSS for a clean look.
How to Run:
1. Save the code as visitor_count.php.
2. Create a counter.txt file in the same directory.
3. Host the PHP file on a local server (like XAMPP or WAMP), and each time
the page is visited, the count will increase.
Part B: PHP Program to Sort Student Records 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.
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;
}
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);
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>
Explanation:
• Database Connection: The script connects to a MySQL database
(student_db) using mysqli.
• Fetching Records: Records are fetched from the students table using a
SELECT query.
• Selection Sort Algorithm: The fetched student records are sorted by
grade using the Selection Sort algorithm.
• Display: The sorted records are displayed in an HTML table.
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.

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.
Solution
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;
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>
</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:
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.
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.

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>

<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.');
}
});
}

// 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
• 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.

***********END of Manual***********

You might also like