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

FSWD Lab Manual (1-8) - (Program&Output Only) - IT3511

The document contains HTML and CSS code for a personal portfolio website and a to-do list application. The portfolio features sections for an about me, projects, resume, and contact information, while the to-do list allows users to add tasks. Both documents include styling to enhance the user interface and experience.

Uploaded by

rmshaira
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)
44 views65 pages

FSWD Lab Manual (1-8) - (Program&Output Only) - IT3511

The document contains HTML and CSS code for a personal portfolio website and a to-do list application. The portfolio features sections for an about me, projects, resume, and contact information, while the to-do list allows users to add tasks. Both documents include styling to enhance the user interface and experience.

Uploaded by

rmshaira
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/ 65

Exercise:01

SOURCE CODE 1:

ex1.html

<html>
<head>
<meta charset="UTF-8">
<title>xyz - Portfolio</title>
<link rel="stylesheet" href="ex1.css">
</head>
<body>
<header>
<h1><b>xyz</b></h1>
<nav class="horizontal-nav">
<ul>
<li><a href="#About">About</a></li>
<li><a href="#portfolio">Projects</a></li>
<li><a href="#resume">Resume</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<section id="About" class="resume">
<h2>About Me</h2>
<img src="https://plus.unsplash.com/premium_photo-1673384114856-
09a46c483b99?w=600&auto=format&fit=crop&q=60&ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MXx8UFJPSkVDVDElMjBpbWFnZXxlbnwwfHwwf
Hx8MA%3D%3D" alt="Your Name">
<p>Hello, I'm <strong>XYZ</strong>. I am a passionate <em>web developer</em> with a
strong foundation in front-end and back-end technologies. I have a keen interest in creating beautiful
and functional websites that deliver a great user experience.</p>
<p>In my free time, I enjoy coding, exploring the latest web development trends, and sharing my
knowledge with the community. Feel free to browse through my portfolio to see some of my recent
projects.</p>
</section>
<section id="portfolio" class="resume">
<!-- Add your portfolio items here -->
<h2>Project Details</h2>
<div>
<img src="https://media.istockphoto.com/id/1074983828/photo/sharing-ideas-concepts-with-
papernote-writing-strategy-on-wall-glass-office-business-
marketing.webp?a=1&b=1&s=612x612&w=0&k=20&c=Z1YwkBtEqhdz72ALF1ohvS2WRTweJrIBt
GQFD__bm8Y=" alt="Project 1">
<h3>Project 1</h3>
<p>Description of Project 1 goes here.</p>
<a href="project1.html">View Details</a>
</div>
<div >
<img src="https://media.istockphoto.com/id/1363104915/photo/presentation-in-multi-ethnic-
office-conference-room-meeting-of-diverse-young-
entrepreneurs.jpg?s=612x612&w=0&k=20&c=AiIsOa78mSwtrgdxpfXZF0ScwLhwxWUisT6QQ-
95jBk=" alt="Project 2">
<h3>Project 2</h3>
<p>Description of Project 2 goes here.</p>
<a href="project2.html">View Details</a>
</div>
</section>
<div id="resume">
<section class="resume">
<h2>Resume</h2>
<p>Click the button below to download my resume:</p>
<a href="ex1.pdf" download="1.pdf">Download Resume</a>
</section>
</div>
<section id="contact" class="resume">
<h2>Contact Information</h2>
<div class="contact-info">
<p><strong>Email:</strong> [email protected]</p>
<p><strong>Phone:</strong> (123) 456-7890</p>
<p><strong>LinkedIn:</strong><a href="https://www.linkedin.com/in/xyz"
target="_blank">Your LinkedIn Profile</a></p>
<p><strong>GitHub:</strong><a href="https://github.com/xyz" target="_blank">Your GitHub
Profile</a></p>
</div>
</section>
<footer> <!-- Add footer information if necessary --> </footer>
</body>
</html>

ex1.css

body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
header {
background-color: #db6a0d;
color: #0c0404;
text-align: center;
padding: 20px;
}
h1 {
margin: 0;
}
.resume {
background-color: #1fcdb6;
padding: 20px;
margin: 30px;
border-radius: 20px;
}
a{
display: inline-block;
padding: 10px 20px;
background-color: #f317cb;
color: #0a0808;
text-decoration: none;
border-radius: 20px;
}

a:hover {
background-color: #a33535;
}
.horizontal-nav {
background-color: #1fcdb6;
}
.horizontal-nav a{
background-color: #1fcdb6;
}

.horizontal-nav ul {
list-style: none;
margin: 0;
padding: 0;
}

.horizontal-nav li {
display: inline;
margin-right: 20px;
}

.horizontal-nav a {
text-decoration: none;
color: #fff;
font-weight: bold;
padding: 10px;
}
.horizontal-nav a:hover {
background-color: #555;
border-radius: 5px;
}

OUTPUT 1:
Source 2 code:
Form1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portfolio</title>
<style>
body{
margin: 0px;
}
.main1{
position: relative;
width: 100%;
height: 70px;
background-color: rgb(192, 189, 16);
}
.main11{
position: absolute;
top: 50%;
left: 20%;
transform: translate(-50%,-50%);
font-size: xx-large;
color: rgb(1, 11, 11);
}
.main12{
position: absolute;
right: 10px;
bottom: 0px;
color: rgb(172, 49, 55);
}
.main12 td :hover{
color: black;
}
.main12 td{
padding-left: 30px;
font-size: x-large;
}
.main2{
position: relative;
width: 100%;
height: 800px;
}
.main2 img{
width: 100%;
height: 100%;
}
.main21{
position: absolute;
top: 0px;
left: 80px;
font-size: xx-large;
color: rgb(161, 22, 22);
}
.main22{
position: absolute;
top: 100px;
right: 100px;
width: 500px;
height: 500px;
}
.main22 img{
width: 300px;
height: 300px;
border-radius: 150px;
}
.hidden{
position: absolute;
top: 200px;
right: 600px;
display: none;
color: rgb(0, 0, 0);
font-size: xx-large;
}
.hidden img{
width:45px;
height: 45px;
}
.hidden td :hover{
width:100px;
height: 95px;
/* border: 2px solid azure; */
box-shadow: 6px 6px 6px rgb(212, 159, 36);
}
.hidden td{
padding: 30px;
}
.main23{
position: absolute;
top: 350px;
left: 100px;
}
.main23 img{
width: 40px;
}
.main23 td :hover{
width: 50px;
background-color: rgb(232, 14, 166);
}
.main23 td{
padding-left: 40px;
text-align: center;
}
.main23 a{
text-decoration: none;
color: rgb(200, 52, 52);
}
footer{
background-color: rgb(192, 189, 16);
height: 100px;
text-align: center;
color: rgb(0, 0, 0);
font-size: xx-large;
}
.main24{
position: absolute;
top: 440px;
left: 130px;
}
.main24 button{
width: 150px;
height: 40px;
font-size: x-large;
font-style: italic;
border-radius: 30px;
background-color: rgb(192, 189, 16);
color: rgb(1, 8, 8);
}
.main24 :hover{
background-color: rgb(186, 59, 97);
}
.main12 a{
text-decoration: none;
/*color: azure;*/
}
footer{
bottom: 10px;
margin-bottom: 10px;}
</style>
</head>
<body>
<div class="main1">
<div class="main11">
<h1>Shaira</h1>
</div>
<div class="main12">
<table>
<tr><td><a href="form1.html"><b>Home</b></a></td>
<td><a href="form1.html"><b>Education</b></a></td>
<td><b>Skills</b></td>
<td><b>Experience</b></td>
<td><b>Contact</b></td>
</tr>
</table>
</div>
</div>
<div class="main2">
<img src="https://www.peaawards.com/wp-content/uploads/2016/05/portfolio-background.jpg"
alt="">
<div class="main21">
<h1 id="h1">Hi there,</h1>
<h1 id="h2">This is <span style="color: rgb(14, 17, 110);">Shaira</span></h1>
<h2 id="h3">Assistant Professor</h2>
</div >
<div class="main22">
<img
src="https://tse1.mm.bing.net/th?id=OIP.PYLwHy47wcaho3nG1V3rGAHaHa&pid=Api&P=0&h=180
" alt="" id="i1">
</div>
<div class="hidden" id="hidden">

