0% found this document useful (0 votes)
19 views60 pages

Lab Report on Scripting Language

Uploaded by

gaganroka902
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)
19 views60 pages

Lab Report on Scripting Language

Uploaded by

gaganroka902
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

TRIBHUWAN UNIVERSITY

Faculty of Humanities and Social Sciences

JANAMAITRI MULTIPLE CAMPUS


Kuleshwar, Kathmandu

A LAB REPORT ON SCRIPTING LANGUAGE

In the partial fulfillment of the requirements for the Bachelors of Computer Applications

Submitted by:
Gagan Rokka
(6-2-263-14-2021)
Janamaitri Multiple Campus
Kuleshwar, Kathmandu

Under the supervision of


Mr. Rabindra Thapa Magar
Department of Computer Application
Letter of Recommendation

This report entitled “A lab report on Scripting Language” by Mr. Gagan Rokka has been
prepared under our supervision for partial fulfillment of the requirement of Computer
Applications (BCA) 4th semester. I, therefore recommend it for evaluation by the thesis
committee.

Mr. Rabindra Thapa Magar

1
Certificate of Acceptance

This report "A lab report on Scripting Language" written by Mr. Gagan Rokka has been
accepted as partial fulfillment of the requirement for a Bachelors of Computer Applications
(BCA) 4th Semester.

Evaluation Committee:

………………………………… ………………………

External Signature Supervisor

2
Declaration Letter
I declare that I completed this work on my own and that information which has been directly or
indirectly taken from other sources has been noted as such. Neither this, nor a similar work, has
been published or presented to an examination committee.
1/21/2081 B.S, Friday

Gagan Rokka
BCA 4th Semester
Janamaitri Multiple Campus
Kuleshwor, Kathmandu

3
Acknowledgement

This research report is prepared for the partial fulfillment of the requirement of BCA 4 th
Semester with the prescribed rules and regulations of the TU board. Firstly, I would like to
acknowledge special thanks to Mr. Rabindra Thapa Magar Sir, our Scripting Language
teacher, for giving me an opportunity to prepare a report on "A lab report on Scripting
Language". His guidance, comments and recommendations helped me to conduct this research.
Secondly, I would like to thank all my friends who inspired me during this lab report. I would
also like to thank my family members who shared their knowledge in this report topic.

Thank you!

4
Self-Declaration Letter

I, Gagan Rokka, candidate of BCA 4th Semester, hereby declare that the contents included on this
Practical Lab Book is entirely done by myself as a part of study. None of the portion on the Lab
Book is duplicated or copied from any other source.

I am liable and obliged to all the corrections and suggestions given by the faculty members,
Internal Examiner as well as External Examiner during the evaluation.

Name: ………………………

Internal Examiner External Examiner

Name: ………………… Name: ………………..

Signature: …………………. Signature: ……………

Date: …………………. Date: …………………

I-EN-
S-S-
-D -

5
1. Write a program which includes a function add (). It should take
arbitrary number of parameters and return the result by adding all
the parameters. Use browser message box to display the output.
Code:
// File Name: [Link]
// Description: Program to add arbitrary number of parameters using a
function.

function add(...args) {
return [Link]((total, num) => total + num, 0);
}

// Example usage:
const result = add(5, 10,
15, 20); alert(`The sum is:
${result}`);
Ouptut:

1) Write a client side program to display the continuous Time in the


status bar of the browser. Time should be updated every second.
Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Continuous Time Display</title>
<style>
#time {
position:
fixed; top:

6
0;
right: 0;
font-size: 18px;
padding: 5px;

7
</head>
<body>
<div id="time"></div>
<script>
const timeElement = [Link]('time');

function updateTime() {
const date = new Date();
const hours = [Link]().toString().padStart(2, '0');
const minutes = [Link]().toString().padStart(2, '0');
const seconds = [Link]().toString().padStart(2, '0');
[Link] = `${hours}:${minutes}:${seconds}`;
}

updateTime();
setInterval(updateTime, 1000); // Update time every second
</script>
</body>
</html>

Ouptut:

2) Write following programs by using dialog box or


component of form as input from user.
WAP to find sum of two numbers.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum of Two Numbers</title>
</head>
<body>
<h1>Sum Calculator</h1>
<label for="num1">Enter First Number:</label>
<input type="number" id="num1" required><br>
<label for="num2">Enter Second Number:</label>
<input type="number" id="num2" required><br>
<button onclick="addNumbers()">Calculate Sum</button>
<p id="result"></p>

<script>
function addNumbers() {
const num1 = parseFloat([Link]('num1').value);
const num2 = parseFloat([Link]('num2').value);

8
const sum = num1 + num2;
[Link]('result').textContent = `The sum of ${num1} and
${num2} is: ${sum}`;
}
</script>
</body>
</html>
Ouptut:

WAP to add, subtract, multiply and divide two numbers.


Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form onsubmit="return calculate()">
<label for="num1">Number 1:</label>
<input type="number" id="num1" required><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" required><br>
<select id="operation">
<option value="add">Add</option>
<option value="subtract">Subtract</option>

