1.
CREATE A FORM AND VALIDATE THE CONTENT OF THE FORM USING
JAVASCRIPT
CODE:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>create a Form and Validate the contents</title>
<link rel="stylesheet" href="style.css">
<style>
body{
width: 100%;
height: 100vh;
display: grid;
place-items: center;
}
</style>
</head>
<body>
<div class="box" >
<div align="center" >
<h3 style="padding: 20px;">Seminar Registeration</h3>
</div>
<form action="welcome.html" id="registerForm" >
<label for="name">Student Name</label>
<input type="text" name="name" id="name" />
<label for="email">Email</label>
<input type="text" name="email" id="email" />
<label for="clgName">College Name</label>
<input type="text" name="clgName" id="clgName" />
<label for="mobileNo">Mobile Number</label>
<input type="text" name="mobileNo" id="mobileNo" />
<div class="gender">
<label for="">Gender</label> <br/> <br />
<input type="radio" name="gender" id="male" value="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" value="female" />
<label for="female">Female</label>
<input type="radio" name="gender" id="others" value="others" />
<label for="others">others</label>
</div>
<div align="center" >
<input type="submit" value="Register">
</div>
</form>
</div>
<script src="main.js"></script>
</body>
</html>
style.css
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
.box{
width: 300px;
border:1px solid #000;
padding: 20px;
}
input{
width: 100%;
height: 25px;
margin-bottom: 15px;
}
input[type="submit"]{
height: 30px;
background-color: darkblue;
border: none;
outline: none;
cursor: pointer;
color: #fff;
font-size: 16px;
transition: .5s;
}
input[type="submit"]:hover{
background-color: blue;
}
input[type="radio"]{
width: 12px;
height: 12px;
}
.gender label{
padding-right: 20px;
}
main.js
document.getElementById('registerForm').addEventListener('submit',(e)=>{
let user = document.getElementById('name').value;
let email = document.getElementById('email').value;
let clgName = document.getElementById('clgName').value;
let mbleNo = document.getElementById('mobileNo').value;
let gender = document.getElementsByName('gender');
let genderValue = false
let error = [];
if( user.length <= 2 || !user.match((/^[a-z,A-Z]+$/)) ){
error.push("invalid student name");
}
if(email.length < 5 || email.indexOf('@') == -1 || email.indexOf('.') == -1
){
error.push("Invalid Email Address");
}
if(clgName.length < 5){
error.push("Invalid college name");
}
if(mbleNo.length != 10 || !mbleNo.match((/^[0-9]+$/)) ){
error.push("Invalid Phone Number");
}
for(let i=0;i<gender.length;i++){
if(gender[i].checked){
genderValue = true
}
}
if(genderValue == false){
error.push("Plase select gender option")
}
if(error.length != 0){
e.preventDefault()
alert(error.map((data)=>`\n ${data}`))
}
});
welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div align="center" >
<h1> Form submitted successfully </h1>
</div>
</body>
</html>
OUTPUT:
2. GET DATA USING FETCH API FROM AN OPEN-SOURCE ENDPOINT AND
DISPLAY THE CONTENTS IN THE FORM OF A CARD
CODE:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetched Data Cards</title>
<style>
.card-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
border: 1px solid #ddd;
border-radius: 8px;
width: 200px;
padding: 15px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
text-align: center;
}
.card img {
width: 100%;
border-radius: 50%;
}
</style>
</head>
<body>
<h1>Fetched Data Cards</h1>
<div class="card-container" id="card-container"></div>
<script>
fetch('https://dummyjson.com/users')
.then(response => response.json())
.then(data => {
const container = document.getElementById('card-container');
data.users.forEach(user => {
const card = document.createElement('div');
card.classList.add('card');
const cardContent = `
<h3>${user.firstName}</h3>
<p>Id: ${user.id}</p>
<p>Age: ${user.age}</p>
<p>Gender: ${user.gender}</p>
`;
card.innerHTML = cardContent;
container.appendChild(card);
});
})
.catch(error => {
console.error('Error fetching data:', error);
});
</script>
</body>
</html>
OUTPUT:
3. Create a NodeJS server that serves static HTML and CSS files to the user without
using Express.
CODE:
index.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="style.css">
<title>Full Stack Web Development</title>
</head>
<body>
<h1>Full Stack Web Development</h1>
<p>- Computer Applications</p>
</body>
</html>
style.css
body {
background-color: green;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
server.js
const http = require('http');
const fs = require('fs');
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else if (req.url.match(/\.(html|css)$/)) {
const filePath = req.url.slice(1);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, { 'Content-Type': filePath.endsWith('.css') ? 'text/css' : 'text/html' });
res.end(data);
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
OUTPUT:
4. CREATE A NODEJS SERVER USING EXPRESS THAT STORES DATA FROM A
FORM AS A JSON FILE AND DISPLAYS IT IN ANOTHER PAGE. THE
REDIRECT PAGE SHOULD BE PREPARED USING HANDLEBARS.
CODE:
New folder/views/index.js
const express = require('express');
const expbs = require('express-handlebars');
const bodyParser = require('body-parser');
const path = require('path'); // Import path module
const app = express();
// Use body-parser middleware with extended option
app.use(bodyParser.urlencoded({ extended: true }));
// Set the views directory
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', expbs.engine({ defaultLayout: false }));
app.set('view engine', 'handlebars');
// Routing
app.get('/', function(request, response, next) {
response.render('index', { layout: false });
});
app.post('/', function(request, response, next) {
response.send(request.body);
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
New folder/views/index.handlebars
<h1>Student Form</h1>
<form action="/" method="post">
<table style="font-size: 20px;">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name" placeholder="Your name.."></td>
</tr>
<tr>
<td><label for="reg">Register Number:</label></td>
<td><input type="text" id="reg" name="registerNumber" placeholder="Your
number"></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td><input type="text" id="city" name="city" placeholder="Your City"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
OUTPUT:
5. CREATE A NODEJS SERVER USING EXPRESS THAT CREATES, READS,
UPDATES AND DELETES STUDENTS' DETAILS AND STORES THEM IN
MONGODB DATABASE. THE INFORMATION ABOUT THE USER SHOULD BE
OBTAINED FROM A HTML FORM
CODE:
A) index.js
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const path = require("path"); // Import the 'path' module
mongoose.connect("mongodb://localhost:27017/student");
const app = express();
app.use(bodyParser.json());
app.use(express.static("public")); // Serve static files from the 'public' directory
app.use(bodyParser.urlencoded({ extended: true }));
// Schema for student details
const studentSchema = new mongoose.Schema({
name: String,
Reg_number: String,
Address: String,
City: String
});
const Student = mongoose.model("Student", studentSchema);
// POST route to add a new student
app.post("/sign_up", (req, res) => {
const { name, reg, add, city } = req.body;
const newStudent = new Student({
name,
Reg_number: reg,
Address: add,
City: city,
});
newStudent.save()
.then(student => {
console.log("Record inserted Successfully");
res.redirect("/view.html");
})
.catch(err => {
console.error("Error inserting record:", err);
res.status(500).send("Error inserting record");
});
});
// GET route for the add student form
app.get("/add_student", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
// GET route to retrieve all students
app.get("/api/students", (req, res) => {
Student.find({})
.then(students => {
res.send(students);
})
.catch(err => {
console.error("Error retrieving students:", err);
res.status(500).send("Error retrieving students");
});
});
// DELETE route to delete a student
app.delete("/api/student/:id", (req, res) => {
const id = req.params.id;
Student.findByIdAndDelete(id)
.then(deletedStudent => {
if (!deletedStudent) {
return res.status(404).send("Student not found");
}
res.send("Student deleted successfully");
})
.catch(err => {
console.error("Error deleting student:", err);
res.status(500).send("Error deleting student");
});
});
// DELETE route to delete the entire database
app.delete("/api/database", (req, res) => {
mongoose.connection.dropDatabase()
.then(() => {
console.log("Database deleted successfully");
res.send("Database deleted successfully");
})
.catch(err => {
console.error("Error deleting database:", err);
res.status(500).send("Error deleting database");
});
});
app.get("/", (req, res) => {
res.set({ "Access-Control-Allow-Origin": "*" });
return res.redirect("index.html");
});
app.listen(3000, () => {
console.log("server listening at port 3000");
});
// PUT route to update a student's information
app.put("/api/student/:id", (req, res) => {
const id = req.params.id;
const { name, reg, add, city } = req.body;
Student.findByIdAndUpdate(id, { name, Reg_number: reg, Address: add, City: city }, {
new: true })
.then(updatedStudent => {
if (!updatedStudent) {
return res.status(404).send("Student not found");
}
res.send("Student updated successfully");
})
.catch(err => {
console.error("Error updating student:", err);
res.status(500).send("Error updating student");
});
});
B) mongodb.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
app.use(express.json());
let database;
app.get('/', (req, res) => {
res.send('Welcome to Mongodb API');
});
MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, (err, client)
=> {
if (err) throw err;
database = client.db('student');
app.listen(3000, () => {
console.log('connection connected');
});
});
app.get('/api/student', (req, res) => {
database.collection('Studetails').find({}).toArray((err, result) => {
if (err) throw err;
res.send(result);
});
});
C)public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Data</title>
</head>
<body>
<h1>Please fill data in the form below:</h1>
<form method="POST" action="/sign_up">
<table>
<tr>
<td><label>Name:</label></td>
<td><input type="text" name="name" required></td>
</tr>
<tr>
<td><label>Reg number:</label></td>
<td><input type="text" name="reg" required></td>
</tr>
<tr>
<td><label>Address:</label></td>
<td><input type="text" name="add" required></td>
</tr>
<tr>
<td><label>City:</label></td>
<td><input type="text" name="city" required></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</body>
</html>
D)public/view.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View Student Records</title>
</head>
<body>
<h1>Student Records</h1>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Reg number</th>
<th>Address</th>
<th>City</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="studentRecords">
<!-- Student records will be dynamically inserted here -->
</tbody>
</table>
<button onclick="location.href='/add_student'">Add Student</button>
<script>
// Fetch student records from the server and display them
fetch('/api/students')
.then(response => response.json())
.then(students => {
const studentRecords = document.getElementById('studentRecords');
students.forEach(student => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${student.name}</td>
<td>${student.Reg_number}</td>
<td>${student.Address}</td>
<td>${student.City}</td>
<td><button onclick="editStudent('${student._id}', '${student.name}',
'${student.Reg_number}', '${student.Address}', '${student.City}')">Edit</button></td>
<td><button onclick="deleteStudent('${student._id}')">Delete</button></td>
`;
studentRecords.appendChild(row);
});
})
.catch(error => console.error('Error fetching student records:', error));
// Function to handle editing a student record
function editStudent(id, name, reg, add, city) {
const newName = prompt("Enter new name", name);
const newReg = prompt("Enter new registration number", reg);
const newAdd = prompt("Enter new address", add);
const newCity = prompt("Enter new city", city);
if (newName && newReg && newAdd && newCity) {
fetch(`/api/student/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: newName,
reg: newReg,
add: newAdd,
city: newCity
})
})
.then(response => response.text())
.then(message => {
alert(message);
location.reload(); // Refresh page after editing
})
.catch(error => console.error('Error editing student:', error));
}
}
// Function to handle deleting a student record
function deleteStudent(id) {
if (confirm("Are you sure you want to delete this student?")) {
fetch(`/api/student/${id}`, {
method: 'DELETE'
})
.then(response => response.text())
.then(message => {
alert(message);
location.reload(); // Refresh page after deletion
})
.catch(error => console.error('Error deleting student:', error));
}
}
</script>
</body>
</html>
OUTPUT:
After submit the data,
6. CREATE A NODEJS SERVER THAT CREATES, READS, UPDATES AND
DELETES EVENT DETAILS AND STORES THEM IN A MYSQL DATABASE. THE
INFORMATION ABOUT THE USER SHOULD BE OBTAINED FROM A HTML
FORM
CODE:
A) Create a MySQL database named events_db and a table named events
CREATE DATABASE events_db;
USE events_db;
CREATE TABLE events (
id INT AUTO_INCREMENT PRIMARY KEY,
participantName VARCHAR(255),
eventName VARCHAR(255),
eventDate DATE,
eventPlace VARCHAR(255)
);
B) server.js
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'events_db'
});
connection.connect((err) => { if (err) throw err; console.log('Connected to MySQL
database'); });
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));
app.post('/addEvent', (req, res) => {
const { participantName, eventName, eventDate, eventPlace } = req.body;
connection.query('INSERT INTO events (participantName, eventName, eventDate,
eventPlace) VALUES (?, ?, ?, ?)', [participantName, eventName, eventDate, eventPlace],
(err, result) => {
if (err) throw err;
console.log('Event added to the database');
res.redirect('/events');
});
});
app.get('/events', (req, res) => {
connection.query('SELECT * FROM events', (err, rows) => {
if (err) throw err;
const eventsList = rows.map(row => `<li>${row.participantName} - ${row.eventName} -
${row.eventDate} - ${row.eventPlace}</li>`).join('');
res.send(`<h1>Success! Your Events Recorded</h1><button
onclick="location.href='/edit'">Edit</button><button
onclick="location.href='/add'">Add</button><button
onclick="location.href='/delete'">Delete</button><ul>${eventsList}</ul>`);
});
});
app.get('/edit', (req, res) => {
connection.query('SELECT * FROM events ORDER BY id DESC LIMIT 1', (err, rows) =>
{
if (err) throw err;
const event = rows[0];
if (!event) res.send('No event found');
else res.send(`
<h1>Edit Event</h1>
<form action="/updateEvent" method="post">
<input type="hidden" name="eventId" value="${event.id}">
<label for="participantName">Participant Name:</label><br>
<input type="text" id="participantName" name="participantName"
value="${event.participantName}"><br>
<label for="eventName">Event Name:</label><br>
<input type="text" id="eventName" name="eventName"
value="${event.eventName}"><br>
<label for="eventDate">Event Date:</label><br>
<input type="date" id="eventDate" name="eventDate"
value="${event.eventDate}"><br>
<label for="eventPlace">Event Place:</label><br>
<input type="text" id="eventPlace" name="eventPlace"
value="${event.eventPlace}"><br><br>
<input type="submit" value="Update">
</form>
`);
});
});
app.post('/updateEvent', (req, res) => {
const { eventId, participantName, eventName, eventDate, eventPlace } = req.body;
if (!eventDate) return res.status(400).send('Event date cannot be empty');
connection.query('UPDATE events SET participantName=?, eventName=?, eventDate=?,
eventPlace=? WHERE id=?', [participantName, eventName, eventDate, eventPlace, eventId],
(err, result) => {
if (err) throw err;
console.log('Event updated in the database');
res.redirect('/events');
});
});
app.get('/add', (req, res) => res.sendFile(__dirname + '/index.html'));
app.get('/delete', (req, res) => {
connection.query('DELETE FROM events ORDER BY id DESC LIMIT 1', (err, result) =>
{
if (err) throw err;
console.log('Recent event deleted from the database');
res.redirect('/events');
});
});
app.listen(port, () => console.log(`Server is listening at http://localhost:${port}`));
C)index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Form</title>
</head>
<body>
<form action="/addEvent" method="post">
<label for="participantName">Participant Name:</label><br>
<input type="text" id="participantName" name="participantName"><br>
<label for="eventName">Event Name:</label><br>
<input type="text" id="eventName" name="eventName"><br>
<label for="eventDate">Event Date:</label><br>
<input type="date" id="eventDate" name="eventDate"><br>
<label for="eventPlace">Event Place:</label><br>
<input type="text" id="eventPlace" name="eventPlace"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
OUTPUT:
Fill in the details and then click 'Submit'
To add new data, click on 'Add'.
To delete existing data, click on 'Delete'
7. CREATE A COUNTER USING REACTJS
CODE:
A) counter.js
import React, { useState } from 'react';
import './Counter.css';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(prevCount => prevCount + 1);
};
const decrement = () => {
setCount(prevCount => prevCount - 1);
};
const reset = () => {
setCount(0);
};
return (
<div className="counter">
<h2>COUNTER</h2>
<div className="count">{count}</div>
<div className="buttons">
<button onClick={decrement}>-</button>
<button onClick={reset} className="reset-button">Reset</button>
<button onClick={increment}>+</button>
</div>
</div>
);
};
export default Counter;
B) counter-app/src/App.js
import React from 'react';
import './App.css';
import Counter from './Counter';
function App() {
return (
<div className="App">
<Counter />
</div>
);
}
export default App;
C) counter-app/src/Counter.css
.counter {
text-align: center;
margin-top: 50px;
}
.count {
font-size: 24px;
margin-bottom: 20px;
}
.buttons button {
font-size: 18px;
margin: 0 10px;
padding: 5px 10px;
cursor: pointer;
}
OUTPUT: