Experiment 1) Program To Build A Chat Module Using HTML Css and Javascript
Experiment 1) Program To Build A Chat Module Using HTML Css and Javascript
Program Explanation
The program uses three files: HTML sets up the structure (message area, input,
button). CSS styles the elements (layout, colors, bubbles). JavaScript handles
the interactivity, like adding messages to the display and simulating replies.
File Structure
/Experiment_1_Chat_Module
├── index.html (HTML Structure)
├── style.css (CSS Styling)
└── script.js (JavaScript Functionality)
Code
1. index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Experiment 1: Chat Module</title>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com"
crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;50
0;600;700&display=swap" rel="stylesheet">
<script src="script.js" defer></script>
</head>
<body>
<div class="chat-container">
1
B64
<div class="chat-header">
Chat Module
</div>
<div class="chat-input-area">
<input
type="text"
id="message-input"
placeholder="Type your message here..."
class="message-input"
>
<button id="send-button" class="send-button">
Send
</button>
</div>
</div>
</body>
</html>
2. style.css:
/* Basic body styling */
body {
font-family: 'Inter', sans-serif; /* Preferred font */
background-color: #f0f2f5; /* Light gray background */
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh; /* Full viewport height */
margin: 0;
padding: 16px; /* Padding around the chat container */
box-sizing: border-box;
}
2
B64
3
B64
4
B64
3. script.js:
// script.js - Chat Module Functionality
/**
* Adds a new message to the chat display area.
* @param {string} message - The text content of the message.
* @param {string} [sender='user'] - The sender ('user' or
'bot').
*/
function addMessage(message, sender = 'user') {
// Create the main message container div
const messageDiv = document.createElement('div');
messageDiv.classList.add('message'); // Common class for
5
B64
all messages
/**
* Handles sending a message when the button is clicked or
Enter is pressed.
*/
function sendMessage() {
// Get the message text from input, removing
leading/trailing whitespace
const messageText = messageInput.value.trim();
6
B64
const replies = [
"Hmm, interesting.",
"Okay, I understand.",
"I'm not sure about that.",
"Alright.",
"Tell me more!",
"Got it!",
"I am just a simple bot."
];
// Select a random reply
const randomReply =
replies[Math.floor(Math.random() * replies.length)];
addMessage(randomReply, 'bot'); // Display the
bot's reply
}, 1000); // Reply after 1000 milliseconds (1 second)
}
}
7
B64
Output
8
B64
Program Explanation
The implementation uses HTML to structure the star icons and display area. CSS
styles the stars' appearance (default, hover, selected states). jQuery handles the
dynamic behavior, detecting mouse hovers and clicks on stars to update the
visual rating and display the selected value.
File Structure
/Experiment_2_Star_Rating
├── index.html (HTML Structure, includes jQuery CDN)
├── style.css (CSS Styling for stars)
└── script.js (jQuery code for interaction)
Code
1. index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Experiment 2: Star Rating</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/6.5.1/css/all.min.css" integrity="sha512-
DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4Tc
tnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous"
referrerpolicy="no-referrer" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com"
crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;50
0;600;700&display=swap" rel="stylesheet">
</head>
<body>
9
B64
<div class="rating-container">
<h2>Rate this Product:</h2>
<div class="star-rating" id="star-rating-container">
<i class="fa-solid fa-star" data-value="1"></i><i
class="fa-solid fa-star" data-value="2"></i><i class="fa-solid
fa-star" data-value="3"></i><i class="fa-solid fa-star" data-
value="4"></i><i class="fa-solid fa-star" data-
value="5"></i></div>
<div id="rating-value" class="rating-value-
display">Rating: 0 / 5</div>
<input type="hidden" id="selected-rating" name="rating"
value="0">
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<script src="script.js"></script> </body>
</html>
2. style.css:
/* Basic body styling */
body {
font-family: 'Inter', sans-serif;
background-color: #f0f2f5;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
}
10
B64
transition */
}
3. script.js:
// script.js - Star Rating Functionality using jQuery
11
B64
12
B64
Output
13
B64
Program Explanation
The program uses Node.js's built-in fs (File System) module. It creates a
readable stream from a sample text file (data.txt) and pipes this stream
directly to a writable stream (process.stdout, which represents the console
output), logging data chunk by chunk.
File Structure
/Experiment_3_Node_Streaming
├── streamApp.js (Node.js code)
└── data.txt (Sample data file to be streamed)
Code
2. streamApp.js:
// streamApp.js - Basic Node.js File Streaming Example
14
B64
15
B64
Output
16
B64
Program Explanation
The application uses Node.js with the Express framework and Passport.js for
session management. Instead of using an external OAuth provider strategy (like
Google), it uses a mock login route. When the user clicks "Mock Login", the
application manually logs in a predefined mock user using Passport's
req.login(), which utilizes serializeUser to store user info in a session
cookie via express-session. Routes are defined to handle this mock login and
logout.
File Structure
/Experiment_4_Node_Mock_Auth
├── app.js (Main application file)
├── package.json (Lists dependencies)
├── config/
│ ├── keys.js (Stores session key ONLY)
│ └── passport-setup.js (Passport configuration - simplified)
├── routes/
│ └── auth-routes.js (Authentication related routes - simplified)
└── views/ (EJS Template files)
├── login.ejs (Login page view - updated button)
└── profile.ejs (User profile page view)
└── home.ejs (Homepage view)
17
B64
Code
File: package.json
(Defines project metadata and dependencies)
{
"name": "exp4-node-mock-auth-fixed",
"version": "1.0.0",
"description": "Node.js Mock Auth Example using express-
session",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express-session": "^1.17.3",
"ejs": "^3.1.6",
"express": "^4.17.1",
"passport": "^0.6.0"
}
}
File: config/keys.js
(Stores configuration keys, like the session secret)
// config/keys.js
// Session secret key for express-session
module.exports = {
session: {
// express-session uses a 'secret' instead of 'keys' array
secret: 'aRandomSecretKeyForSessionEncryption' // Choose any
random string here!
}
};
File: config/passport-setup.js
(Configures Passport serialize/deserialize functions)
// config/passport-setup.js
const passport = require('passport');
18
B64
File: routes/auth-routes.js
(Defines routes related to authentication: login, logout, mock
login)
// routes/auth-routes.js
const router = require('express').Router();
const passport = require('passport'); // Still needed for
req.login/req.logout
// Auth logout
router.get('/logout', (req, res, next) => {
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
19
B64
Placeholder image
};
module.exports = router;
File: views/home.ejs
(EJS template for the homepage)
<!DOCTYPE html>
<html>
<head>
<title>Mock Auth App Homepage</title>
<style> body { font-family: Arial, sans-serif; padding: 20px;
} a { margin: 5px; padding: 10px; background-color: #eee; text-
decoration: none; color: #333; border-radius: 4px;} </style>
</head>
<body>
<h1>Welcome to the Mock Auth App!</h1>
<% if (user) { %>
<p>You are logged in as <%= user.displayName %></p>
<a href="/profile">View Profile</a>
<a href="/auth/logout">Logout</a>
<% } else { %>
<p>Please login to continue.</p>
<a href="/auth/login">Login</a>
<% } %>
</body>
</html>
File: views/login.ejs
(EJS template for the login page)
20
B64
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<style> body { font-family: Arial, sans-serif; padding: 20px;
} a { display: inline-block; margin-top: 10px; padding: 10px
15px; background-color: #4CAF50; color: white; text-decoration:
none; border-radius: 4px;} </style>
</head>
<body>
<h1>Login</h1>
<% if (user) { %>
<p>You are already logged in as <%= user.displayName %></p>
<a href="/profile">Go to Profile</a>
<a href="/auth/logout">Logout</a>
<% } else { %>
<p>Click the button to simulate login:</p>
<a href="/auth/mock">Mock Login</a>
<% } %>
</body>
</html>
File: views/profile.ejs
(EJS template for the user profile page)
<!DOCTYPE html>
<html>
<head>
<title>Profile</title>
<style> body { font-family: Arial, sans-serif; padding: 20px;
} img { border-radius: 50%; vertical-align: middle; margin-right:
10px;} a { margin-top: 15px; display: inline-block;}</style>
</head>
<body>
<h1>Your Profile</h1>
<% if (user) { %>
<p>
<% if (user.photos && user.photos.length > 0) { %>
<img src="<%= user.photos[0].value %>"
alt="Profile Picture" width="50" height="50">
<% } %>
<strong>Welcome, <%= user.displayName %>!</strong>
</p>
<p>Email: <%= user.emails && user.emails.length > 0 ?
user.emails[0].value : 'Not available' %></p>
<p>Mock ID: <%= user.id %></p>
<a href="/auth/logout">Logout</a>
21
B64
<br>
<a href="/">Go to Homepage</a>
<% } else { %>
<p>You need to be logged in to view this page.</p>
<a href="/auth/login">Login</a>
<% } %>
</body>
</html>
File: app.js
(Main application file: sets up Express, middleware, routes, and
starts server)
22
B64
Output
23
B64
24
B64
Program Explanation
The core logic involves using Nodemailer. First, a transporter object is
created and configured with the SMTP service details (host, port) and
authentication credentials (e.g., a Gmail address and its corresponding App
Password). Then, mailOptions are defined specifying the sender, recipient,
subject, and body of the email. Finally, the transporter.sendMail() method
is called with these options to send the email asynchronously. Proper credential
setup (like using Gmail App Passwords) is crucial for successful execution.
File Structure
/Experiment_5_Node_Email
├── package.json (Defines dependencies like Nodemailer)
└── sendEmail.js (The Node.js script to send the email)
Code
File: package.json
(Defines project metadata and dependencies)
{
"name": "exp5-node-email",
"version": "1.0.0",
"description": "Node.js email sending example using
Nodemailer",
"main": "sendEmail.js",
"scripts": {
"start": "node sendEmail.js"
},
"dependencies": {
"nodemailer": "^6.7.0"
}
}
25
B64
File: sendEmail.js
(Contains the Node.js code using Nodemailer to send an email -
Comments Removed)
let mailOptions = {
from: `"Your Name or App Name" <${senderEmail}>`,
to: recipientEmail,
subject: 'Test Email from Node.js App',
text: 'Hello! This is a test email sent from a Node.js
application using Nodemailer.',
html: '<b>Hello!</b><p>This is a test email sent from a
Node.js application using Nodemailer.</p>'
};
26
B64
sendTestEmail();)
Output
Attempting to send email from [email protected] to
[email protected]...
27
B64
Program Explanation
[Node.js (with Express.js) ka use karke API endpoints (routes) kaise define kiye
gaye hain. HTTP methods (GET, POST, PUT, DELETE) ka use. Request handling
(req.params, req.query, req.body). Response sending (res.json, res.send, status
codes). Deployment platform (e.g., Heroku, Vercel, AWS) aur process ka brief.]
File Structure
[e.g.,
● server.js / app.js
● routes/api.js
● controllers/ (optional, for route logic)
● models/ (optional, for data structure/database interaction)
● Procfile / vercel.json (for deployment)]
Code
[Yahan javascript ... block mein Node.js (Express) code paste karna hai (server
setup, routes).]
Output
[Yahan API endpoints ko test karne ka example (using tools like Postman/curl)
aur expected JSON response dikhana hai. Deployed API ka URL mention karna
hai.]
28
B64
Program Explanation
The provided code defines React components, likely intended for a single file
structure. An App class component manages the state, holding the sequence of
operations (numbers and operators) in an array (this.state.operations).
Separate components Display, Buttons, and Button handle rendering the
output screen and the calculator buttons. The handleClick method updates
the operations state based on button presses. A calculateOperations
method joins the operations array into a string and uses math.eval() (likely
from the mathjs library, which would need to be installed) to compute the result
upon pressing '='.
File Structure
/Experiment_7_React_Calculator
├── public/
│ └── index.html
├── src/
│ ├── App.js (Contains all React components and logic)
│ ├── App.css (Contains styling - CSS not provided in PDF)
│ └── index.js (Renders the App component)
└── package.json (Defines dependencies like react, react-dom, mathjs)
Code
src/App.js (Components and Logic):
import React, { Component } from 'react';
// import update from 'immutability-helper'; // Needed for
the $push syntax shown in PDF
import * as math from 'mathjs'; // Needed for math.eval and
math.format
// import './App.css'; // Assuming CSS is in App.css
29
B64
// Display Component
class Display extends Component {
render() {
// Join the operations array, default to '0' if empty
const string = this.props.data.join('') || '0';
return <div className="Display"> {string} </div>;
}
}
// Button Component
class Button extends Component {
render() {
return (
<div
onClick={this.props.onClick}
className="Button"
data-size={this.props.size} // For potential styling
of wider buttons
data-value={this.props.value} // The value passed to
handleClick
>
{this.props.label} {/* The text shown on the button
*/}
</div>
);
}
}
30
B64
this.state = { operations: [] };
}
switch (value) {
case 'clear':
// Clear the operations array
this.setState({
operations: [],
});
break;
case 'equal':
// Calculate the result
this.calculateOperations();
break;
default:
// Append the button value (number or operator) to
the operations array
// Using simple array concat instead of 'update'
helper for simplicity
const newOperations = [...this.state.operations,
value];
this.setState({
operations: newOperations,
});
break; // Added missing break statement
}
// Removed extra closing brace from PDF snippet
} // Added missing closing brace for handleClick
31
B64
render() {
return (
<div className="App"> {/* Assuming a root div with
class App */}
{/* Display component showing current
operations/result */}
<Display data={this.state.operations} />
{/* Container for all buttons */}
<Buttons>
{/* Row 1 */}
<Button onClick={this.handleClick} label="C"
value="clear" />
{/* PDF shows +/- and % here, not implemented in
logic */}
<Button label="+/-" value="null" /> {/*
Placeholder */}
<Button label="%" value="null" /> {/* Placeholder
*/}
<Button onClick={this.handleClick} label="/"
value="/" />
{/* Row 2 */}
<Button onClick={this.handleClick} label="7"
value="7" />
<Button onClick={this.handleClick} label="8"
value="8" />
<Button onClick={this.handleClick} label="9"
value="9" />
<Button onClick={this.handleClick} label="x"
32
B64
value="*" />
{/* Row 3 */}
<Button onClick={this.handleClick} label="4"
value="4" />
<Button onClick={this.handleClick} label="5"
value="5" />
<Button onClick={this.handleClick} label="6"
value="6" />
<Button onClick={this.handleClick} label="-"
value="-" />
{/* Row 4 */}
<Button onClick={this.handleClick} label="1"
value="1" />
<Button onClick={this.handleClick} label="2"
value="2" />
<Button onClick={this.handleClick} label="3"
value="3" />
<Button onClick={this.handleClick} label="+"
value="+" />
{/* Row 5 */}
<Button onClick={this.handleClick} label="0"
value="0" size="2"/> {/* Assuming size="2" makes it wider
*/}
<Button onClick={this.handleClick} label="."
value="." />
<Button onClick={this.handleClick} label="="
value="equal" />
</Buttons>
</div>
);
}
}
.App {
width: 300px;
margin: 50px auto;
border: 1px solid #ccc;
border-radius: 5px;
overflow: hidden;
box-shadow: 2px 2px 5px rgba(0,0,0,0.1);
}
33
B64
.Display {
background-color: #222;
color: white;
font-size: 2em;
padding: 15px;
text-align: right;
min-height: 1.5em;
line-height: 1.5em;
word-wrap: break-word;
}
.Buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
.Button {
background-color: #f0f0f0;
border: 1px solid #ccc;
padding: 20px 0;
font-size: 1.2em;
text-align: center;
cursor: pointer;
user-select: none;
}
.Button:hover {
background-color: #e0e0e0;
}
.Button:active {
background-color: #d0d0d0;
}
.Button[data-value="/"],
.Button[data-value="*"],
.Button[data-value="-"],
.Button[data-value="+"],
.Button[data-value="equal"] {
background-color: #ff9800;
color: white;
}
.Button[data-value="/"]:hover,
.Button[data-value="*"]:hover,
34
B64
.Button[data-value="-"]:hover,
.Button[data-value="+"]:hover,
.Button[data-value="equal"]:hover {
background-color: #f57c00;
}
.Button[data-value="clear"] {
background-color: #e0e0e0;
}
.Button[data-value="clear"]:hover {
background-color: #d0d0d0;
}
.Button[data-size="2"] {
grid-column: span 2;
}
Output
35
B64
Program Explanation
The code utilizes React loaded via CDN and the useState hook to manage the
state of different voting options (name and vote count). A single functional App
component renders the list of options, displays vote counts, and provides
buttons. Clicking a "Vote" button triggers the handleVote function, which
updates the state immutably to increment the respective option's vote count.
Embedded CSS provides styling, and the Babel CDN transpiles the JSX code
within the browser.
File Structure
/Experiment_8_React_Voting
└── index.html (Contains HTML, CSS, React/JSX code, and CDN links)
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Experiment 8: React Voting App (Preview)</title>
<script
src="https://unpkg.com/react@18/umd/react.development.js"
crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-
dom.development.js" crossorigin></script>
<script
src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<style>
/* --- CSS Code --- */
/* Basic styling for the voting app */
36
B64
body {
font-family: sans-serif;
background-color: #f0f2f5; /* Apply background to body
*/
display: flex; /* Use flex to center the app */
justify-content: center;
align-items: flex-start; /* Align top */
min-height: 100vh;
padding-top: 40px; /* Add some padding at the top */
margin: 0;
}
.App {
/* font-family: sans-serif; */ /* Moved to body */
max-width: 500px;
/* margin: 40px auto; */ /* Centered by body flex */
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
background-color: #f9f9f9;
width: 90%; /* Ensure it doesn't stretch too wide on
large screens */
}
h1, h2 {
text-align: center;
color: #333;
}
.options-list {
list-style: none;
padding: 0;
margin-top: 20px;
}
.option-item {
background-color: #fff;
border: 1px solid #eee;
border-radius: 5px;
padding: 15px;
margin-bottom: 10px;
display: flex;
justify-content: space-between;
align-items: center;
transition: box-shadow 0.2s ease-in-out;
}
37
B64
.option-item:hover {
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.option-name {
font-size: 1.1em;
font-weight: 500;
}
.vote-count {
font-size: 1em;
color: #555;
margin: 0 15px; /* Added margin for spacing */
font-weight: bold;
}
.vote-button {
background-color: #007bff;
color: white;
border: none;
padding: 8px 15px;
border-radius: 4px;
cursor: pointer;
font-size: 0.9em;
transition: background-color 0.2s ease-in-out;
}
.vote-button:hover {
background-color: #0056b3;
}
.results-section {
margin-top: 30px;
padding-top: 20px;
border-top: 1px dashed #ccc;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState } = React; // Destructure useState from
React
function App() {
// Initial state for voting options
38
B64
return (
<div className="App">
<h1>React Voting App</h1>
<div className="options-section">
<h2>Cast Your Vote:</h2>
<ul className="options-list">
{options.map(option => (
<li key={option.id} className="option-item">
<div>
<span className="option-
name">{option.name}</span>
</div>
{/* Wrap vote count and button for better
alignment */}
<div style={{ display: 'flex', alignItems:
'center' }}>
{/* Display current votes */}
<span className="vote-count">Votes:
{option.votes}</span>
{/* Button to vote for this option */}
<button
39
B64
className="vote-button"
onClick={() => handleVote(option.id)} //
Call handleVote with option's id
>
Vote
</button>
</div>
</li>
))}
</ul>
</div>
</script>
</body>
</html>
40
B64
Output
41
B64
Program Explanation
The code uses a React functional component (App) with the useState hook to
manage error messages and the form submission status (isSubmitted). An
array (database) holds hardcoded username/password pairs for validation. The
handleSubmit function prevents default form submission, retrieves input
values, finds the matching user, checks the password, and updates the state
either to show an error message (using renderErrorMessage) or a success
message. Basic styling is provided via CSS (App.css).
File Structure
/Experiment_9_React_Login
├── public/
│ └── index.html
├── src/
│ ├── App.js (Contains the React component logic)
│ ├── App.css (Contains CSS styling)
│ └── index.js (Renders the App component)
└── package.json (Defines dependencies like react, react-dom)
Code
src/App.js:
import './App.css';
import React, { useState } from "react";
// import ReactDOM from "react-dom"; // ReactDOM is usually used
in index.js
function App() {
42
B64
// React States
const [errorMessages, setErrorMessages] = useState({});
const [isSubmitted, setIsSubmitted] = useState(false);
// Error messages
const errors = {
uname: "invalid username",
pass: "invalid password"
};
43
B64
}
};
return (
<div className="app">
<div className="login-form">
<div className="title">Sign In</div>
{/* Conditionally render success message or login form
*/}
{isSubmitted ? <div>User is successfully logged in</div>
: renderForm}
</div>
</div>
);
}
src/App.css:
44
B64
.app {
font-family: sans-serif;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 20px;
height: 100vh;
/* font-family: Cambria, Cochin, Georgia, Times, "Times New
Roman", serif; */ /* Overridden by sans-serif above */
background-color: #f8f9fd;
}
input[type="text"],
input[type="password"] {
height: 25px;
border: 1px solid rgba(0, 0, 0, 0.2);
padding: 5px 10px; /* Added padding for better appearance */
border-radius: 3px; /* Added border-radius */
font-size: 1em; /* Added font-size */
}
input[type="submit"] {
margin-top: 10px;
cursor: pointer;
font-size: 15px;
background: #01d28e;
border: 1px solid #01d28e;
color: #fff;
padding: 10px 20px;
border-radius: 3px; /* Added border-radius */
}
input[type="submit"]:hover {
background: #6cf0c2;
}
.button-container {
display: flex;
justify-content: center;
}
.login-form {
background-color: white;
padding: 2rem;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0
rgba(0, 0, 0, 0.19);
border-radius: 5px; /* Added border-radius */
45
B64
.error {
color: red;
font-size: 12px;
}
.title {
font-size: 25px;
margin-bottom: 20px;
text-align: center; /* Added text-align */
}
.input-container {
display: flex;
flex-direction: column;
gap: 8px;
margin: 10px;
}
46
B64
Output
47
B64
Program Explanation
Implementation: Utilizes AngularJS (CDN) with ng-model for data binding.
Validation rules (required, ng-minlength, min, max, type="email",
type="number") are applied in HTML. Error messages display conditionally
using ng-show based on form state ($touched, $invalid, $error). The
submit button uses ng-disabled="myForm.$invalid" for dynamic state
control.
File Structure
/Experiment_10_AngularJS_Validation
└── index.html (Contains HTML, CSS, AngularJS script, and CDN link)
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Experiment 10: AngularJS Validation</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angula
r.min.js"></script>
<style>
body {
font-family: sans-serif;
padding: 20px;
background-color: #f4f4f4;
}
.container {
background-color: #fff;
padding: 30px;
border-radius: 8px;
48
B64
.error-message {
color: #dc3545; /* Red color for error messages */
font-size: 0.9em;
margin-top: 5px;
padding-left: 5px;
}
button {
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
49
B64
font-size: 1em;
transition: background-color 0.2s;
}
button:hover:not(:disabled) {
background-color: #0056b3;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
h2 {
text-align: center;
color: #333;
margin-bottom: 25px;
}
</style>
</head>
<body ng-app="validationApp">
<div class="form-group">
<label for="nameInput">Name:</label>
<input type="text"
id="nameInput"
name="myName"
ng-model="user.name"
required
ng-minlength="3"
placeholder="Enter your name (min 3
chars)">
<div class="form-group">
<label for="emailInput">Email:</label>
<input type="email"
50
B64
id="emailInput"
name="myEmail"
ng-model="user.email"
required
placeholder="Enter a valid email address">
<div class="form-group">
<label for="ageInput">Age:</label>
<input type="number"
id="ageInput"
name="myAge"
ng-model="user.age"
required
min="18"
max="100"
placeholder="Enter age (18-100)">
</form>
</div>
51
B64
<script>
// Define the AngularJS application module
var app = angular.module('validationApp', []);
</body>
</html>
Output
52
B64
Program Explanation
Implementation: Uses AngularJS (CDN) with ng-model for two-way data binding
between form inputs ($scope.newStudent object) and the view. An array
($scope.students) in the controller's scope holds the student list data. The
ng-repeat directive iterates through this array to display students in an HTML
table. ng-click triggers controller functions: addStudent() copies
$scope.newStudent to the array and clears the form, while
deleteStudent(index) uses the $index provided by ng-repeat to remove
a student via splice. Basic form validation (required) and ng-disabled
control the "Add Student" button's state.
File Structure
/Experiment_11_AngularJS_Student_Info
└── index.html (Contains HTML, CSS, AngularJS script, and CDN link)
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Experiment 11: AngularJS Student Info</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angula
r.min.js"></script>
<style>
body {
font-family: sans-serif;
padding: 20px;
background-color: #f8f9fa;
53
B64
}
.container {
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
max-width: 700px; /* Wider container */
margin: auto;
}
.form-container, .table-container {
margin-bottom: 30px;
}
.form-inline .form-group {
display: inline-block; /* Display form groups inline
*/
margin-right: 15px;
margin-bottom: 10px;
vertical-align: top;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #333;
}
input[type="text"],
input[type="number"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 0.95em;
}
input.ng-invalid.ng-touched {
border-color: #dc3545;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 15px;
}
th, td {
border: 1px solid #dee2e6;
padding: 10px;
text-align: left;
}
th {
background-color: #e9ecef;
font-weight: bold;
54
B64
}
tr:nth-child(even) {
background-color: #f8f9fa;
}
button {
background-color: #007bff;
color: white;
padding: 8px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 0.9em;
transition: background-color 0.2s;
vertical-align: bottom; /* Align button with bottom
of inputs */
margin-top: 24px; /* Align with inputs */
}
button.delete-btn {
background-color: #dc3545;
padding: 5px 10px;
font-size: 0.8em;
margin-top: 0; /* Reset margin for table button */
}
button:hover:not(:disabled) {
background-color: #0056b3;
}
button.delete-btn:hover {
background-color: #c82333;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
h2, h3 {
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 5px;
margin-bottom: 20px;
}
.error-message {
color: #dc3545;
font-size: 0.8em;
margin-top: 3px;
}
</style>
</head>
<body ng-app="studentApp">
55
B64
<div class="form-container">
<h3>Add New Student</h3>
<form name="addForm" ng-submit="addStudent()"
class="form-inline" novalidate>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name"
name="studentName" ng-model="newStudent.name" required
placeholder="Student Name">
<div ng-show="addForm.studentName.$touched
&& addForm.studentName.$invalid" class="error-message">
<span ng-
show="addForm.studentName.$error.required">Name is
required.</span>
</div>
</div>
<div class="form-group">
<label for="roll">Roll No:</label>
<input type="number" id="roll"
name="studentRoll" ng-model="newStudent.roll" required
placeholder="Roll Number">
<div ng-show="addForm.studentRoll.$touched
&& addForm.studentRoll.$invalid" class="error-message">
<span ng-
show="addForm.studentRoll.$error.required">Roll No is
required.</span>
<span ng-
show="addForm.studentRoll.$error.number">Enter a valid
number.</span>
</div>
</div>
<div class="form-group">
<label for="grade">Grade:</label>
<input type="text" id="grade"
name="studentGrade" ng-model="newStudent.grade" required
placeholder="e.g., A, B+">
<div ng-show="addForm.studentGrade.$touched
&& addForm.studentGrade.$invalid" class="error-message">
<span ng-
show="addForm.studentGrade.$error.required">Grade is
required.</span>
</div>
</div>
<div class="form-group">
56
B64
<div class="table-container">
<h3>Student List</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Grade</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="student in students track by
$index">
<td>{{ student.name }}</td>
<td>{{ student.roll }}</td>
<td>{{ student.grade }}</td>
<td>
<button class="delete-btn" ng-
click="deleteStudent($index)">Delete</button>
</td>
</tr>
<tr ng-if="students.length === 0">
<td colspan="4" style="text-align:
center; color: grey;">No students added yet.</td>
</tr>
</tbody>
</table>
</div>
</div>
<script>
// Define the AngularJS application module
var app = angular.module('studentApp', []);
57
B64
$scope.students.push(angular.copy($scope.newStudent));
</body>
</html>
58
B64
Output
59
B64
Program Explanation
The application consists of two main parts:
File Structure
/Experiment_12_Online_Job_Portal
├── backend/
├── public/
│ └── index.html
├── src/
60
B64
│ ├── App.css
│ └── index.js
Code
// src/App.js (Structure Example)
import React, { useState, useEffect, useMemo } from 'react';
// import JobList from './components/JobList'; // Assuming
components are separated
// import JobDetail from './components/JobDetail';
// import apiService from './services/api'; // Assuming API
service file
function App() {
const [jobs, setJobs] = useState([]); // Initially empty,
fetched from API
const [selectedJobId, setSelectedJobId] = useState(null);
const [searchTerm, setSearchTerm] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
61
B64
return (
<div className="container mx-auto max-w-3xl">
<h1 className="text-3xl font-bold text-center mb-8 text-
gray-800">Online Job Portal</h1>
{loading && <p className="text-center">Loading
jobs...</p>}
{error && <p className="text-center text-red-
500">{error}</p>}
</div>
);
}
// Mock data needed for this snippet example if not fetching
const MOCK_JOBS = [ { id: 1, title: 'Sample Job', company:
62
B64
63
B64
module.exports = router;
64
B64
// Middleware
app.use(cors()); // Enable CORS for frontend requests
app.use(express.json()); // Parse JSON request bodies
// Basic route
app.get('/', (req, res) => {
res.send('Job Portal Backend API Running');
});
app.listen(PORT, () => {
console.log(`Backend server running on port ${PORT}`);
});
65
B64
Output
66
B64
Program Explanation
The application comprises two main parts:
File Structure
/Experiment_13_Online_Book_Shop
├── backend/
├── public/
│ └── index.html
├── src/
67
B64
│ ├── App.css
│ └── index.js
Code
// src/App.js (Structure Example)
import React, { useState, useEffect } from 'react';
// import Header from './components/Header';
// import BookList from './components/BookList';
// import BookDetail from './components/BookDetail';
// import apiService from './services/api'; // Example API
service
function App() {
const [books, setBooks] = useState([]);
const [selectedBookId, setSelectedBookId] = useState(null);
const [cartItemCount, setCartItemCount] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
68
B64
fetchBooks();
}, []);
return (
<div>
{/* <Header cartItemCount={cartItemCount} /> */}
<p>(Header Component with Cart: {cartItemCount} items)</p>
<main className="container mx-auto max-w-6xl px-4 py-4">
{loading && <p>Loading books...</p>}
{error && <p className="text-red-500">{error}</p>}
{!loading && !error ? (
selectedBook ? (
// <BookDetail book={selectedBook}
onBack={handleBackToList} onAddToCart={handleAddToCart} />
<div>
<p>(Book Detail Component for
'{selectedBook.title}')</p>
<button
onClick={handleBackToList}>Back</button>
</div>
) : (
// <BookList books={books}
onViewDetails={handleViewDetails} onAddToCart={handleAddToCart}
/>
<p>(Book List Component displaying
{books.length} books)</p>
)
) : null }
</main>
{/* Footer */}
</div>
);
}
69
B64
70
B64
module.exports = router;
71
B64
// Middleware
app.use(cors());
app.use(express.json());
// Basic route
app.get('/', (req, res) => {
res.send('Book Shop Backend API Running');
});
app.listen(PORT, () => {
console.log(`Backend server running on port ${PORT}`);
});
72
B64
Output
73
B64
Program Explanation
Implementation: The code uses React components (App, Product). The main
App component imports product data from a local products.json file. It then
maps through this data, rendering a Product component for each item within a
grid layout. The Product component displays details like image, name,
description, and price. Crucially, it includes an "Add to Cart" button with specific
snipcart-add-item class and data-item-* attributes, indicating reliance on
the external SnipCart service to handle the shopping cart and checkout process.
File Structure
/Experiment_14_Grocery_App
├── public/
│ └── index.html
├── src/
│ ├── App.jsx
│ ├── components/
│ │ └── Product/
│ ├── assets/
74
B64
Code
src/assets/products.json:
[
{
"id": "t-shirt",
"name": "Fruits",
"price": 35.0,
"imageUrl": "https://www.lalpathlabs.com/blog/wp-
content/uploads/2019/01/Fruits-and-Vegetables.jpg",
"description": "A Basket of fruits",
"url": "/api/products/halfmoon"
},
{
"id": "wallet",
"name": "Vegitables",
"price": 20.0,
"imageUrl": "https://img.freepik.com/free-photo/bottom-view-
fruits-vegetables-radish-cherry-tomatoes-persimmon-tomatoes-kiwi-
cucumber-apples-red-cabbage-parsley-quince-aubergines-blue-
table_140725-146174.jpg",
"description": "A Basket of Veges",
"url": "/api/products/wallet"
},
{
"id": "cup",
"name": "Milk",
"price": 5.0,
"imageUrl": "https://encrypted-
tbn0.gstatic.com/images?q=tbn:ANd9GcSeujHMy6OLRZHTpsrUMVLsHyiolmZ
iZI4fMQ&usqp=CAU",
"description": "Healthy Milk",
"url": "/api/products/veiltail"
}
]
src/components/Product/index.js:
import "./index.css"; // Assuming corresponding CSS exists
return (
<div
key={id} // Key should ideally be on the element generated
by .map in parent
className={"product"} // Assuming 'product' class provides
75
B64
styling
>
<img
src={imageUrl}
alt={`Image of ${name}`} // Corrected alt text
interpolation
className={"image-product"} // Assuming 'image-product'
class provides styling
/>
<h3>{name}</h3>
<p>{description}</p>
<span>${price}</span> {/* Assuming price is number,
formatting might be needed */}
<div>
<button
className="snipcart-add-item" // SnipCart specific
class
data-item-id={id}
data-item-image={imageUrl}
data-item-name={name}
data-item-url="/" // SnipCart needs URL, using root for
example
data-item-price={price}
>
Add to Cart
</button>
</div>
</div>
);
}
src/App.jsx:
import "./index.css"; // Assuming global styles
import "./App.css"; // Assuming component styles
import products from "./assets/products.json"; // Importing local
JSON data
import Product from "./components/Product"; // Importing Product
component
76
B64
77
B64
Output
78