9
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select><br>
<input type="submit" value="Calculate">
</form>
<p id="result"></p>

<script>
function calculate() {
const num1 = parseFloat([Link]('num1').value);
const num2 = parseFloat([Link]('num2').value);
const operation = [Link]('operation').value;

let result;
if (operation === "add") {
result = num1 + num2;
} else if (operation === "subtract") {
result = num1 - num2;
} else if (operation === "multiply") {
result = num1 * num2;
} else if (operation === "divide") {
if (num2 === 0) {
alert("Division by zero is not allowed!");
return false;
}
result = num1 / num2;
}

[Link]('result').textContent = `Result: ${result}`;


return false; // Prevent form submission
}
</script>
</body>
</html>

10
Ouptut:

WAP to find largest among two numbers.


Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Largest Number</title>
</head>
<body>
<form onsubmit="return findLargest()">
<label for="num1">Number 1:</label>
<input type="number" id="num1" required><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" required><br>
<button type="submit">Find Largest</button>
</form>

<script>
function findLargest() {
const num1 = parseFloat([Link]('num1').value);
const num2 = parseFloat([Link]('num2').value);

let largest;
if (num1 > num2) {
largest = num1;
} else {
largest = num2;

11
}

alert(`The largest number is: ${largest}`);


return false; // Prevent form submission
}
</script>
</body>
</html>

Ouptut:

WAP to find smallest among two numbers.


Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Smallest Number</title>
</head>
<body>
<h1>Find the Smallest Number</h1>
<form id="numberForm">
<label for="num1">Enter first number:</label>
<input type="number" id="num1" name="num1" required><br>
<label for="num2">Enter second number:</label>
<input type="number" id="num2" name="num2" required><br>
<button type="button" onclick="findSmallest()">Find Smallest</button>
</form>
<p id="result"></p>

<script>
function findSmallest() {
const num1 = parseFloat([Link]('num1').value);
const num2 = parseFloat([Link]('num2').value);

let smallest;
if (num1 < num2) {
smallest = num1;
} else {
smallest = num2;
}

const resultElement = [Link]('result');

12
[Link] = `The smallest number is: ${smallest}`;
}
</script>
</body>
</html>

Ouptut:

WAP to find largest among three numbers.


Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Largest Number</title>
</head>
<body>
<h1>Find Largest Number</h1>
<form id="numberForm">
<label for="num1">Number 1:</label>
<input type="number" id="num1" required><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" required><br>
<label for="num3">Number 3:</label>

13
<input type="number" id="num3" required><br>
<button type="button" onclick="findLargest()">Find Largest</button>
</form>

<script>
function findLargest() {
const num1 = parseInt([Link]('num1').value);
const num2 = parseInt([Link]('num2').value);
const num3 = parseInt([Link]('num3').value);

let largest = num1;


if (num2 > largest) {
largest = num2;
}
if (num3 > largest) {
largest = num3;
}

alert(`The largest number is: ${largest}`);


}
</script>
</body>
</html>
Ouptut:

14
WAP to find smallest among three numbers.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Smallest Number</title>
</head>
<body>
<h1>Find the Smallest Number</h1>
<form id="numberForm">
<label for="num1">Number 1:</label>
<input type="number" id="num1" name="num1" required><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" name="num2" required><br>
<label for="num3">Number 3:</label>
<input type="number" id="num3" name="num3" required><br>
<button type="button" onclick="findSmallest()">Find Smallest</button>
</form>

<script>
function findSmallest() {
const num1 = parseFloat([Link]("num1").value);
const num2 = parseFloat([Link]("num2").value);
const num3 = parseFloat([Link]("num3").value);

let smallest = [Link](num1, num2, num3);

const message = `The smallest number is: ${smallest}`;


alert(message);
}
</script>
</body>
</html>

15
Ouptut:

2) Create HTML form with fields Full Name, Address,


Telephone, Gender, Email, Country and Comments. Write
JavaScript program to validate that form so that user will
only write correct values. Check for empty values, number,
and email and focus them on receiving invalid values.
Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>User Registration</h1>
<form id="userForm" onsubmit="return validateForm()">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName" required><br>
<label for="address">Address:</label>
<textarea id="address" name="address" required></textarea><br>
<label for="telephone">Telephone:</label>

16
<input type="tel" id="telephone" name="telephone" required><br>
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="male" required>
<span>Male</span>
<input type="radio" id="female" name="gender" value="female" required>
Female<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="country">Country:</label>
<select id="country" name="country" required>
<option value="">Select Country</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="India">India</option>
<option value="Nepal">Nepal</option>
</select><br>
<label for="comments">Comments:</label>
<textarea id="comments" name="comments"></textarea><br>
<button type="submit">Submit</button>
</form>

<script src="[Link]"></script>
</body>
</html>

CSS:
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}

