0% found this document useful (0 votes)
11 views26 pages

Lab Manual Solution AWP 2025

The document provides a comprehensive guide for creating various applications using Node.js and AngularJS, including a library management system, MongoDB operations for insertion, selection, updating, and deletion, as well as file management functionalities such as creating, reading, writing, and deleting files. It also covers setting up a file upload application using Express and Multer, along with a file compression and decompression feature. Each section includes code snippets and instructions for implementation, aimed at enhancing web programming skills for students in the IT Department at GEC Bhavnagar.
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)
11 views26 pages

Lab Manual Solution AWP 2025

The document provides a comprehensive guide for creating various applications using Node.js and AngularJS, including a library management system, MongoDB operations for insertion, selection, updating, and deletion, as well as file management functionalities such as creating, reading, writing, and deleting files. It also covers setting up a file upload application using Express and Multer, along with a file compression and decompression feature. Each section includes code snippets and instructions for implementation, aimed at enhancing web programming skills for students in the IT Department at GEC Bhavnagar.
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/ 26

Lab Manual Solution-IT Department, GEC Bhavnagar

Semester-6 Advanced Web Programming

1. Create a single page application for Library that will allow the librarian to add a new book and search
whether book is currently available in the library or not.

index.js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Library System</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="libraryApp">
<div ng-controller="LibraryController as libCtrl">
<h1>Library System</h1>

<h2>Add New Book</h2>


<form ng-submit="libCtrl.addBook()">
<input type="text" ng-model="libCtrl.newBook.title" placeholder="Book Title" required>
<input type="text" ng-model="libCtrl.newBook.author" placeholder="Author" required>
<button type="submit">Add Book</button>
</form>

<h2>Search for a Book</h2>


<input type="text" ng-model="libCtrl.searchTitle" placeholder="Search by Title">
<button ng-click="libCtrl.searchBook()">Search</button>

<h3>Available Books</h3>
<ul>
<li ng-repeat="book in libCtrl.books">
{{book.title}} by {{book.author}}
</li>
</ul>

<h3>Search Result:</h3>
<div ng-if="libCtrl.searchResult">
<p>{{libCtrl.searchResult.title}} by {{libCtrl.searchResult.author}} is available.</p>
</div>
<div ng-if="!libCtrl.searchResult && libCtrl.searchTitle">
<p>No book found with the title "{{libCtrl.searchTitle}}".</p>
</div>
</div>
</body>
</html>
app.js

var app = angular.module('libraryApp', []);

app.controller('LibraryController', function() {
var vm = this;
vm.books = [];
vm.newBook = {};
vm.searchTitle = '';
vm.searchResult = null;

vm.addBook = function() {
vm.books.push({
title: vm.newBook.title,
author: vm.newBook.author
});
vm.newBook = {}; // Clear the input fields
};

vm.searchBook = function() {
vm.searchResult = vm.books.find(book => book.title.toLowerCase() ===
vm.searchTitle.toLowerCase()) || null;
};
});

Output
2.Write Node JS code to perform selection and updation operation to select and update specific
document in Mongo DB.

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

// Create database
MongoClient.connect(url, function (err, db) {
if (err) throw err;

var dbo = db.db("customer");


var data = { name: 'bharatvainsh' }; // Selector
var data1 = { $set: { name: "jack" } }; // Update statement

// Update the document


dbo.collection("custreg").updateOne(data, data1, function (err, res) {
if (err) throw err;
console.log("One document updated");
db.close(); // Move db.close() inside the callback
});
});

Write Node JS code to perform deletion operation from Mongo DB.

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

// Create database
MongoClient.connect(url, function (err, db) {
if (err) throw err;

var dbo = db.db("customer");


var data = { name: "jack" }; // Document to delete

dbo.collection("custreg").deleteOne(data, function (err, res) {


if (err) throw err;
console.log("One document deleted");

db.close(); // Close the database connection here


});
});
Study MongoDB environment setup and write Node JS code to perform insertion
operation in Mongo DB.

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