<table>
<tr>
<td><img src="https://tse1.mm.bing.net/th?id=OIP.bkbn2-
K7c9rMBV5dvYXDrQHaIh&pid=Api&rs=1&c=1&qlt=95&w=78&h=90" alt=""></td>
<td><img src="https://tse1.mm.bing.net/th?id=OIP.ggb-3B-
8LRfbgS0lPLYNxwHaIU&pid=Api&rs=1&c=1&qlt=95&w=80&h=90" alt=""></td>
<td><img
src="https://th.bing.com/th/id/OIP.cIy6EEdlrO0RQelinI20aQHaEK?w=286&h=180&c=7&r=0&o=5&
dpr=1.5&pid=1.7" alt=""></td>
<td><img src="https://cdn4.iconfinder.com/data/icons/logos-3/600/React.js_logo-
128.png" alt=""></td>
<td><img src="https://cdn2.iconfinder.com/data/icons/amazon-aws-
stencils/100/SDKs_copy_nodeJS-64.png" alt=""></td>
<td><img
src="https://ajeetchaulagain.com/static/7cb4af597964b0911fe71cb2f8148d64/87351/express-js.png"
alt=""></td>
<td><img src="https://marketplacedesignoye.s3.ap-south-1.amazonaws.com/mongodb-
branding-icon-symbol-logo-vector-_1540.png" alt=""></td>
</tr>
</table>
</div>
<div class="main23">
<table>
<tr>
<td><a href="https://www.linkedin.com/in/shairabanu-shahardeen-96ba63279/"
target="_blank"><b><img src="https://cdn-icons-png.flaticon.com/128/1384/1384014.png"
alt=""></b></a></td>
<td><a href="https://www.instagram.com/accounts/password/reset/"
target="_blank"><b><img src="https://cdn-icons-png.flaticon.com/128/1384/1384031.png" alt=""
></b></a></td>
</tr>
</table>

</div>
<div class="main24">
<button id="b1">About</button>
</div>

</div>
<footer>
<b> [email protected]</b>
</footer>
<script>
document.getElementById("b1").onclick=function(){
document.getElementById("h1").innerHTML="LANGUAGES KNOWN ";
document.getElementById("h2").innerHTML=" ";
document.getElementById("h3").innerHTML=" ";
document.getElementById("hidden").style.display='block';
}
</script>
</body>
</html>
OUTPUT 2:
Exercise:02
ex2.html

<html>
<head>
<link rel="stylesheet" href="ex2.css">
</head>
<body>
<div class="container">
<div class="todo-app">
<h2>To-Do List <img
src="https://th.bing.com/th/id/OIP.bf_Um5shxy9Snj8HbRR0ZAHaHa?w=199&h=199&c=7&r=0&o=
5&dpr=1.5&pid=1.7"></h2>
<div class="row">
<input type="text" id="input-box" placeholder="Add your text">
<button onclick="addTask()">Add</button>
</div>
<ul id="list-container"> </ul>
</div>
</div>
<script src="ex2.js"></script>
</body>
</html>

ex2.css