h1 {
text-align: center;
font-size: 2em;
margin-bottom: 20px;
}

form {
max-width: 500px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

label {
display: block;
margin-bottom: 5px;
}

17
input,
textarea,
select {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}

input[type="radio"] {
width: initial;
}

button[type="submit"] {
background-color: #4caf50;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}

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

.error {
color: red;
font-size: 14px;
margin-top: 5px;
}

JavaScript:
function validateForm() {
const fullName = [Link]("fullName").[Link]();
const address = [Link]("address").[Link]();
const telephone = [Link]("telephone").[Link]();
const email = [Link]("email").[Link]();
const country = [Link]("country").value;
const comments = [Link]("comments").[Link]();

let isValid = true;

// Check Full Name


if (fullName === "") {
alert("Full Name cannot be empty!");
[Link]("fullName").focus();
isValid = false;
}

// Check Address
if (address === "") {

18
alert("Address cannot be empty!");
[Link]("address").focus();
isValid = false;
}

// Check Telephone (basic check for numbers)


if (isNaN(telephone) || telephone === "") {
alert("Telephone must contain only numbers!");
[Link]("telephone").focus();
isValid = false;
}

// Check Email format


const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".
+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-
zA-Z]{2,}))$/;
if (![Link](email)) {
alert("Please enter a valid email address!");
[Link]("email").focus();
isValid = false;
}

// Check Country selection


if (country === "") {
alert("Please select a country!");
[Link]("country").focus();
isValid = false;
}

return isValid;
}

19
Ouptut:

3) Write a JavaScript program that will ask a value and


store them in a cookie which need to be expire in an hour.
After storing the value; upon clicking 'show' button alert
the stored value.
Code:
Html:
<!DOCTYPE html>

20
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Store and Show Value</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Store and Show Value Program</h1>
<input type="text" id="valueInput" placeholder="Enter a value">
<button type="button" onclick="storeValue()">Store</button>
<button type="button" onclick="showValue()">Show</button>
<script src="[Link]"></script>
</body>
</html>

CSS:
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}

h1 {
text-align: center;
font-size: 2em;
margin-bottom: 20px;
}

input[type="text"] {
width: 200px;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}

button {
margin-left: 10px;
padding: 8px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: #4caf50;
color: #fff;
font-size: 16px;
}

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

JavaScript:

21
function storeValue() {
const value = [Link]("valueInput").value;
if (value) {
const expires = new Date();
[Link]([Link]() + (1 * 60 * 60 * 1000)); // One hour in
milliseconds
[Link] = `storedValue=${value}; expires=${[Link]()};
path=/`;
alert("Value stored successfully!");
} else {
alert("Please enter a value to store!");
}
}

function showValue() {
const storedValue = [Link](';').find(c =>
[Link]('storedValue='));
if (storedValue) {
const value = [Link]('=')[1];
alert(`Stored value: ${value}`);
} else {
alert("No value found in the cookie!");
}
}
Ouptut:

4) Create a calculator type form. It should contain three


list boxes. The first and third list boxes should list the
numbers 0 to 9. The middle list box should list the
following mathematical operators: +, -, * & /. The user
should be able to select the two numbers and the operation.
Answer should be shown on submission of the form.
Code:
Html:
<<!DOCTYPE html>
<html lang="en">
<head>

22
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Calculator</h1>
<form id="calculatorForm">
<label for="number1">Number 1:</label>
<select id="number1" name="number1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>

<label for="operator">Operator:</label>
<select id="operator" name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>

<label for="number2">Number 2:</label>


<select id="number2" name="number2">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>

<button type="button" id="calculateBtn">Calculate</button>


</form>

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

<script src="[Link]"></script>
</body>
</html>

CSS:

body {
font-family: Arial, sans-serif;

23
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}

h1 {
text-align: center;
font-size: 2em;
margin-bottom: 20px;
}

form {
max-width: 400px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

label {
display: block;
margin-bottom: 10px;
}

select {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}

button {
display: block;
margin: 20px auto 0;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: #4caf50;
color: #fff;
font-size: 16px;
}

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

#result {
margin-top: 20px;
font-size: 18px;
text-align: center;
}
JavaScript:

24
[Link]("calculateBtn").addEventListener("click", function() {
const num1 = parseInt([Link]("number1").value);
const num2 = parseInt([Link]("number2").value);
const operator = [Link]("operator").value;
let result;

switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
result = "Invalid operation";
}

[Link]("result").innerText = `Result: ${result}`;


});

Ouptut:

25
5) Write a program in JavaScript to display
multiplication table as follows. Take the number input from
the user. E.g. Input number is 4.

|mulitpicad|muliplier|product|
|4 |1 |4 |
|4 |2 |8 |
| | | |
Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiplication Table</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Multiplication Table</h1>
<input type="number" id="numberInput" placeholder="Enter a number">
<button type="button" onclick="showTable()">Show Table</button>
<div id="tableContainer"></div>
<script src="[Link]"></script>
</body>
</html>

CSS:

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}