// Create database
MongoClient.connect(url, function(err, db) {
if (err) throw err;

var dbo = db.db("customer");


var myobj = { name: "John", password: "Highway 37" }; // Document to insert

dbo.collection("custreg").insertOne(myobj, function(err, res) {


if (err) throw err;
console.log("1 document inserted");

db.close(); // Close the database connection


});
});
Create a Node JS application that will allow a user to create new file, read file, write
into a file and delete a file.

const fs = require('fs');
const readline = require('readline');

// Setup readline interface for user input


const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

// Function to create a new file


function createFile(filename, content) {
fs.writeFile(filename, content, (err) => {
if (err) {
console.error("Error creating file:", err);
} else {
console.log(`File '${filename}' created successfully!`);
}
rl.close();
});
}

// Function to read a file


function readFile(filename) {
fs.readFile(filename, 'utf8', (err, data) => {
if (err) {
console.error("Error reading file:", err);
} else {
console.log(`File content of '${filename}':\n`, data);
}
rl.close();
});
}

// Function to write to a file


function writeFile(filename, content) {
fs.appendFile(filename, content, (err) => {
if (err) {
console.error("Error writing to file:", err);
} else {
console.log(`Content added to '${filename}' successfully!`);
}
rl.close();
});
}

// Function to delete a file


function deleteFile(filename) {
fs.unlink(filename, (err) => {
if (err) {
console.error("Error deleting file:", err);
} else {
console.log(`File '${filename}' deleted successfully!`);
}
rl.close();
});
}

// Main function to interact with the user


function main() {
console.log("\nFile Manager:");
console.log("1. Create a new file");
console.log("2. Read a file");
console.log("3. Write to a file");
console.log("4. Delete a file");

rl.question("\nChoose an option (1-4): ", (option) => {


switch(option) {
case '1':
rl.question("Enter the filename: ", (filename) => {
rl.question("Enter content to write into the file: ", (content) => {
createFile(filename, content);
});
});
break;
case '2':
rl.question("Enter the filename to read: ", (filename) => {
readFile(filename);
});
break;
case '3':
rl.question("Enter the filename to write into: ", (filename) => {
rl.question("Enter content to add to the file: ", (content) => {
writeFile(filename, content);
});
});
break;
case '4':
rl.question("Enter the filename to delete: ", (filename) => {
deleteFile(filename);
});
break;
default:
console.log("Invalid option. Please choose between 1 and 4.");
rl.close();
}
});
}
main();

node file1.js

1. Create a new file


2. Read a file
3. Write to a file
4. Delete a file

Choose an option (1-4): 1


Enter the filename: bharat
Enter content to write into the file: hello nodejs
File 'bharat' created successfully!
PS C:\Users\vainshbharat\Documents\NODEJS\File> 2
2
PS C:\Users\vainshbharat\Documents\NODEJS\File> node file1.js
File Manager:
1. Create a new file
2. Read a file
3. Write to a file
4. Delete a file
Choose an option (1-4): 2
Enter the filename to read: bharat
File content of 'bharat':
hello nodejs
PS C:\Users\vainshbharat\Documents\NODEJS\File>
Create a Node JS application that will allow a user to browse and upload a file in
localhost.
file-upload-app/
├── node_modules/
├── public/ │ └── index.html
├── uploads/ (Folder for storing uploaded files)
├── app.js └── package.json

C:\Users\vainshbharat\Documents\NODEJS\fileupload> npm install mongodb

added 12 packages, and audited 13 packages in 2s

C:\Users\vainshbharat\Documents\NODEJS\fileupload> npm install express multer


added 88 packages, and audited 101 packages in 4s

15 packages are looking for funding


run `npm fund` for details

found 0 vulnerabilities
PS C:\Users\vainshbharat\Documents\NODEJS\fileupload>
PS C:\Users\vainshbharat\Documents\NODEJS\fileupload> npm install express

up to date, audited 101 packages in 1s

15 packages are looking for funding


run `npm fund` for details

found 0 vulnerabilities
PS C:\Users\vainshbharat\Documents\NODEJS\fileupload> node app.js
Server is running on http://localhost:3000
PS C:\Users\vainshbharat\Documents\NODEJS\fileupload> node app.js
Server is running on http://localhost:3000

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h1>Upload File</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required />
<button type="submit">Upload</button>
</form>
</body>
</html>
app.js
const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();


const PORT = 3000;

// Set up storage configuration for multer