*{
margin:0;
padding:0;
font-family:'poppins',sans-serif;
box-sizing:border-box;
}
.container{
width:100%;
min-height:100vh;
background:linear-gradient(135deg,#e0341d,#30c261);
padding:10px;
}
.todo-app{
width:100%;
max-width:540px;
background:#fff;
margin:100px auto 20px;
padding: 40px 30px 70px;
border-radius: 10px;
}
.todo-app h2{
color:#650011;
display:flex;
align-items:center;
margin-bottom: 20px;
}
.todo-app h2 img{
width:30px;
margin-left: 10px;
}
.row{
display:flex;
align-items:center;
justify-content: space-between;
background: #edeef0;
border-radius:30px;
padding-left:20px;
margin-bottom: 25px;
}
input{
flex:1;
border:none;
outline:none;
background:transparent;
padding:10px;
font-weight:14px;
}
button{
border:none;
outline:none;
padding:16px 50px;
background:#ff5945;
color:#fff;
font-size:16px;
cursor:pointer;
border-radius:40px;
}
ul li{
list-style: none;
font-size: 17px;
padding:12px 8px 12px 50px;
user-select: none;
cursor: pointer;
position: relative;
}
ul li::before{
content: '';
position: absolute;
height: 28px;
width: 28px;
border-radius:50%;
background-image:url(https://cdn.pixabay.com/photo/2013/07/12/17/40/checkbox-
152188_960_720.png);
background-size: cover;
background-position: center;
top:12px;
left:8px;
}
ul li.checked{
color:#555;
text-decoration: line-through;
}
ul li.checked::before{
background-
image:url(https://th.bing.com/th/id/R.04d6bea90fa0944aaae9734cb26cb528?rik=5xhIC1iPy8bWgA&ri
u=https%3a%2f%2ffanyv88.com%3a443%2fhttp%2fwww.pngmart.com%2ffiles%2f16%2fTick-Green-Check-Mark-PNG-
Photos.png&ehk=6oelccNgeq6IIZhhRFPyphMtaIHGxH%2bIWoTeXbUglKM%3d&risl=&pid=ImgR
aw&r=0);
}
ul li span{
position: absolute;
right: 0;
top:5px;
width: 40px;
height: 40px;
font-size: 22px;
color:#555;
line-height: 40px;
text-align: center;
border-radius: 50%;
}
ul li span:hover{
background: #1148b5;
}

ex2.js

const inputBox=document.getElementById("input-box");
const listContainer=document.getElementById("list-container");
function addTask(){
if(inputBox.value===''){
alert("you must write something");
}
else{
let li=document.createElement("li");
li.innerHTML=inputBox.value;
listContainer.appendChild(li);
let span=document.createElement("span");
span.innerHTML="\u00d7";
li.appendChild(span);
}
inputBox.value="";
saveData();
}
listContainer.addEventListener("click",function(e){
if(e.target.tagName==="LI"){
e.target.classList.toggle("checked");
saveData();
}
else if(e.target.tagName==="SPAN"){
e.target.parentElement.remove();
saveData();
}
},false);
function saveData(){
localStorage.setItem("data",listContainer.innerHTML);
}

OUTPUT
Exercise:03
ex3.html

<!DOCTYPE html>
<html>
<head>
<title>Microblog</title>
<link rel="stylesheet" type="text/css" href="/ex3.css">
</head>
<body>
<h1>Microblog</h1>
<form action="/create" method="POST">
<input type="text" name="title" placeholder="Title" required>
<textarea name="content" placeholder="Content" required></textarea>
<button type="submit">Create Post</button>
</form>
<ul>
<% posts.forEach(post => { %>
<li>
<h2><%= post.title %></h2>
<p><%= post.content %></p>
<p><em><%= post.timestamp.toLocaleString() %></em></p>
</li>
<% }); %>
</ul>
</body>
</html>

ex3.css

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
h1 {
text-align: center;
margin: 20px 0;
}
form {
display: flex;
flex-direction: column;
align-items: center;
}
input[type="text"],
textarea {
width: 80%;
padding: 10px;
margin: 5px 0;
}
button {
padding: 10px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}
ul {
list-style: none;
padding: 0;
}
li {
border: 1px solid #ccc;
padding: 10px;
margin: 10px 0;
}

post.js

const mongoose = require('mongoose');


const postSchema = new mongoose.Schema({
title: String,
content: String,
timestamp: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Post', postSchema);

server.js

const express = require('express');


const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Post = require('./models/Post');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
mongoose.connect('mongodb://127.0.0.1:27017/microblog_db', { useNewUrlParser: true,
useUnifiedTopology: true });
app.set('view engine', 'ejs');
// Set up middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.get('/', async (req, res) => {
const posts = await Post.find().sort({ timestamp: -1 });
res.render('./index1.ejs', { posts });
});
app.post('/create', async (req, res) => {
const { title, content } = req.body;
const newPost = new Post({ title, content });
await newPost.save();
res.redirect('/');
});
// Start the server
app.listen(3000, () => {
console.log(`Server is running on port ${PORT}`);
});

Output:
Server is running on port 3000
Exercise:04
ex4.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="ex4.css">
<title>Food Delivery</title>
</head>
<body>
<header>
<h1>Food Delivery</h1>
</header>
<table>

<div class="menu">
<tr>
<td>
<div class="item">
<img src="https://freepngimg.com/thumb/burger/4-2-burger-png-file.png" alt="Burger">
<h2>Burger</h2>
<p>Delicious burger with all the fixings.</p>
<span class="price">$243.99</span>
<button class="add-to-cart">Add to Cart</button>
</div>
</td>
<td>
<div class="item">
<img src="http://www.pngall.com/wp-content/uploads/2016/05/Pizza-Free-PNG-Image.png"
alt="Pizza">
<h2>Pizza</h2>
<p>Classic cheese pizza with tomato sauce.</p>
<span class="price">$90.66</span>
<button class="add-to-cart">Add to Cart</button>
</div>
</td>
<td>
<div class="item">
<img
src="https://tse4.mm.bing.net/th?id=OIP.E1rbpg4YKmjAXhsyA8Gh9QHaE8&pid=Api&P=0&h=180
" alt="Veg">
<h2>Vegetable Briyani</h2>
<p>Dish made with rice, veggies & spices.</p>
<span class="price">$90.99</span>
<button class="add-to-cart">Add to Cart</button>
</div>
<!-- Add more items here -->
</div>
</td>
<td></td>
<td>
<div class="cart">
<h2 style="text-align: center;color: blue;">Cart</h2>
<ul id="cart-items"></ul>
<h3>Total: $<span id="cart-total">0.00</span></h3>
</div>
</td>
</tr>
</table>
<script src="ex4.js"></script>
</body>
</html>

ex4.css

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #f03a3a;
color: rgb(19, 18, 18);
text-align: center;
padding: 5px;
}
.item {
border: 1px solid #ddd;
padding: 5px;
margin: 5px;
text-align: center;
width: 180px;
background-color: #30d7e3;
border-radius:15px;
}
.item img {
max-width: 100%;
}
.price {
font-weight: bold;
}
.add-to-cart {
background-color: #e360bc;
color: rgb(7, 9, 10);
border: none;
padding: 5px 10px;
cursor: pointer;
border-radius:20px;
}
.cart {
border: 1px solid #ddd;
padding: 10px ;
position: fixed;
top: 200px;
right: 350px;
width: 200px;
background-color: #e360bc;
border-radius: 30px;
}

ex4.js

const addToCartButtons = document.querySelectorAll('.add-to-cart');


const cartItemsList = document.getElementById('cart-items');
const cartTotal = document.getElementById('cart-total');
let total = 0;
const cart = {};
addToCartButtons.forEach(button => {
button.addEventListener('click', () => {
const item = button.parentElement;
const itemName = item.querySelector('h2').textContent;
const itemPrice = parseFloat(item.querySelector('.price').textContent.slice(1));
if (cart[itemName]) {
cart[itemName] += 1;
} else {
cart[itemName] = 1;
}
total += itemPrice;
updateCart();
});
});
function updateCart() {
cartItemsList.innerHTML = '';
for (const item in cart) {
const li = document.createElement('li');
li.textContent = `${item} x ${cart[item]}`;
cartItemsList.appendChild(li);
}
cartTotal.textContent = total.toFixed(2);
}
OUTPUT
Exercise:05

product.js

const mongoose = require('mongoose');