h1 {
text-align: center;
font-size: 2em;
margin-bottom: 20px;
}

input[type="number"] {
width: 200px;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;

26
box-sizing: border-box;
margin-right: 10px;
}

button {
padding: 8px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: #4caf50;
color: #fff;
font-size: 16px;
}

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

table {
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}

th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: center;
}

th {
background-color: #4caf50;
color: #fff;
}
JavaScript:

function showTable() {
const number = parseInt([Link]("numberInput").value);
if (isNaN(number)) {
alert("Please enter a valid number!");
return;
}

const tableContainer = [Link]("tableContainer");


[Link] = ""; // Clear previous table

const table = [Link]("table");

// Create header row


const headerRow = [Link]("tr");
const headers = ["Multiplicand", "Multiplier", "Product"];
[Link](headerText => {
const header = [Link]("th");
[Link] = headerText;
[Link](header);
});
[Link](headerRow);

27
// Create rows for multiplication
for (let i = 1; i <= 10; i++) {
const row = [Link]("tr");
const cells = [number, i, number * i];
[Link](cellText => {
const cell = [Link]("td");
[Link] = cellText;
[Link](cell);
});
[Link](row);
}

[Link](table);
}

Ouptut:

28
6) Write a program to display a number randomly. The
Random number should be generated when you click upon a
link 'Click Me'. If the number is less than 20 then show a
alert box with a message "Hey (random Number) is less than
20", and if the random number is greater than 20 then show
a alert box with a message "Your(random Number) is greater
than or equals to 20".
Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Generator</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Random Number Generator</h1>
<a href="#" id="clickMeLink">Click Me</a>
<div id="result"></div>
<script src="[Link]"></script>
</body>
</html>

CSS:

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}

h1 {
text-align: center;
font-size: 2em;
margin-bottom: 20px;
}

a {
display: block;
text-align: center;
padding: 10px 20px;
background-color: #4caf50;
color: #fff;
border-radius: 4px;
text-decoration: none;
font-size: 16px;
margin-bottom: 20px;
}

29
a:hover {
background-color: #45a049;
}

#result {
text-align: center;
font-size: 1.2em;
margin-top: 20px;
}

JavaScript:

[Link]("clickMeLink").addEventListener("click", function() {
const randomNumber = [Link]([Link]() * 100) + 1;
[Link]("result").textContent = `Random Number: $
{randomNumber}`;

if (randomNumber < 20) {


alert(`Hey ${randomNumber} is less than 20`);
} else {
alert(`Your ${randomNumber} is greater than or equal to 20`);
}
});
Ouptut:

30
7) Write a program that displays the continuous time in
the web page. The Time should be in the format of HH:MM:SS.
[Hints use setTimeOut/setInterval function]
Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Continuous Time Display</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Continuous Time Display</h1>
<div id="timeDisplay"></div>
<script src="[Link]"></script>
</body>
</html>

CSS:

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}

h1 {
text-align: center;
font-size: 2em;
margin-bottom: 20px;
}

#timeDisplay {
text-align: center;
font-size: 3em;
color: #333;
}
JavaScript:

function updateTime() {
const now = new Date();
const hours = String([Link]()).padStart(2, '0');
const minutes = String([Link]()).padStart(2, '0');
const seconds = String([Link]()).padStart(2, '0');
const timeString = `${hours}:${minutes}:${seconds}`;

[Link]("timeDisplay").textContent = timeString;
}

31
setInterval(updateTime, 1000); // Update time every second

Ouptut:

8) Write a program that will change the background color


in every 2 seconds. Use at least 6 colors.
Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Background Color Changer</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Background Color Changer</h1>
<div id="content">
<p>This background color will change every 2 seconds.</p>
</div>
<script src="[Link]"></script>
</body>
</html>

CSS:

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}

h1 {
text-align: center;
font-size: 2em;
margin-bottom: 20px;
}

#content {

32
text-align: center;
font-size: 1.2em;
padding: 20px;
border-radius: 5px;
color: #fff;
}
JavaScript:

const colors = ["#3498db", "#e74c3c", "#2ecc71", "#f39c12", "#9b59b6", "#1abc9c"];


let currentIndex = 0;

function changeBackgroundColor() {
[Link]("content").[Link] =
colors[currentIndex];
currentIndex = (currentIndex + 1) % [Link]; // Loop through colors array
}

setInterval(changeBackgroundColor, 2000); // Change color every 2 seconds


Ouptut:

9) Write a program which includes a function sum(). This


function sum() should be designed to add an arbitrary list
of parameters.(For e.g. if you call the function sum() as
sum (2, 3) it should return the result 5 and if again you
call the function sum() as sum(2,3,4) it should return the
result 9).
Code:
Html:

33
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum Function Example</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Sum Function</h1>
<p>Enter numbers separated by commas (,) and click the button to calculate the
sum.</p>
<input type="text" id="numbers" placeholder="Enter numbers (e.g., 2, 3, 4)">
<button id="calculateButton">Calculate Sum</button>
<p id="result"></p>