const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // Destination folder for uploaded files
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname)); // Append timestamp to the file
name
}
});

const upload = multer({ storage: storage });

// Serve the HTML form


app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html')); // Adjust the path as needed
});

// Handle file upload


app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
res.send(`File uploaded successfully: ${req.file.filename}`);
});

// Start the server


app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

Create the uploads Directory: The uploads/ folder will store the files uploaded by the user.
Ensure this folder exists in your project directory.

mkdir uploads

Access the Application: Open your browser and navigate to http://localhost:3000. You
should see the file upload form. You can browse and upload a file, and it will be saved in the
uploads directory.
Express is used to create a simple server that listens on port 3000.
Multer is used to handle file uploads. The uploaded file is stored in the uploads/ directory
with a unique filename (timestamped).
The form in index.html sends the uploaded file to the /upload route using POST. The file is
processed by multer and saved in the uploads/ folder.
Once the file is uploaded, the server sends a success message back to the user.
Design a webpage with a file input control to browse appropriate file and four buttons Read File
Synchronously, Read File Asynchronously, Compress File, and Decompress File. Implement the
functionality of all four buttons on the browsed file using Node JS.

1. Frontend (HTML & JavaScript):

The frontend will provide a simple file input, four buttons, and a display area to show the
result or status of each action.

2. Backend (Node.js):

We will create a backend to handle the file reading and compression/decompression using
libraries like fs (for reading files) and zlib (for compression and decompression).

Project Setup

Step 1: Initialize a Node.js project

First, ensure you have Node.js installed on your machine. Then, initialize a Node.js project:

mkdir file-compression-app
cd file-compression-app
npm init –y

npm install express multer

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Compression & Decompression</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.container {
max-width: 600px;
margin: auto;
text-align: center;
}
input[type="file"] {
margin: 20px 0;
}
button {
margin: 10px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
#output {
margin-top: 20px;
white-space: pre-wrap;
}
</style>
</head>
<body>
<div class="container">
<h1>File Compression and Decompression</h1>
<input type="file" id="fileInput">
<div>
<button onclick="readFileSync()">Read File Synchronously</button>
<button onclick="readFileAsync()">Read File Asynchronously</button>
<button onclick="compressFile()">Compress File</button>
<button onclick="decompressFile()">Decompress File</button>
</div>
<div id="output"></div>
</div>

<script>
let selectedFile = null;

document.getElementById('fileInput').addEventListener('change', function(e) {
selectedFile = e.target.files[0];
});

function readFileSync() {
if (!selectedFile) {
alert("Please select a file first.");
return;
}

const reader = new FileReader();


reader.onload = function(event) {
document.getElementById('output').textContent = event.target.result;
};
reader.readAsText(selectedFile);
}

function readFileAsync() {
if (!selectedFile) {
alert("Please select a file first.");
return;
}

const reader = new FileReader();


reader.onload = function(event) {
document.getElementById('output').textContent = event.target.result;
};
reader.readAsText(selectedFile);
}
function compressFile() {
if (!selectedFile) {
alert("Please select a file first.");
return;
}

const formData = new FormData();


formData.append('file', selectedFile);
fetch('/compress', {
method: 'POST',
body: formData,
})
.then(response => response.text())
.then(data => {
document.getElementById('output').textContent = 'Compressed File: ' + data;
})
.catch(error => console.error('Error:', error));
}

function decompressFile() {
if (!selectedFile) {
alert("Please select a file first.");
return;
}

const formData = new FormData();


formData.append('file', selectedFile);
fetch('/decompress', {
method: 'POST',
body: formData,
})
.then(response => response.text())
.then(data => {
document.getElementById('output').textContent = 'Decompressed File: ' + data;
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>

Server.js

const express = require('express');


const multer = require('multer');
const fs = require('fs');
const zlib = require('zlib');
const path = require('path');

const app = express();


const port = 3000;
// Set up storage for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
},
});

const upload = multer({ storage: storage });

// Create the 'uploads' directory if it doesn't exist


if (!fs.existsSync('uploads')) {
fs.mkdirSync('uploads');
}

// Serve the static HTML file


app.use(express.static('public'));

// Endpoint to compress the file