const productSchema = new mongoose.Schema({
title: String,
description: String,
price: Number,
status: { type: String, enum: ['available', 'purchased'], default: 'available' }
});
const Product = mongoose.model('Product', productSchema);
module.exports = Product;

User.js

const mongoose = require('mongoose');


const userSchema = new mongoose.Schema({
username: String,
email: String,
password: String,
});
module.exports = mongoose.model('User', userSchema);

app.js

document.addEventListener('DOMContentLoaded', () => {
const productList = document.getElementById('product-list');
// Function to fetch and display product listings
const fetchProducts = () => {
fetch('/api/products')

.then(response => response.json())


.then(products => {
productList.innerHTML = ''; // Clear existing list
products.forEach(product => {
const li = document.createElement('li');
li.textContent = `${product.title} - $${product.price}`;
// Add a "Buy" button for each product
const actionButton = document.createElement('button');
if (product.status === 'purchased') {
actionButton.textContent = 'Purchased';
actionButton.disabled = true;
} else {
actionButton.textContent = 'Buy';
actionButton.addEventListener('click', () => buyProduct(product._id, actionButton));
}
li.appendChild(actionButton);
productList.appendChild(li);
});
})
.catch(error => console.error('Error fetching products:', error));
};
// Call the fetchProducts function initially and after creating a listing
fetchProducts();
// Create a new product listing
const createListingButton = document.getElementById('create-listing-button');
createListingButton.addEventListener('click', () => {
const title = document.getElementById('title').value;
const description = document.getElementById('description').value;
const price = document.getElementById('price').value;
const newData = {
title: title,
description: description,
price: price
};
fetch('/api/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newData)
})
.then(response => response.json())
.then(product => {
console.log('Product created:', product);
// Clear input fields
document.getElementById('title').value = '';
document.getElementById('description').value = '';
document.getElementById('price').value = '';
// Fetch and display products after creating a listing
fetchProducts();
})
.catch(error => console.error('Error creating product:', error));
});

// Buy a product
const buyProduct = (productId, actionButton) => {
fetch(`/api/products/${productId}/buy`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(updatedProduct => {
console.log('Product purchased:', updatedProduct);
// Update the button text to "Purchased" and disable it
actionButton.textContent = 'Purchased';
actionButton.disabled = true;
// Optionally, you can add a CSS class to style the "Purchased" button differently
actionButton.classList.add('purchased-button');
})
.catch(error => console.error('Error purchasing product:', error));
};
// Initial fetch and display of products
fetchProducts();
});

index.html

<!DOCTYPE html>
<html>
<head>
<title>Classifieds App</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Welcome to Classifieds App</h1>
<h2>Product Listings</h2>
<ul id="product-list"></ul>
<h2>Create a Listing</h2>
<form id="create-listing-form">
<label for="title">Title:</label>
<input type="text" id="title" required><br>
<label for="description">Description:</label>
<textarea id="description" required></textarea><br>
<label for="price">Price:</label>
<input type="number" id="price" required><br>
<button type="button" id="create-listing-button">Create Listing</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="app.js"></script>
</body>
</html>
style.css

<!DOCTYPE html>
<html>
<head>
<title>Classifieds App</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Welcome to Classifieds App</h1>
<h2>Product Listings</h2>
<ul id="product-list"></ul>
<h2>Create a Listing</h2>
<form id="create-listing-form">
<label for="title">Title:</label>
<input type="text" id="title" required><br>
<label for="description">Description:</label>
<textarea id="description" required></textarea><br>
<label for="price">Price:</label>
<input type="number" id="price" required><br>
<button type="button" id="create-listing-button">Create Listing</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="app.js"></script>
</body>
</html>

style.css

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

}
h1 {
color: #333;
}
h2 {
color: #555;
margin-top: 20px;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 10px 0;
padding: 10px;
border: 1px solid #ddd;
background-color: #f9f9f9;
}
label {
display: inline-block;
width: 100px;
}
input, textarea {
width: 300px;
padding: 5px;
margin-bottom: 10px;
}
button {
background-color: #8e2727;
color: #fff;
padding: 5px 10px;
border: none;
cursor: pointer;
border-radius: 20px;
}
/* Style for the "Purchased" button */
.purchased-button {
background-color: #ccc;
color: #888;
cursor: not-allowed;
}