<script src="[Link]"></script>
</body>
</html>

CSS:

* {box-sizing: border-box;}
body {
font-family: sans-serif;
margin: 20px;
}

h1 {
text-align: center;
margin-bottom: 10px;
}

p {
margin-bottom: 5px;
}

#numbers,
#calculateButton {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 10px;
display: block;
width: 50%;
}

#result {
font-weight: bold;
margin-top: 10px;
}

JavaScript:

function sum(...numbers) {
// Use the spread operator (...) to convert arguments to an array
let total = 0;

34
for (const number of numbers) {
total += number;
}
return total;
}

const calculateButton = [Link]("calculateButton");


const resultElement = [Link]("result");

[Link]("click", () => {
const numbersString = [Link]("numbers").value;

// Split the comma-separated string into an array of numbers


const numbersArray = [Link](",").map(Number);

// Calculate the sum using the sum function


const sumResult = sum(...numbersArray);

// Display the result in the paragraph element


[Link] = `The sum is: ${sumResult}`;
});
Ouptut:

35
10) Write a program to create two text boxes and two
buttons. If the user inputs the value in first text box and
click upon the button then the value entered into the first
text box should be displayed into the second text box (in
uppercase if the user have inputtedin lowercase and vice
versa), similarly for the second text-box similarly for the
second text box.
Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Box Converter</title>
<link rel="stylesheet" href="[Link]"> </head>
<body>
<h1>Text Box Converter</h1>
<div class="container">
<input type="text" id="textbox1" placeholder="Enter Text">
<button id="button1">Convert to Uppercase</button>
<input type="text" id="textbox2" placeholder="Converted Text">
<button id="button2">Convert to Lowercase</button>
</div>

<script src="[Link]"></script> </body>


</html>
CSS:

.container {
display: flex;
flex-direction: column;
align-items: center;
margin: 20px auto;
}

input[type="text"], button {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
border-radius: 5px;
}

JavaScript:

const textbox1 = [Link]("textbox1");


const textbox2 = [Link]("textbox2");
const button1 = [Link]("button1");
const button2 = [Link]("button2");

function convertText(sourceTextbox, targetTextbox, conversion) {


const text = [Link];

36
let convertedText;
if (conversion === "uppercase") {
convertedText = [Link]();
} else {
convertedText = [Link]();
}
[Link] = convertedText;
}

[Link]("click", () => {
convertText(textbox1, textbox2, "uppercase");
});

[Link]("click", () => {
convertText(textbox2, textbox1, "lowercase");
});
Ouptut:

11) Write a program which display a button, clicking on


that the browser window needs to be closed.
Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Close Window</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<button id="closeButton">Close Window</button>

37
<script src="[Link]"></script>
</body>
</html>

CSS:

body {
font-family: sans-serif;
margin: 20px;
}

#closeButton {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f00; /* Red background for the button */
color: #fff; /* White text for the button */
cursor: pointer; /* Indicate clickable cursor */
}

/* Optional styles for [Link] (assuming it exists) */


.confirmation-page {
text-align: center;
padding: 20px;
}

.confirmation-page h1 {
font-size: 20px;
margin-bottom: 10px;
}

JavaScript:

const closeButton = [Link]("closeButton");


[Link]("click", () => {
[Link] = "[Link]";
});
Ouptut:

38
12) Show example of form validation using regular
expression where the given input should validate the field
name which does not contain any special characters,
password that contains at least one uppercase, one number,
one special characters and small letters and its length
should be at least 8 character long, similarly validate
phone number and email id as well.
Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Registration Form</h1>
<form id="registrationForm">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name">
<span id="nameError"></span>
</div>

<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter your
password">
<span id="passwordError"></span>
</div>

<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="text" id="phone" name="phone" placeholder="Enter your phone
number">
<span id="phoneError"></span>
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email">
<span id="emailError"></span>
</div>

<button type="submit" id="registerButton">Register</button>


<button id="closeButton">Close Window</button>
</form>

<script src="[Link]"></script>
</body>

39
</html>

CSS:

body {
font-family: sans-serif;
margin: 20px;
}

#registrationForm {
display: flex;
flex-direction: column;
gap: 15px;
width: 400px;
background-color: #f5f5f5;
border-radius: 5px;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* Added subtle shadow effect */
}

.form-group {
display: flex;
flex-direction: column;
gap: 5px;
}

label {
font-weight: bold;
}

input[type="text"],
input[type="email"],
input[type="password"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 3px;
width: 100%;
}

[Link] {
color: red;
font-size: smaller;
}

#closeButton {
padding: 10px 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f00; /* Red background for the close button */
color: #fff; /* White text for the close button */
cursor: pointer; /* Indicate clickable cursor */
margin-top: 10px;
float: right; /* Align button to the right */
}

#registerButton {
padding: 10px 20px;

40
border: 1px solid #4CAF50; /* Green border for the register button */
border-radius: 5px;
background-color: #4CAF50; /* Green background */
color: white; /* White text */
cursor: pointer; /* Indicate clickable cursor */
margin-top: 10px;
}

/* Added styles for a more visually appealing form */


input[type="text"]:focus,
input[type="email"]:focus,
input[type="password"]:focus {
outline: none; /* Remove default outline on focus */
border-color: #4CAF50; /* Change border color on focus */
}

JavaScript:

const closeButton = [Link]("closeButton");


const registrationForm = [Link]("registrationForm");
const nameInput = [Link]("name");
const passwordInput = [Link]("password");
const phoneInput = [Link]("phone");
const emailInput = [Link]("email");
const nameError = [Link]("nameError");
const passwordError = [Link]("passwordError");
const phoneError = [Link]("phoneError");
const emailError = [Link]("emailError");

[Link]("click", () => {
[Link] = "[Link]"; // Redirect to confirmation page
(optional)
});

[Link]("submit", (event) => {


[Link](); // Prevent default form submission

// Reset error messages


[Link] = "";
[Link] = "";
[Link] = "";
[Link] = "";

// Validation logic
let isValid = true;

// Name validation
if (!/^[a-zA-Z ]+$/.test([Link])) {
[Link] = "Name can only contain letters and spaces.";
isValid = false;
}

// Password validation
const passwordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^\w\s]).{8,}$/;
if (![Link]([Link])) {

41
[Link] = "Password must be at least 8 characters and contain
at least one uppercase letter, one lowercase letter, one number, and one special
character.";
isValid = false;
}

// Phone number validation (basic example)


if (!/^\d+$/.test([Link])) { // This validates only digits
[Link] = "Phone number can only contain digits.";
isValid = false;
}

// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (![Link]([Link])) {
[Link] = "Please enter a valid email address.";
isValid = false;
}

// Submit the form if everything is valid (optional)


if (isValid) {
// Your form submission logic here (e.g., send data to server)
alert("Form submitted successfully!");
}
});
Ouptut:

42
13) Show Example of Post and Get in PHP.
Code:
Html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GET vs POST Example</title>
<style>
body {

43
font-family: sans-serif;
margin: 20px;
}

h1 {
text-align: center;
}

h3 {
margin-top: 20px;
}

form {
display: flex;
flex-direction: column;
gap: 10px;
width: 400px;
margin: 0 auto; /* Center the form horizontally */
border: 1px solid #ddd;
padding: 20px;
border-radius: 5px;
}

label {
font-weight: bold;
}

input[type="text"],
input[type="email"],
textarea {
padding: 10px;
border: 1px solid #ccc;
border-radius: 3px;
width: 100%;
}

textarea {
min-height: 100px; /* Set a minimum height for the textarea */
}

button[type="submit"] {
padding: 10px 20px;
border: 1px solid #4CAF50; /* Green border for the submit button */
border-radius: 5px;
background-color: #4CAF50; /* Green background */
color: white; /* White text */
cursor: pointer; /* Indicate clickable cursor */
margin-top: 10px;
}
</style>
</head>
<body>
<h1>GET vs POST Example</h1>
<h3>GET Method</h3>
<form action="get_data.php" method="get">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name">

44
<br>
<label for="message">Message:</label>
<textarea id="message" name="message" placeholder="Enter your
message"></textarea>
<br>
<button type="submit">Send (GET)</button>
</form>

<h3>POST Method</h3>
<form action="post_data.php" method="post">
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email">
<br>
<label for="subject">Subject:</label>
<input type="text" id="subject" name="subject" placeholder="Enter your
subject">
<br>
<button type="submit">Send (POST)</button>
</form>
</body>
</html>

get_data.php:

.<?php
// Access data sent using GET method
if (isset($_GET['name']) && isset($_GET['message'])) {
$name = $_GET['name'];
$message = $_GET['message'];
echo "<h3>GET Data</h3>";
echo "Name: $name <br>";
echo "Message: $message";
} else {
echo "No data received through GET method.";
}
?>

post_data.php:

<?php
// Access data sent using POST method
if (isset($_POST['email']) && isset($_POST['subject'])) {
$email = $_POST['email'];
$subject = $_POST['subject'];
echo "<h3>POST Data</h3>";
echo "Email: $email <br>";
echo "Subject: $subject";
} else {
echo "No data received through POST method.";
}
?>
Ouptut:

45
46
14) WAP which takes input from the HTML form and insert the
values into any database table, fields containing full
name, email id, address, contact, DOB, sex.
Code:
Html:

<!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>
<link rel="stylesheet" href="[Link]">
<script src="[Link]"></script>
</head>
<body>
<h1>Registration Form</h1>
<form id="registrationForm" action="[Link]" method="post">
<div class="form-group">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName" placeholder="Enter your full
name" required>
<span id="fullNameError"></span>
</div>

<div class="form-group">
<label for="email">Email ID:</label>
<input type="email" id="email" name="email" placeholder="Enter your email"
required>
<span id="emailError"></span>
</div>