app.post('/compress', upload.single('file'), (req, res) => {
const filePath = req.file.path;
const compressedPath = filePath + '.gz';

const fileStream = fs.createReadStream(filePath);


const compressedStream = fs.createWriteStream(compressedPath);
const gzip = zlib.createGzip();

fileStream.pipe(gzip).pipe(compressedStream);

compressedStream.on('finish', () => {
res.send(`File compressed successfully: ${compressedPath}`);
});
});

// Endpoint to decompress the file


app.post('/decompress', upload.single('file'), (req, res) => {
const filePath = req.file.path;
const decompressedPath = filePath.replace('.gz', '');

const fileStream = fs.createReadStream(filePath);


const decompressedStream = fs.createWriteStream(decompressedPath);
const gunzip = zlib.createGunzip();

fileStream.pipe(gunzip).pipe(decompressedStream);

decompressedStream.on('finish', () => {
res.send(`File decompressed successfully: ${decompressedPath}`);
});
});

// Start the server


app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Create an example demonstrating the concept of Angular JS Routing.

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Routing Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular-
route.min.js"></script>
</head>
<body>
<!-- Main Navigation -->
<div>
<a href="#!home">Home</a> |
<a href="#!about">About</a> |
<a href="#!contact">Contact</a>
</div>

<!-- View Content (Dynamic content will load here) -->


<div ng-view></div>

<!-- AngularJS App Script -->


<script src="app.js"></script>
</body>
</html>

Indx.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Routing Example</title>
</head>
<body>

<!-- Main Navigation -->


<div>
<a href="#!home">Home</a> |
<a href="#!about">About</a> |
<a href="#!contact">Contact</a>
</div>

<!-- View Content (Dynamic content will load here) -->


<div ng-view></div>

<!-- AngularJS App Script -->


<script src="app.js"></script>
</body>
</html>
app.js

// Define the AngularJS Module and configure routes


var app = angular.module('myApp', ['ngRoute']);

// Configure the Routes


app.config(function($routeProvider) {
$routeProvider
.when("/home", {
template: "<h1>Welcome to the Home Page</h1><p>This is the home page of the
AngularJS Routing example.</p>"
})
.when("/about", {
template: "<h1>About Us</h1><p>This page contains information about us.</p>"
})
.when("/contact", {
template: "<h1>Contact Us</h1><p>This is the contact page. Reach us at
[email protected].</p>"
})
.otherwise({
redirectTo: '/home' // Default route
});
});
Create an Angular JS application for validation that will accept Email, Username and
Password as required fields from the user. It will enable submit button only if all the
entered data are valid.

index.html

<!DOCTYPE html>
<html lang="en" ng-app="validationApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Validation Example</title>
<script src="https://code.angularjs.org/1.8.2/angular.min.js"></script>
<style>
.error { color: red; }
.valid { color: green; }
</style>
</head>
<body>
<div ng-controller="FormController">
<h2>Signup Form</h2>

<form name="signupForm" ng-submit="submitForm()" novalidate>


<div>
<label>Email:</label>
<input type="email" name="email" ng-model="email" required email />
<span class="error" ng-show="signupForm.email.$touched &&
signupForm.email.$invalid">Email is required and must be valid.</span>
</div>

<div>
<label>Username:</label>
<input type="text" name="username" ng-model="username" required />
<span class="error" ng-show="signupForm.username.$touched &&
signupForm.username.$invalid">Username is required.</span>
</div>

<div>
<label>Password:</label>
<input type="password" name="password" ng-model="password" required ng-
minlength="6" />
<span class="error" ng-show="signupForm.password.$touched &&
signupForm.password.$invalid">Password is required and must be at least 6
characters.</span>
</div>

<div>
<button type="submit" ng-disabled="signupForm.$invalid">Submit</button>
</div>
</form>

<div ng-show="formSubmitted">
<p>Form Submitted!</p>
<p><strong>Email:</strong> {{ email }}</p>
<p><strong>Username:</strong> {{ username }}</p>
<p><strong>Password:</strong> {{ password }}</p>
</div>
</div>

<script>
var app = angular.module('validationApp', []);

