<!DOCTYPE html>
<html>
<head>
<title>Movie Ticket Booking</title>
</head>
<body>
<h1>Movie Ticket Booking</h1>
<form id="ticketForm">
<label for="numTickets">Number of Tickets:</label>
<input type="number" id="numTickets" name="numTickets">
<button type="button" id="calculateButton">Calculate Total Price</button>
</form>
<p id="result"></p>
<script>
// Constants
const ticketPrice = 150; // Price per ticket
const maxAllowedSeats = 6; // Maximum allowed seats for booking
const discountSeatsLowerLimit = 3; // Lower limit for discount seats
const discountSeatsUpperLimit = 6; // Upper limit for discount seats
const discountRate = 0.1; // Discount rate (10%)
// Get form and result element from DOM
const ticketForm = document.getElementById('ticketForm');
const resultElement = document.getElementById('result');
// Add event listener to calculate button
document.getElementById('calculateButton').addEventListener('click', function() {
// Get input value for number of tickets
const numTickets = parseInt(document.getElementById('numTickets').value);
// Check if number of tickets is not more than 2
if (numTickets <= 2) {
// Calculate total price without discount
const totalPrice = numTickets * ticketPrice;
// Display result in result element
resultElement.textContent = `Total Price: Rs. ${totalPrice}`;
}
// Check if number of tickets is between 3 and 6
else if (numTickets >= discountSeatsLowerLimit && numTickets <= discountSeatsUpperLimit) {
// Calculate total price with discount
const totalPrice = numTickets * ticketPrice;
const discountAmount = totalPrice * discountRate;
const finalTotalPrice = totalPrice - discountAmount;
// Display result in result element
resultElement.textContent = `Total Price: Rs. ${totalPrice}, Discounted Amount: Rs. ${discountAmount}, Final Total Price: Rs. ${finalTotalPrice}`;
}
// Check if number of tickets is 6 or more
else if (numTickets >= maxAllowedSeats) {
// Display error message
resultElement.textContent = `Booking is not allowed for more than ${maxAllowedSeats} seats.`;
}
});
</script>
</body>
</html>
8. Create an Employee class extending from a base class Person. Hints: (i) Create a class Person
with name and age as attributes. (ii) Add a constructor to initialize the values (iii) Create a
class Employee extending Person with additional attributes role in javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class Employee extends Person {
constructor(name, age, role) {
super(name, age);
this.role = role;
}
}
// Create an instance of Employee class
const employee1 = new Employee("John", 30, "Manager");
// Access attributes of Person class from Employee class
console.log("Name: " + employee1.name); // Output: Name: John
console.log("Age: " + employee1.age); // Output: Age: 30
// Access attribute of Employee class
console.log("Role: " + employee1.role); // Output: Role: Manager
9. Create an array of objects having movie details. The object should include the movie name,
starring, language, and ratings. Render the details of movies on the page using the array. Use HTML and Javascript
<!DOCTYPE html>
<html>
<head>
<title>Movie Details</title>
</head>
<body>
<h1>Movie Details</h1>
<ul id="movieList"></ul>
<script>
// Define the movie objects
const movies = [
{ name: "Movie 1", starring: "Actor 1, Actress 1", language: "English", ratings: 4.5 },
{ name: "Movie 2", starring: "Actor 2, Actress 2", language: "Hindi", ratings: 4.2 },
{ name: "Movie 3", starring: "Actor 3, Actress 3", language: "Telugu", ratings: 4.8 },
{ name: "Movie 4", starring: "Actor 4, Actress 4", language: "Tamil", ratings: 4.0 }
];
// Get the <ul> element to display the movie details
const movieList = document.getElementById("movieList");
// Loop through the movies array and render movie details on the page
for (const movie of movies) {
const li = document.createElement("li");
li.textContent = `Movie Name: ${movie.name}, Starring: ${movie.starring}, Language: ${movie.language}, Ratings: ${movie.ratings}`;
movieList.appendChild(li);
}
</script>
</body>
</html>
10. Validate the user by creating a login module. Hints: (i) Create a file login.js with a User
class. (ii) Create a validate method with username and password as arguments. (iii) If the
username and password are equal it will return "Login Successful" else will return login failed using Javascript
class User {
constructor(username, password) {
this.username = username;
this.password = password;
}
validate(username, password) {
if (this.username === username && this.password === password) {
return "Login Successful";
} else {
return "Login Failed";
}
}
}
// Create instances of User class
const user1 = new User("username1", "password1");
const user2 = new User("username2", "password2");
// Validate user credentials
console.log(user1.validate("username1", "password1")); // Output: Login Successful
console.log(user1.validate("username1", "wrongpassword")); // Output: Login Failed
console.log(user2.validate("username2", "password2")); // Output: Login Successful
console.log(user2.validate("username2", "wrongpassword")); // Output: Login Failed
11. a) Create a text file src.txt and add the following data to it. Mongo, Express, Angular, Node using Node.js
const fs = require('fs');
const data = 'Mongo, Express, Angular, Node';
fs.writeFile('src.txt', data, function(err) {
if (err) throw err;
console.log('Data written to file');
});
EXPRESS.JS
create a directory MyProject1
cd MyProject1
npm init -y
to create package.json file
npm install express
to install express
save this in MyProject1 as ws1.js
// app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Express! welcome123');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
node ws1.js
o/p:
Server is running at http://localhost:3000
open browser and type
http://localhost:3000
you will see
Hello, Express! welcome123
b) Implement routing for home page, about and contact pages by embedding the necessary code in the routes/route.js file.
route.js in routes folder created in MyProject1 folder
**************************************************************
const express = require('express');
const router = express.Router();
// Define routes
router.get('/', function(req, res) {
res.send('Welcome to our website!');
});
router.get('/about', function(req, res) {
res.send('Learn more about our company.');
});
router.get('/contact', function(req, res) {
res.send('Contact us for more information.');
});
// Export router
module.exports = router;
**********************************
const express = require('express');
const app = express();
const routes = require('./routes/route');
app.use('/', routes);
app.listen(3000, function() {
console.log('Server listening on port 3000.');
});
*****************************************************
save in MyProject1 folder as p11.js and run and test all 3 pages
************************************************************
c) Defining a route, Handling Routes, Route Parameters, Query Parameters .Implement routing for the AdventureTrails application by embedding the necessary code in routes/route.js file
Create routes folder in your project folder.
Save below code in route2.js file and save it in routes folder
******************
const express = require('express');
const router = express.Router();
// Sample data for AdventureTrails
const trails = [
{ id: 1, name: "Mountain Trek", difficulty: "Hard" },
{ id: 2, name: "Forest Walk", difficulty: "Easy" },
{ id: 3, name: "Desert Expedition", difficulty: "Medium" },
{ id:4,name:"SkyDiving",difficulty:"Hard"},
{id:5,name:"pool Jumping",difficulty:"Medium"},
{id:6,name:"Para Gliding",difficulty:"Hard"},
{id:7,name:"Go Karting",difficulty:"Medium"}
];
/**
* 1. Defining a Route (Home Route)
*/
router.get('/', (req, res) => {
res.send('Welcome to AdventureTrails!');
});
/**
* 2. Handling Routes - Fetch all trails
*/
router.get('/trails', (req, res) => {
res.json(trails);
});
/**
* 4. Query Parameters - Filter trails by difficulty
* Example: GET /trails/filter?difficulty=Easy
*/
router.get('/trails/filter', (req, res) => {
const difficulty = req.query.difficulty; // Extract query parameter
if (!difficulty) {
return res.status(400).json({ message: "Please provide a difficulty level" });
}
const filteredTrails = trails.filter(t => t.difficulty.toLowerCase() === difficulty.toLowerCase());
if (filteredTrails.length === 0) {
return res.status(404).json({ message: "No trails found for the specified difficulty" });
}
res.json(filteredTrails);
});
/**
* 3. Route Parameters - Fetch a specific trail by ID
* Example: GET /trails/2
*/
router.get('/trails/:id', (req, res) => {
const trailId = parseInt(req.params.id);
const trail = trails.find(t => t.id === trailId);
if (!trail) {
return res.status(404).json({ message: "Trail not found" });
}
res.json(trail);
});
module.exports = router;
*************
const express = require('express');
const app = express();
const routes = require('./routes/route2');
app.use('/api', routes);
app.listen(3000, () => console.log('Server running on port 3000'));
*******
this code in MyProject1 folder with name server.js
12. Send a Form to browser with Name, Age, Nationality fields, with Express.js
When user submits the form, log the data at server console. use pug file format
npm install --save pug
npm install --save body-parser
npm install --save multer
12.a)
index.js
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var app = express();
app.get('/', function(req, res){
res.render('form');
});
app.set('view engine', 'pug');
app.set('views', './views');
// for parsing application/json
app.use(bodyParser.json());
// for parsing application/xwww-
app.use(bodyParser.urlencoded({ extended: true }));
//form-urlencoded
// for parsing multipart/form-data
app.use(upload.array());
app.use(express.static('public'));
app.post('/', function(req, res){
console.log(req.body);
res.send("recieved your request!");
});
app.listen(3000);
form.pug create in views sub folder
html
head
title
Form Tester
body
form(action
= "/", method
= "POST")
div
label(for
= "say") Name:
input(name
= "name" )
br
div
label(for
= "to") Age :
input(name
= "age")
br
div
label(for
= "to") Nationality :
input(name
= "nationality")
br
button(type
= "submit")
Add me
In terminal type
node index.js
To test goto browser type url
http://localhost:3000/
fill the form,
check server console
12. B) without pug files
run the following command in command prompt in your project folder
npm install --save mongoose@6.0
save the below code in your project folder as server1.js
******************
var express = require('express');
var app = express();
// Middleware for parsing request body
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', function(req, res) {
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Tester</title>
</head>
<body>
<h2>Form Tester</h2>
<form action="/" method="POST">
<div>
<label for="name">Name:</label>
<input type="text" name="name" required>
</div>
<br>
<div>
<label for="age">Age:</label>
<input type="number" name="age" required>
</div>
<br>
<div>
<label for="nationality">Nationality:</label>
<input type="text" name="nationality" required>
</div>
<br>
<button type="submit">Add me</button>
</form>
</body>
</html>
`);
});
app.post('/', function(req, res) {
console.log(req.body); // Logs submitted form data
res.send("Received your request!");
});
// Start server
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
***********
open server1.js, run->debug
open browser and test http://localhost:3000
fill the form and press add me
The below program saves form data into mongodb
save the below code in your project folder as
server2.js
*********
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose'); // Import mongoose
var multer = require('multer');
var upload = multer();
var app = express();
// Connect to MongoDB (Replace <your_connection_string> with your actual MongoDB URI)
mongoose.connect('mongodb://127.0.0.1:27017/library1', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));
// Define Mongoose Schema
var personSchema = new mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
// Middleware for parsing request body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // For form-urlencoded
app.use(upload.array()); // For multipart/form-data
app.use(express.static('public')); // Serve static files if needed
app.get('/', function(req, res) {
// Sending HTML directly
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Tester</title>
</head>
<body>
<h2>Form Tester</h2>
<form action="/" method="POST">
<div>
<label for="name1">Name1:</label>
<input type="text" name="name" required>
</div>
<br>
<div>
<label for="age">Age:</label>
<input type="number" name="age" required>
</div>
<br>
<div>
<label for="nationality">Nationality:</label>
<input type="text" name="nationality" required>
</div>
<br>
<button type="submit">Add me</button>
</form>
</body>
</html>
`);
});
app.post('/', function(req, res) {
console.log(req.body); // Logs submitted form data
var personInfo = req.body; // Get the parsed information
if (!personInfo.name || !personInfo.age || !personInfo.nationality) {
return res.send(`
<h3 style="color:red">Sorry, you provided wrong info</h3>
`);
}
var newPerson = new Person({
name: personInfo.name,
age: personInfo.age,
nationality: personInfo.nationality
});
newPerson.save()
.then(() => {
res.send(`
<h3 style="color:green">New person added</h3>
<p>Name: ${personInfo.name}</p>
<p>Age: ${personInfo.age}</p>
<p>Nationality: ${personInfo.nationality}</p>
`);
})
.catch(err => {
console.error("Database error:", err);
res.send('<h3 style="color:red">Database error</h3>');
});
});
// Start server
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
**************
open server2.js, run->debug
open browser and test http://localhost:3000
fill the form and test data storing in mongodb
by opening mongodb compass tool
Comments
Post a Comment