<div class="form-group">
<label for="address">Address:</label>
<textarea id="address" name="address" placeholder="Enter your address"
required></textarea>
<span id="addressError"></span>
</div>

<div class="form-group">
<label for="contact">Contact Number:</label>
<input type="tel" id="contact" name="contact" placeholder="Enter your contact
number" pattern="[0-9]{10}" required>
<span id="contactError"></span>
</div>

<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>
</div>

<div class="form-group">
<label for="sex">Sex:</label>
<select id="sex" name="sex" required>

47
<option value="">Select Sex</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
</div>

<button type="submit" id="submitButton">Register</button>


</form>
</body>
</html>

CSS:

body {
font-family: sans-serif;
margin: 20px;
}

#registrationForm {
display: flex;
flex-direction: column;
gap: 15px;
width: 400px;
background-color: #f5f5f5;
border-radius: 5px;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.form-group {
display: flex;
flex-direction: column;
gap: 5px;
}

label {
font-weight: bold;
}

input[type="text"],
input[type="email"],
input[type="tel"],
textarea {
padding: 10px;
border: 1px solid #ccc;
border-radius: 3px;
width: 100%;
}

[Link] {
color: red;
font-size: smaller;
}

#submitButton {
padding: 10px 20px;

48
border: 1px solid #4CAF50; /* Green border */
border-radius: 5px;
background-color: #4CAF50; /* Green background */
color: white; /* White text */
cursor: pointer; /* Indicate clickable cursor */
margin-top: 10px;
}

/* Added styles for a more visually appealing form */


input[type="text"]:focus,
input[type="email"]:focus,
input[type="tel"]:focus,
textarea:focus {
outline: none; /* Remove default outline on focus */
border-color: #4CAF50; /* Change border color on focus */
}

JavaScript:

.<?php
const fullNameInput = [Link]("fullName");
const emailInput = [Link]("email");
const addressInput = [Link]("address");
const contactInput = [Link]("contact");
const fullNameError = [Link]("fullNameError");
const emailError = [Link]("emailError");
const addressError = [Link]("addressError");
const contactError = [Link]("contactError");
const submitButton = [Link]("submitButton");

[Link]("click", (event) => {


[Link](); // Prevent default form submission

// Reset error messages


[Link] = "";
[Link] = "";
[Link] = "";
[Link] = "";

// Validation logic
let isValid = true;

// Name validation (basic example)


if ([Link]() === "") {
[Link] = "Full name is required.";
isValid = false;
}

// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (![Link]([Link])) {
[Link] = "Please enter a valid email address.";
isValid = false;
}

// Address validation (basic example)


if ([Link]() === "") {

49
[Link] = "Address is required.";
isValid = false;
}

// Contact number validation (basic example)


const contactRegex = /^\d+$/; // Allows only digits
if (![Link]([Link]) || [Link] !== 10) {
[Link] = "Please enter a valid 10-digit contact number.";
isValid = false;
}

// Submit the form if everything is valid


if (isValid) {
// Your form submission logic here (e.g., send data using AJAX or form
submission)
alert("Form submitted successfully!");
}
});

[Link]:

<?php
// Database connection details (replace with your own)
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "users";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Extract form data and perform basic validation (optional)


$fullName = trim($_POST["fullName"]);
$email = trim($_POST["email"]);
$address = trim($_POST["address"]);
$contact = trim($_POST["contact"]);
$dob = $_POST["dob"];
$sex = $_POST["sex"];

// Additional validation (e.g., email format, phone number format) can be added
here

// Prepare SQL statement (prevents SQL injection)


$sql = "INSERT INTO users (full_name, email, address, contact, dob, sex) VALUES (?,
?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);

// Bind values to prepared statement


$stmt->bind_param("ssssss", $fullName, $email, $address, $contact, $dob, $sex);

// Execute the statement


if ($stmt->execute()) {

50
echo "New record created successfully!";
} else {
echo "Error: " . $stmt->error;
}

$stmt->close();
$conn->close();
?>
Ouptut:

51
15) WAP to retrieve the data from any database and show in
the browser. The data should be in table format columns and
must contain action filed which must have edit, delete
[Link] clicking them, the database field should
edit/delete as given.
Code:
db_connect.php:

<?php
// Define database connection variables
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

[Link]:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Data</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Student Data</h1>
<table class="data-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Program</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
include 'db_connect.php';

52
$sql = "SELECT id, name, email, phone, program FROM info";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["email"] . "</td>";
echo "<td>" . $row["phone"] . "</td>";
echo "<td>" . $row["program"] . "</td>";
echo "<td>";
echo "<a href='[Link]?id=" . $row["id"] . "' class='edit-btn'>Edit</a>";
echo "<a href='[Link]?id=" . $row["id"] . "' class='delete-btn'
onclick='return confirmDelete()'>Delete</a>";
echo "</td>";
echo "</tr>";
}
} else {
echo "<tr><td colspan='6'>No students found.</td></tr>";
}
$conn->close();
?>
</tbody>
</table>
<script>
function confirmDelete() {
return confirm("Are you sure you want to delete this student?");
}
</script>
</body>
</html>