app.controller('FormController', function($scope) {
$scope.formSubmitted = false;

// Function to handle form submission


$scope.submitForm = function() {
if ($scope.signupForm.$valid) {
$scope.formSubmitted = true;
} else {
alert("Please fill in the form correctly.");
}
};
});
</script>
</body>
</html>
Write Angular JS code to read Customer’s data in JSON format available in a
Customers.php file using $http service and display the same on a webpage in tabular
format.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Customer Data</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="customerApp" ng-controller="customerCtrl">

<h2>Customer Data</h2>

<!-- Table to display customer data -->


<table border="1">
<thead>
<tr>
<th>Customer ID</th>
<th>Customer Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="customer in customers">
<td>{{ customer.id }}</td>
<td>{{ customer.name }}</td>
<td>{{ customer.email }}</td>
<td>{{ customer.phone }}</td>
</tr>
</tbody>
</table>

<script src="app.js"></script>
</body>
</html>
app.js

// Create AngularJS app module


var app = angular.module('customerApp', []);

// Define controller for the app


app.controller('customerCtrl', function($scope, $http) {

// Initialize customers array


$scope.customers = [];

// Fetch customer data from Customers.php file


$http.get('Customers.php')
.then(function(response) {
// Assign data to customers array on successful API response
$scope.customers = response.data;
}, function(error) {
// Handle error if the request fails
console.error('Error fetching customer data: ', error);
});
});

customer.php

<?php
// Customers.php file to simulate a response in JSON format

// Sample customer data