productRoute.js
const express = require('express');
const router = express.Router();
const Product = require('../models/product');
// Create a new product listing
router.post('/', async (req, res) => {
try {
const newProduct = await Product.create(req.body);
res.json(newProduct);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// Get all product listings
router.get('/', async (req, res) => {
try {
const products = await Product.find();
res.json(products);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// Update product status to mark as purchased
router.put('/:productId/buy', async (req, res) => {
try {
const productId = req.params.productId;
// Find the product by ID and update its status or relevant fields
const updatedProduct = await Product.findByIdAndUpdate(
productId,
{ $set: { status: 'purchased' } }, // Update the status or relevant fields here
{ new: true } // Return the updated product
);
if (!updatedProduct) {
return res.status(404).json({ message: 'Product not found' });
}
res.json(updatedProduct);
} catch (error) {
console.error('Error buying product:', error);
res.status(500).json({ message: 'An error occurred while buying the product' });
}
});
module.exports = router;

userRoute.js

const express = require('express');


const router = express.Router();
const User = require('../models/User');
// User registration
router.post('/register', async (req, res) => {
try {
const newUser = await User.create(req.body);
res.json(newUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
module.exports = router;

server.js

const express = require('express');


const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path'); // Import the 'path' module
const app = express();
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/classifieds', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(express.static(path.join(__dirname, 'public')));
// Routes
const userRoutes = require('./route/userRoute');
const productRoutes = require('./route/productRoute');
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);

const PORT = process.env.PORT || 4000;


app.listen(4000, () => {
console.log(`Server is running on port ${PORT}`);
});

OUTPUT:
C:\Users\MAC PRO\OneDrive\Desktop\FULLSTACKLAB\EX5CLASSIFIEDS> npm install express

PS C:\Users\MAC PRO\OneDrive\Desktop\FULLSTACKLAB\EX5CLASSIFIEDS> npm install mongoose

C:\Users\MAC PRO\OneDrive\Desktop\FULLSTACKLAB\EX5CLASSIFIEDS> npm install body-parser

PS C:\Users\MAC PRO\OneDrive\Desktop\FULLSTACKLAB\EX5CLASSIFIEDS> npm install cors

C:\Users\MAC PRO\OneDrive\Desktop\FULLSTACKLAB\EX5CLASSIFIEDS> npm install path

PS C:\Users\MAC PRO\OneDrive\Desktop\FULLSTACKLAB\EX5CLASSIFIEDS> npm start


Exercise:06

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Leave Management System</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>Welcome to Leave Management System</h1>
<form action="http://localhost:4000/apply" method="POST">
<label for="employeeName">Employee Name:</label>
<input type="text" id="employeeName" name="employeeName" required>
<br>
<label for="leaveType">Leave Type:</label>
<select id="leaveType" name="leaveType" required>
<option value="vacation">Vacation</option>
<option value="sick">Sick Leave</option>
</select>
<br>
<label for="startDate">Start Date:</label>
<input type="date" id="startDate" name="startDate" required>
<br>
<label for="endDate">End Date:</label>
<input type="date" id="endDate" name="endDate" required>
<br>
<button type="submit">Submit</button>
</form>
</body>
</html>

style.css

body {
font-family: Arial, sans-serif;
text-align: center;
margin: 50px;
background-color: aqua;
}
h1 {
color: #e41776;
font-family:cursive;
}
form {
margin: 20px auto;s
width: 300px;
border:#e41776 solid;
padding: 20px;
border-radius: 40px;
}
label {
display: block;
margin-bottom: 5px;

}
input[type="text"],
input[type="date"],
select {
width: 100%;
padding: 5px;
margin-bottom: 10px;
border-radius: 50px;
}
button {
background-color: #ba1770;
color: #fff;
border: none;
padding: 10px 20px;
cursor: pointer;
border-radius: 40px;
margin-left:10px;
}

server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended:false }));
mongoose.connect('mongodb://127.0.0.1:27017/leave_management_system', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on('open', () => { });
// Define a LeaveRequest schema
const leaveRequestSchema = new mongoose.Schema({
employeeName: String,
leaveType: String,
startDate: Date,
endDate: Date,
});
// Create a LeaveRequest model
const LeaveRequest = mongoose.model('LeaveRequest', leaveRequestSchema);
app.get('/', (req, res) => {
// Retrieve leave requests from MongoDB
LeaveRequest.find({}, (err, leaveRequests) => {
if (err) {
console.error(err);
res.status(500).send('Internal Server Error');
} else {
res.render('index', { leaveRequests });
}
});
});

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


// Create and save a new leave request
const newLeaveRequest = new LeaveRequest({
employeeName:req.body.employeeName,
leaveType:req.body.leaveType,
startDate:req.body.startDate,
endDate:req.body.endDate
});
newLeaveRequest.save();
res.end("Submitted");
});
const port = process.env.PORT || 4000; // Use the provided port or default to 3000
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
OUTPUT:
Exercise:07
Homepage.js
// PROJECTDASHBOARD\frontend\src\components
import React, { useState } from 'react';
import { useNavigate } from "react-router-dom";
function Homepage() {
const [projectname, setProjectname] = useState('');
const [message, setMessage] = useState('');
const [ Objectid,setObjectid] = useState('');
const navigate=useNavigate();
function handlenewproject(){
navigate("/newproject")
}
const handleProject = async () => {
try {
const response = await fetch('http://localhost:3001/homepage', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ projectname}),
});
if (response.status === 200) {
const data = await response.json();
setObjectid(data.userId);
navigate("/project/",{state:{id:data.userId,projectname:projectname,projectaim:data.projectaim,proje
ctalgorithm:data.projectalgorithm,projectprogram:data.projectprogram,projectoutput:data.projectout
put}});
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
return (<center>
<div><div>
<h2>Search Project</h2>
<input
type="text"
placeholder="Project"
value={projectname}
onChange={(e) => setProjectname(e.target.value)}
/>
<button onClick={handleProject}>Submit</button>
<p>{message}</p>
<br></br>
</div>
<div >
<h1 onClick={handlenewproject}>Create Project</h1>
</div></div></center>
);}; export default Homepage;
Newproject.js
// PROJECTDASHBOARD\frontend\src\components
import React, { useState } from 'react';
function Newproject() {
const [projectname, setProjectname] = useState('');
const [projectaim, setProjectaim] = useState('');
const [projectalgorithm, setProjectalgorithm] = useState('');
const [projectprogram, setProjectprogram] = useState('');
const [projectoutput, setProjectoutput] = useState('');
const [message, setMessage] = useState('');
const handleNewproject = async () => {
try {
const response = await fetch('http://localhost:3001/newproject', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ projectname,projectaim,projectalgorithm,projectprogram,projectoutput
}),
});
if (response.status === 201) {
const data = await response.json();
setMessage(data.message);
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
return (
<center> <div>
<h1>New Project</h1>
<h4>Project name</h4>
<input
type="text"
placeholder="Name"
value={projectname}
onChange={(e) => setProjectname(e.target.value)}
/>
<h4>Aim</h4>
<textarea
type="text"
placeholder="Aim"
value={projectaim}
onChange={(e) => setProjectaim(e.target.value)} rows={5} cols={100}
/>
<h4>Algorithm</h4>
<textarea
type="text"
placeholder="Algorithm"
value={projectalgorithm}
onChange={(e) => setProjectalgorithm(e.target.value)} rows={10} cols={100}
/>
<h4>Program</h4>
<textarea type="text"
placeholder="Program"
value={projectprogram}
onChange={(e) => setProjectprogram(e.target.value)} rows={10} cols={100} />
<h4>Output</h4>
<textarea
type="text"
placeholder="Output"
value={projectoutput}
onChange={(e) => setProjectoutput(e.target.value)} rows={10} cols={100}
/>
<h1></h1>
<button onClick={handleNewproject}>Submit</button>
<p>{message}</p>
</div></center>
);
}
export default Newproject;

Project.js
// PROJECTDASHBOARD\frontend\src\components
import React, { useState } from 'react';
import CanvasJSReact from '@canvasjs/react-charts';
import { useLocation } from 'react-router-dom';
var CanvasJSChart = CanvasJSReact.CanvasJSChart;
function countWordsInParagraph(paragraph) {
const words = paragraph.trim().split(/\s+/);
var a = words.length;
if (paragraph === "") {
a = 0;
}
return a;
}
function percentage(a, b) {
return (a / b) * 100;
}
const Project = () => {
const [message, setMessage] = useState('');
const [projectname, setProjectname] = useState('');
const [projectDetails, setProjectDetails] = useState('');
const location = useLocation();
const state = location.state;
const projectName = state.projectname;
const projectAim = state.projectaim;
const projectAlgorithm = state.projectalgorithm;
const projectProgram = state.projectprogram;
const projectOutput = state.projectoutput;
const projectaimcount = countWordsInParagraph(projectAim);
const projectalgorithmcount = countWordsInParagraph(projectAlgorithm);
const projectprogramcount = countWordsInParagraph(projectProgram);
const projectoutputcount = countWordsInParagraph(projectOutput);
const b = projectaimcount + projectalgorithmcount + projectprogramcount + projectoutputcount;
const options = {
exportEnabled: true,
animationEnabled: true,
title: {
text: projectName.toUpperCase()
},
data: [{
type: "pie",
startAngle: 75,
toolTipContent: "<b>{label}</b>: {y}%",
showInLegend: "true",
legendText: "{label}",
indexLabelFontSize: 16,
indexLabel: "{label} - {y}%",
dataPoints: [
{ y: percentage(projectaimcount, b), label: "Aim" },
{ y: percentage(projectalgorithmcount, b), label: "Algorithm" },
{ y: percentage(projectprogramcount, b), label: "Program" },
{ y: percentage(projectoutputcount, b), label: "Output" },
]
}]
};
const handleInputChange = (fieldName, value) => {
setProjectDetails({
...projectDetails,
[fieldName]: value,
});
};
const [chartVisible, setChartVisible] = useState(false);
const [buttonVisible, setbuttonVisible] = useState(true);
const handlechart = async () => {
setChartVisible(true);
setbuttonVisible(false);
};
const handleHide = async () => {
setChartVisible(false);
setbuttonVisible(true);
};
const handleNewproject = async () => {
try {
const updatedProjectDetails = {
projectname: projectName,
projectaim: projectDetails.projectAim || projectAim,
projectalgorithm: projectDetails.projectAlgorithm || projectAlgorithm,
projectprogram: projectDetails.projectProgram || projectProgram,
projectoutput: projectDetails.projectOutput || projectOutput,
};
const response = await fetch('http://localhost:3001/project', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedProjectDetails),
});
if (response.status === 201) {
const data = await response.json();
setMessage(data.message);
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
return (
<center>
<div>
<h4>Project name</h4>
<input
type="text"
placeholder="Name"
value={projectName}
onChange={(e) => setProjectname(e.target.value)}
/>
<h4>Aim</h4>
<textarea
type="text"
placeholder="Aim"
value={projectDetails.projectAim || projectAim}
onChange={(e) => handleInputChange('projectAim', e.target.value)}
rows={5}
cols={100}
/>
<h4>Algorithm</h4>
<textarea
type="text"
placeholder="Algorithm"
value={projectDetails.projectAlgorithm || projectAlgorithm}
onChange={(e) => handleInputChange('projectAlgorithm', e.target.value)}
rows={10}
cols={100}
/>
<h4>Program</h4>
<textarea
type="text"
placeholder="Program"
value={projectDetails.projectProgram || projectProgram}
onChange={(e) => handleInputChange('projectProgram', e.target.value)}
rows={10}
cols={100}
/>
<h4>Output</h4>
<textarea
type="text"
placeholder="Output"
value={projectDetails.projectOutput || projectOutput}
onChange={(e) => handleInputChange('projectOutput', e.target.value)}
rows={10}
cols={100}
/>
<br />
<button onClick={() => { handleNewproject(); }}>Update</button>
<p>{message}</p>
{chartVisible ? (
<div>
<CanvasJSChart options={options} />
<button onClick={handleHide}>Hide Report</button>
</div>
) : null}
{buttonVisible ? (
<div>
<button onClick={handlechart}>View Report</button>
</div>
) : null}
</div>
</center>
);
};
export default Project;

App.js
// PROJECTDASHBOARD\frontend \src
import React from 'react';
import Project from './components/Project';
import Homepage from './components/Homepage';
import Newproject from './components/Newproject';
import { Route,Routes} from "react-router-dom";
function App() {
return (
<div className="App">
<Routes>
<Route path='/' element={<Homepage />} />
<Route path='/newproject' element={<Newproject />} />
<Route path='/project' element={<Project />} /> {/* Add this route for the Project */}

</Routes>
</div>
);
}
export default App;
index.js
// PROJECTDASHBOARD\frontend \src
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);

user.js
// PROJECTDASHBOARD\backend\models
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
projectname: { type: String, required: true},
projectaim: { type: String },
projectalgorithm: { type: String },
projectprogram: { type: String },
projectoutput: { type: String }
});
module.exports = mongoose.model('User', userSchema);
PROJECTDASHBOARD\backend\routes
homepage.js
const express = require('express');
const router = express.Router();
const UserModel = require('../models/user');
router.post('/', async (req, res) => {
const { projectname } = req.body;
try {
const user = await UserModel.findOne({ projectname });
if (!user) {
return res.status(401).json({ message: 'Project name is wrong' });
}
const userid=user.id;
const projectaim=user.projectaim;
const projectalgorithm=user.projectalgorithm;
const projectprogram=user.projectprogram;
const projectoutput=user.projectoutput;
res.status(200).json({ message: 'Project
successful',userid:userid,projectname,projectaim,projectalgorithm,projectprogram,projectoutput});
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

newproject.js
PROJECTDASHBOARD\backend\routesconst
express = require('express');

const router = express.Router();


const User = require('../models/user');
router.post('/', async (req, res) => {
try {
const { projectname,projectaim,projectalgorithm,projectprogram,projectoutput } = req.body;
const existingUser = await User.findOne({ projectname });
if (existingUser) {
return res.status(409).json({ message: 'Project already exists' });
}
const newUser = new User({
projectname,projectaim,projectalgorithm,projectprogram,projectoutput,
});
await newUser.save();
res.status(201).json({ message: 'Project added successful' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

project.js
// PROJECTDASHBOARD/backend/routes
const express = require('express');
const router = express.Router();
const User = require('../models/user');
router.post('/', async (req, res) => {
try {
const { projectname, projectaim, projectalgorithm, projectprogram, projectoutput } = req.body;
// Find the existing user by projectname
const existingUser = await User.findOne({ projectname});
if (!existingUser) {
return res.status(404).json({ message: 'Project not found' });
}
existingUser.projectaim = projectaim;
existingUser.projectalgorithm = projectalgorithm;
existingUser.projectprogram = projectprogram;
existingUser.projectoutput = projectoutput;
await existingUser.save();
res.status(200).json({ message: 'Project updated successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

index.js
// PROJECTDASHBOARD/backend/
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
const bodyParser = require('body-parser');
dotenv.config();
const app = express();
const port = process.env.PORT || 3001;
// MongoDB connection
mongoose.connect("mongodb://0.0.0.0:27017/gokul", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB');
});
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Routes
const homepageRouter = require('./routes/homepage');
const newprojectRouter = require('./routes/newproject');
const projectRouter = require('./routes/project');
// const leaveRouter = require('./routes/leave');
app.use('/homepage', homepageRouter);
app.use('/newproject', newprojectRouter);
app.use('/project', projectRouter);
// app.use('/leave', leaveRouter);
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
})

Output:
Exercise:08

Login.js
//SURVEY\frontend\src\components
import React, { useState } from 'react';
import { useNavigate } from "react-router-dom";
function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const [objectid, setObjectid] = useState('');
const navigate = useNavigate();
function handlesignup() {
navigate("/signup")
}
const handleLogin = async () => {
try {
const response = await fetch('http://localhost:3001/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
if (response.status === 200) {
const data = await response.json();
setObjectid(data.userId);
console.log("User ID : ", data.userId);
navigate("/Survey/", { state: { id: data.userId, name1: data.name, regno1: data.regno } });
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
return (
<div>
<h2>Login</h2>
<p>{objectid}</p>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>

<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<input
type="text"
placeholder="Reg No."
value={regno}
onChange={(e) => setRegno(e.target.value)}
/>
<button onClick={handleSignup}>Signup</button>
<p>{message}</p>
<br>
</br>
<h1 onClick={handleLogin}>Login</h1>
</div>
);
}
export default Signup;

Survey.js
// SURVEY\frontend\src\components
import React, { useState } from 'react';
import { BarChart, Bar, CartesianGrid, XAxis, YAxis } from 'recharts';
import './Survey.css'
import { useLocation } from "react-router-dom";
const Survey = () => {
const location = useLocation();
const id1 = location.state.id;
const staffNames = ["Manivannan", "Nelson", "Kosalairaman", "MaheshKumar", "Gobinath",
"Umamaheswari"];
const questions = [
{
id: 'q1',
question: '1. The class was very well organized',
},
{
id: 'q2',
question: '2. The instructor was very knowledgeable about the topic that was taught',
},
{
id: 'q3',
question: '3. The instructor was very good at communication',
},
{
id: 'q4',
question: '4. The instructor was motivating and enthusiastic',
},
{
id: 'q5',
question: "5. The instructor's methods helped in understanding the topic better",
},
{
id: 'q6',
question: '6. The grading system was not biased',
},
{
id: 'q7',
question: '7. The facilities provided were up to your expectations',
},
{
id: 'q8',
question: '8. The teaching environment in the class helped in better learning',
},
{
id: 'q9',
question: '9. The hygiene was very well maintained at the facility',
},
{
id: 'q10',
question: '10. Is the instructor biased between three classes',
},
];
const choiceValues = {
'Strongly disagree': 1,
'Somewhat disagree': 2,
'Neutral': 3,
'Somewhat agree': 4,
'Strongly agree': 5,
};
console.log("id :", id1);
console.log("name:", location.state.name1);
console.log("regm=n: ", location.state.regno1);
const [staffMember, setStaffMember] = useState('');
const [Manivannan, setManivannan] = useState('');
const [Nelson, setNelson] = useState('');
const [Kosalairaman, setKosalairaman] = useState('');
const [MaheshKumar, setMaheshKumar] = useState('');
const [Gobinath, setGobinath] = useState('');
const [Umamaheswari, setUmamaheswari] = useState('');
const [responses, setResponses] = useState({});
const [message, setMessage] = useState('Welcome!!!!');
const handleStaffChange = (e) => {
setResponses({});
setStaffMember(e.target.value);
};
const data = [
{ name: 'Manivannan', students: Manivannan },
{ name: 'Nelson', students: Nelson },
{ name: 'Kosalairaman', students: Kosalairaman },
{ name: 'MaheshKumar', students: MaheshKumar },
{ name: 'Gobinath', students: Gobinath },
{ name: 'Umamaheswari', students: Umamaheswari },
];
const review = async () => {
try {
const response = await fetch(`http://localhost:3001/survey/${id1}`);
const data = await response.json();
if (response.ok) {
setManivannan(data.Manivannan);
setNelson(data.Nelson);
setKosalairaman(data.Kosalairaman);
setMaheshKumar(data.MaheshKumar);
setGobinath(data.Gobinath);
setUmamaheswari(data.Umamaheswari);
} else {
console.error('Failed to fetch users:', data.message);
}
} catch (error) {
console.error('Error during user fetch:', error.message);
}
};
const handleSubmit1 = async () => {
if (staffMember === "") {
alert("Please Choose StaffName !!!!!");
}
else {
try {
const response = await fetch('http://localhost:3001/survey', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id1, staffMember, responses }),
});
console.log("id = ", id1);
if (response.status === 200) {
const data = await response.json();
setMessage(data.message);
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
}
};
const handleResponseChange = (questionId, choice) => {
console.log("afjljjflfj");
const value = choiceValues[choice];
setResponses((prevResponses) => ({
...prevResponses,
[questionId]: value,
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Data to be submitted:', {
staffMember,
responses,
});
};
return (
<div className="container">
<h1>Student Survey Form</h1>
<form onSubmit={handleSubmit}>
<p>{message}</p>
<p>Name :{location.state.name1}</p>
<p>RegNo : {location.state.regno1}</p>
<div className="student-info">
<div className="form-group">
<label htmlFor="staffMember">Select Staff Member:</label>
<select
name="staffMember"
id="staffMember"
value={staffMember}
onChange={handleStaffChange}
>
<option value="">Select a staff member</option>
{staffNames.map((name, index) => (
<option key={index} value={name}>
{name}
</option>
))}
</select>
</div>
</div>
{questions.map((question) => (
<div key={question.id}>
<p>{question.question}</p>
<div className="options">
{Object.keys(choiceValues).map((choice) => (
<div key={choice}>
<label>
<input
type="radio"
name={question.id}
value={choice}
checked={responses[question.id] === choiceValues[choice]}
onChange={() => handleResponseChange(question.id, choice)}
/>
{choice}
</label>
</div>
))}
</div>
</div>
))}
<button type="submit" className="btn btn-primary"
onClick={handleSubmit1}>
Submit
</button><br></br><br></br>
<button
type="button"
className="btn btn-secondary"
onClick={review}
>
Review
</button>
</form>
<br></br>
<BarChart width={700} height={600} data={data}>
<Bar dataKey="students" fill="green" />
<CartesianGrid stroke="#ccc" />
<XAxis dataKey="name" />
<YAxis domain={[0, 5]} />
</BarChart>
</div>
);
};
export default Survey;

Survey.css
// SURVEY\frontend\src\components
.container {
max-width: 700px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
animation: fade-in 1s ease-in-out;
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.btn {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.btn:hover {
background-color: #0056b3;
}
App.js
// SURVEY\frontend\src
import React from 'react';
import Login from './components/Login';
import Signup from './components/Signup';
import Survey from './components/Survey';
import { Route, Routes } from "react-router-dom";
function App() {
return (
<div className="App">
<Routes>
<Route path='/' element={<Login />} />
<Route path='/signup' element={<Signup />} />
<Route path='/Survey' element={<Survey />} />
</Routes>
</div>

);
}
export default App;

index.js
// SURVEY\frontend\src
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);

Backend

survey.js
//SURVEY\backend\models
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
regno: {
type: String,
},
Manivannan: {
type: String,
},
Nelson: {
type: String,
},
Kosalairaman: {
type: String,
},
MaheshKumar: {
type: String,
},
Gobinath: {
type: String,
},
Umamaheswari: {
type: String,
},
});
const User = mongoose.model('User', userSchema);
module.exports = User;

login.js
SURVEY\backend\routes

const express = require('express');


const router = express.Router();
//const bcrypt = require('bcrypt');
const User = require('../models/survey'); // Assuming you have a User model
router.post('/', async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ message: 'Authentication failed' });
}
//const isPasswordValid = await bcrypt.compare(password, user.password);
//if (!isPasswordValid) {
const userId = user._id;
const name = user.username;
const regno = user.regno;
if(password!=user.password){
return res.status(401).json({ message: 'Authentication failed' });
}
// Handle successful login
res.status(200).json({ message: 'Login successful',userId,name,regno});
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

signup.js

// SURVEY\backend\routes
const express =
require('express');const router =
express.Router();

//const bcrypt = require('bcrypt');


const User = require('../models/survey');
router.post('/', async (req, res) => {
try {
const { username, password,regno } = req.body;
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(409).json({ message: 'User already exists' });
}
const Manivannan="0";
const Nelson="0";
const Kosalairaman="0";
const MaheshKumar="0";
const Gobinath="0";
const Umamaheswari="0";
console.log(username,
//password: hashedPassword,
password,regno,Manivannan,Nelson,Kosalairaman,MaheshKumar,Gobinath,Umamaheswari);
//const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
username,
//password: hashedPassword,
password,regno,Manivannan,Nelson,Kosalairaman,MaheshKumar,Gobinath,Umamaheswari,
});
await newUser.save();
res.status(201).json({ message: 'Signup successful' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

survey.js

// SURVEY/backend/routes
const express =
require('express');const router =
express.Router();

const mongoose = require('mongoose');


const User = require('../models/survey');
router.put('/', async (req, res) => {
try {
const { id1, staffMember, responses } = req.body;
console.log("id = ", id1);
const existingUser = await User.findById(id1);
const user = await User.findById(id1);
if (!existingUser) {
return res.status(409).json({ message: 'User found' });
}
const calculateSumOfResponses = (responses) => {
let sum = 0;

for (const questionId in responses) {


sum += responses[questionId];
}
sum = sum / 10;
console.log("sum", sum);
return (sum);
}
if (staffMember == "Manivannan") {
console.log("if staf 1 =", user.Manivannan);
const Manivannan = calculateSumOfResponses(responses);
if (staffMember == "Manivannan" && user.Manivannan == "0") {
console.log("Sum = ", Manivannan);
updatedUser = await User.findByIdAndUpdate(
id1,
{ Manivannan },
{ new: true }
);
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ message: 'Update successful', user: updatedUser });
}
else {
console.log("already filed");
res.json({ message: 'limit exeeded' });
}
}
else if (staffMember == "Nelson") {
console.log("if Nelson =", user.Nelson);
const Nelson = calculateSumOfResponses(responses);
if (staffMember == "Nelson" && user.Nelson == "0") {
console.log("Sum = ", Nelson);
updatedUser = await User.findByIdAndUpdate(
id1,
{ Nelson },
{ new: true }
);
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ message: 'Update successful', user: updatedUser });
}
else {
console.log("already filed");
res.json({ message: 'limit exeeded' });
}
}
else if (staffMember == "Kosalairaman") {
console.log("if Kosalairaman =", user.Kosalairaman);
const Kosalairaman = calculateSumOfResponses(responses);
if (staffMember == "Kosalairaman" && user.Kosalairaman == "0") {
console.log("Sum = ", Kosalairaman);
updatedUser = await User.findByIdAndUpdate(
id1,
{ Kosalairaman },
{ new: true });
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ message: 'Update successful', user: updatedUser });

console.log("already filed");
res.json({ message: 'limit exeeded' });
}
}
else if (staffMember == "MaheshKumar") {
console.log("MaheshKumar =", user.MaheshKumar);
const MaheshKumar = calculateSumOfResponses(responses);
if (staffMember == "MaheshKumar" && user.MaheshKumar == "0") {
console.log("Sum = ", MaheshKumar);
updatedUser = await User.findByIdAndUpdate(
id1,
{ MaheshKumar },
{ new: true }
);
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ message: 'Update successful', user: updatedUser });
}
else {
console.log("already filed");
res.json({ message: 'limit exeeded' });
}
}
else if (staffMember == "Gobinath") {
console.log("if staf 5 =", user.Gobinath);
const Gobinath = calculateSumOfResponses(responses);
if (staffMember == "Gobinath" && user.Gobinath == "0") {
console.log("Sum = ", Gobinath);
updatedUser = await User.findByIdAndUpdate(
id1,
{ Gobinath },
{ new: true }
);
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ message: 'Update successful', user: updatedUser });
}
else {
console.log("already filed");
res.json({ message: 'limit exeeded' });
}
}
else if (staffMember == "Umamaheswari") {
console.log("if staf 6 =", user.Umamaheswari);
const Umamaheswari = calculateSumOfResponses(responses);
if (staffMember == "Umamaheswari" && user.Umamaheswari == "0") {
console.log("Sum = ", Umamaheswari);
updatedUser = await User.findByIdAndUpdate(

id1,
{ Umamaheswari },
{ new: true }

return res.status(404).json({ message: 'User not found' });


}
res.status(200).json({ message: 'Update successful', user: updatedUser });
}
else {
console.log("already filed");
res.json({ message: 'limit exeeded' });
}
}
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
router.get('/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
console.log(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json(user);
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

index.js
// SURVEY/backend/
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const dotenv = require('dotenv');
dotenv.config();
const app = express();
const port = process.env.PORT || 3001;
// MongoDB connection
mongoose.connect("mongodb://0.0.0.0:27017/ananth", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB');
});
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
// Middleware
app.use(cors());
app.use('/signup', signupRouter);
app.use('/survey', surveyRouter);
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);});
Output:

You might also like