[Link]:

<?php
include 'db_connect.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) {


$id = $_GET['id'];
$sql = "SELECT * FROM info WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
// Display edit form with CSS styling
echo"<h2 style='text-align:center'>Edit Student Data</h2>";
echo "<form action='[Link]' method='post' style='max-width: 400px; margin:
0 auto;'>";
echo "<input type='hidden' name='id' value='" . $row["id"] . "'>";
echo "<div style='margin-bottom: 10px;'>";
echo "<label for='name' style='display: block; margin-bottom:
5px;'>Name:</label>";

53
echo "<input type='text' id='name' name='name' value='" . $row["name"] . "'
style='width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-
sizing: border-box;'>";
echo "</div>";
echo "<div style='margin-bottom: 10px;'>";
echo "<label for='email' style='display: block; margin-bottom:
5px;'>Email:</label>";
echo "<input type='email' id='email' name='email' value='" . $row["email"] . "'
style='width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-
sizing: border-box;'>";
echo "</div>";
echo "<div style='margin-bottom: 10px;'>";
echo "<label for='phone' style='display: block; margin-bottom:
5px;'>Phone:</label>";
echo "<input type='tel' id='phone' name='phone' value='" . $row["phone"] . "'
style='width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-
sizing: border-box;'>";
echo "</div>";
echo "<div style='margin-bottom: 10px;'>";
echo "<label for='program' style='display: block; margin-bottom:
5px;'>Program:</label>";
echo "<input type='text' id='program' name='program' value='" . $row["program"]
. "' style='width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px;
box-sizing: border-box;'>";
echo "</div>";
echo "<button type='submit' style='background-color: #4CAF50; color: white;
padding: 10px 20px; border: none; border-radius: 4px; cursor:
pointer;'>Update</button>";
echo "</form>";
} else {
echo "Student not found.";
}
} else {
echo "Invalid request.";
}
$conn->close();
?>

[Link]:

<?php
include 'db_connect.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) {


$id = $_GET['id'];
$sql = "DELETE FROM info WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
header("Location: [Link]");
exit;
} else {
echo "Error deleting student.";
}
} else {
echo "Invalid request.";
}

54
$conn->close();
?>

[Link]:

body {
font-family: Arial, sans-serif;
margin: 20px;
}

h1 {
text-align: center;
}

.data-table {
width: 100%;
border-collapse: collapse;
}

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

.data-table th {
background-color: #f2f2f2;
text-align: left;
}

.edit-btn,
.delete-btn {
display: inline-block;
padding: 5px 10px;
margin-right: 5px;
background-color: #4CAF50;
color: #fff;
text-decoration: none;
border-radius: 4px;
}

.delete-btn {
background-color: #f44336;
}
Ouptut:

49
16) WAP showing a example of AJAX connecting to a database
and retrieving data in asynchronous way.
Code:
Html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Information</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
text-align: center;

50
}
#employee-table {
width: 100%;
border-collapse: collapse;
}
#employee-table th, #employee-table td {
padding: 8px;
border: 1px solid #ccc;
text-align: left;
}
</style>
</head>
<body>
<h1>Employee Information</h1>
<div id="employee-list">
<table id="employee-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Department</th>
</tr>
</thead>
<tbody>
<!-- Employee data will be populated here -->
</tbody>
</table>
</div>
<script>
[Link]("DOMContentLoaded", function() {
var xhr = new XMLHttpRequest();
[Link] = function() {
if ([Link] === [Link]) {
if ([Link] === 200) {
var data = [Link]([Link]);
if (data && [Link] > 0) {
var html = '';
[Link](function(employee) {
html += '<tr>';
html += '<td>' + [Link] + '</td>';
html += '<td>' + [Link] + '</td>';
html += '<td>' + [Link] + '</td>';
html += '<td>' + [Link] + '</td>';
html += '</tr>';
});
[Link]('employee-
table').getElementsByTagName('tbody')[0].innerHTML = html;
} else {
[Link]('employee-list').innerHTML = '<p>No employees
found.</p>';
}
} else {
[Link]('Error:', [Link]);
}
}
};

51
[Link]('GET', 'get_employees.php', true);
[Link]('Content-Type', 'application/json');
[Link]();
});
</script>
</body>
</html>

get_employees.php:

<?php
// Database connection details (replace with your own)
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employee";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Fetch employee data from the database


$sql = "SELECT id, name, email, department FROM info";
$result = $conn->query($sql);

$employees = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$employees[] = array(
'id' => $row['id'],
'name' => $row['name'],
'email' => $row['email'],
'department' => $row['department']
);
}
}

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

// Return employee data as JSON


header('Content-Type: application/json');
echo json_encode($employees);
?>

52
Ouptut:

53

You might also like