$customers = [
["id" => 1, "name" => "John Doe", "email" => "[email protected]", "phone" => "123-
456-7890"],
["id" => 2, "name" => "Jane Smith", "email" => "[email protected]", "phone" =>
"987-654-3210"],
["id" => 3, "name" => "Mary Johnson", "email" => "[email protected]",
"phone" => "555-555-5555"]
];

// Set content type to JSON


header('Content-Type: application/json');

// Convert the PHP array to JSON format and output it


echo json_encode($customers);
?>
Modify Practical 3 and provide a search field to search records on the top of the page
and allow user to sort table according to the column values when user clicks on a
column using filter.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table with Search and Sort</title>
<style>
/* Simple styling for the table and search field */
body {
font-family: Arial, sans-serif;
margin: 20px;
}

input[type="text"] {
padding: 10px;
margin-bottom: 20px;
width: 200px;
border: 1px solid #ccc;
}

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

th, td {
padding: 10px;
text-align: left;
border: 1px solid #ddd;
}

th {
cursor: pointer;
}

th.sortable:hover {
background-color: #f1f1f1;
}
</style>
</head>
<body>

<!-- Search Input -->


<input type="text" id="searchInput" placeholder="Search records..."
onkeyup="searchTable()">

<!-- Table -->


<table id="dataTable">
<thead>
<tr>
<th class="sortable" onclick="sortTable(0)">ID</th>
<th class="sortable" onclick="sortTable(1)">Name</th>
<th class="sortable" onclick="sortTable(2)">Age</th>
<th class="sortable" onclick="sortTable(3)">City</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John Doe</td>
<td>28</td>
<td>New York</td>
</tr>
<tr>
<td>2</td>
<td>Jane Smith</td>
<td>34</td>
<td>Los Angeles</td>
</tr>
<tr>
<td>3</td>
<td>Mike Johnson</td>
<td>40</td>
<td>Chicago</td>
</tr>
<tr>
<td>4</td>
<td>Amy Brown</td>
<td>25</td>
<td>Miami</td>
</tr>
</tbody>
</table>

<script>
// Function to filter records based on search input
function searchTable() {
const input = document.getElementById('searchInput').value.toUpperCase();
const table = document.getElementById('dataTable');
const tr = table.getElementsByTagName('tr');

for (let i = 1; i < tr.length; i++) {


const td = tr[i].getElementsByTagName('td');
let found = false;
for (let j = 0; j < td.length; j++) {
if (td[j]) {
const txtValue = td[j].textContent || td[j].innerText;
if (txtValue.toUpperCase().indexOf(input) > -1) {
found = true;
break;
}
}
}
tr[i].style.display = found ? '' : 'none';
}
}

// Function to sort the table by a specific column


function sortTable(n) {
const table = document.getElementById('dataTable');
const rows = table.rows;
let switching = true;
let shouldSwitch;
let dir = 'asc'; // Set the sorting direction to ascending
let switchcount = 0;

while (switching) {
switching = false;
const rowsArray = Array.from(rows);
for (let i = 1; i < rowsArray.length - 1; i++) {
shouldSwitch = false;
const x = rowsArray[i].getElementsByTagName('TD')[n];
const y = rowsArray[i + 1].getElementsByTagName('TD')[n];

if (dir === 'asc') {


if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir === 'desc') {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}

if (shouldSwitch) {
rowsArray[i].parentNode.insertBefore(rowsArray[i + 1], rowsArray[i]);
switching = true;
switchcount++;
} else {
if (switchcount === 0 && dir === 'asc') {
dir = 'desc';
switching = true;
}
}
}
}
</script>
</body>
</html>
Create a HTML form that will accept Enrolment No., Name, Semester, Branch, Mobile
Number, Email, Address etc. from the student and display them on the page using
Angular JS Directives and Expressions.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Enrolment Form</title>

<!-- Include AngularJS -->


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

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

form {
margin-bottom: 20px;
}

label {
margin-right: 10px;
}

input, textarea {
margin-bottom: 10px;
padding: 5px;
width: 300px;
}

.form-group {
margin-bottom: 15px;
}

.result {
margin-top: 20px;
padding: 10px;
background-color: #f0f0f0;
}
</style>
</head>
<body ng-app="studentApp" ng-controller="studentCtrl">

<h1>Student Enrolment Form</h1>

<!-- Form to Accept Student Information -->


<form name="studentForm">
<div class="form-group">
<label for="enrollmentNo">Enrolment No.:</label>
<input type="text" id="enrollmentNo" ng-model="student.enrollmentNo" required>
</div>

<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" ng-model="student.name" required>
</div>

<div class="form-group">
<label for="semester">Semester:</label>
<input type="text" id="semester" ng-model="student.semester" required>
</div>

<div class="form-group">
<label for="branch">Branch:</label>
<input type="text" id="branch" ng-model="student.branch" required>
</div>

<div class="form-group">
<label for="mobile">Mobile Number:</label>
<input type="text" id="mobile" ng-model="student.mobile" required>
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" ng-model="student.email" required>
</div>

<div class="form-group">
<label for="address">Address:</label>
<textarea id="address" ng-model="student.address" required></textarea>
</div>

<button type="submit" ng-click="submitForm()" ng-


disabled="studentForm.$invalid">Submit</button>
</form>

<!-- Display Submitted Information -->


<div class="result" ng-if="submitted">
<h3>Student Details:</h3>
<p><strong>Enrolment No.:</strong> {{ student.enrollmentNo }}</p>
<p><strong>Name:</strong> {{ student.name }}</p>
<p><strong>Semester:</strong> {{ student.semester }}</p>
<p><strong>Branch:</strong> {{ student.branch }}</p>
<p><strong>Mobile Number:</strong> {{ student.mobile }}</p>
<p><strong>Email:</strong> {{ student.email }}</p>
<p><strong>Address:</strong> {{ student.address }}</p>
</div>

<script>
// AngularJS Application Module and Controller
var app = angular.module('studentApp', []);

app.controller('studentCtrl', function($scope) {
$scope.student = {}; // Object to store form data
Design a webpage that reads a Text file using AJAX.

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Read Text File with AJAX</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#output {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
background-color: #f9f9f9;
white-space: pre-wrap;
word-wrap: break-word;
}
</style>
</head>
<body>

<h1>Read a Text File using AJAX</h1>


<button id="loadFileBtn">Load Text File</button>

<div id="output"></div>

<script src="script.js"></script>

</body>
</html>
Script.js

document.getElementById('loadFileBtn').addEventListener('click', loadTextFile);

function loadTextFile() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'demo.txt', true); // Make sure your file is in the same directory or specify
the correct path

xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('output').textContent = xhr.responseText;
} else {
document.getElementById('output').textContent = "Error loading the file!";
}
};

xhr.onerror = function() {
document.getElementById('output').textContent = "Request failed.";
};

xhr.send();
}

Demo.txt

This is the content of the text file.


It can contain multiple lines and any text.
AJAX is used to load it into the webpage.

You might also like