0% found this document useful (0 votes)
14 views

web development practical file

Uploaded by

vesopa8821
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)
14 views

web development practical file

Uploaded by

vesopa8821
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/ 43

A

PRACTICAL FILE

ON

Web Development

24CSC402SE01

In Partial Fulfilment of the Requirements in Bachelor of Computer Applications

Sem-02

Session: 2024-27

Submitted to: Submitted by:

Ms. Aastha Student id:

Assistant professor. BCA-2-C

Dept. of Computer Science

DPG STM
S.no. Pg.no.
Topics
Create an XML document to store information about a collection of
1 books, including elements for author, publication year, and genre.
Write a simple html page that uses JavaScript to load and display the
XML data.
Create an XML file and an XSLT stylesheet to transform the
2 XML data into an html table. Use the transformation Node or
XSLTProcessor methods to apply the transformation and
display the result in a web page.
Write an HTML page with an script that loads an XML file containing a
3 list of employees. Parse the XML data with JavaScript and display the
employee names and departments in the list of the web page.
Write an HTML page with an script that loads an XML file containing a list of
4 employees. Parse the XML data with JavaScript and display the employee
names and departments in the list of the web page.
Write a Ajax Script to get player details from xml file when user select
5 player name game. Also create xml file to store details of
player(name, country, wickets and runs).
Write a AJAX request to URL that does not exist. Implement error
6 handling to display a user friendly message when the request fails.
Write a jQuery code to select values from a JSONobject. Also
7 Write a jQuery code to remove all CSS classes from an
Applications.
Create a php Script that defines variable of different data
8 types (string, integer, float, Boolean, array). Output the values
and types of these variables using echo and var_dump.
Develop an HTML form to upload a file. Write a php
9 script to handle the file upload, save the file on the
server, and display a message indicating the file upload
status.
Create a MySQL database and table to store user information
10 (name, email). Write a PHP Script to connect to the database
and insert a new user record. Display a success message upon
successful insertion.

11 Create a web page for travel agency


using PHP.
Q.1 Create an XML document to store information about a collection of
books, including elements for author, publication year, and genre.
Write a simple html page that uses JavaScript to load and display the
XML data.
Syntax:
<?xml version="1.0" encoding="UTF-8"?>

<library>

<book>

<title>The Catcher in the Rye</title>

<author>J.D. Salinger</author>

<year>1951</year>

<genre>Fiction</genre>

</book>

<book>

<title>1984</title>

<author>George Orwell</author>

<year>1949</year>

<genre>Dystopian</genre>

</book>

<book>

<title>To Kill a Mockingbird</title>

<author>Harper Lee</author>

<year>1960</year>

<genre>Fiction</genre>

</book>

<book>

<title>Brave New World</title>

<author>Aldous Huxley</author>

<year>1932</year>

<genre>Dystopian</genre>

</book>

</library>
HTML Syntax:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Book Collection</title>

</head>

<body>

<h1>Book Collection</h1>

<div id="bookList"></div>

<script>

// Sample XML data embedded in the script

const xmlData = `<?xml version="1.0" encoding="UTF-8"?>

<library>

<book>

<title>The guide</title>

<author>R K Narayan</author>

<year>1906</year>

<genre>writer</genre>

</book>

<book>

<title>The story of my life</title>

<author>Ruskin Bond</author>

<year>1961</year>

<genre>Indian Litrature</genre>

</book>

<book>

<title>The Namesake</title>

<author>Jhumpa Lahiri</author>
<year>1967</year>

<genre>Litery Fiction</genre>

</book>

<book>

<title>Brave New World</title>

<author>Aldous Huxley</author>

<year>1932</year>

<genre>Dystopian</genre>

</book>

</library>`;

// Function to parse and display XML data

function loadXML() {

// Parse the XML data from the string

const parser = new DOMParser();

const xmlDoc = parser.parseFromString(xmlData, "application/xml");

// Get all the books

const books = xmlDoc.getElementsByTagName("book");

let output = "<ul>";

// Loop through the books and extract details

for (let i = 0; i < books.length; i++) {

const title = books[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;

const author = books[i].getElementsByTagName("author")[0].childNodes[0].nodeValue;

const year = books[i].getElementsByTagName("year")[0].childNodes[0].nodeValue;

const genre = books[i].getElementsByTagName("genre")[0].childNodes[0].nodeValue;

// Append each book's details to the output

output += `<li><strong>Title:</strong> ${title} <br><strong>Author:</strong> ${author} <br><strong>Year:</strong> ${year}


<br><strong>Genre:</strong> ${genre}</li>`;

// Close the unordered list and display it in the div

output += "</ul>";
document.getElementById("bookList").innerHTML = output;

// Call the function to load the XML when the page loads

window.onload = loadXML;

</script>

</body>

</html>
Output:
Q.2 Create an XML file and an XSLT stylesheet to transform the XML
data into an html table. Use the transformation Node or XSLTProcessor
methods to apply the transformation and display the result in a web
page.
XML Syntax:
<student>
<name>John Doe</name>
<age>20</age>
<grade>A</grade>
</student>
<student>
<name>Jane Smith</name>
<age>22</age>
<grade>B</grade>
</student>
<student>
<name>Mark Johnson</name>
<age>21</age>
<grade>A</grade>
</student>
</students><!-- XSLT Stylesheet (style.xsl) --><?xml version="1.0"
encoding="UTF-8"?><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template
match="/"> <html> <head> <title>Student List</title> </head> <body>
<h2>Student Information</h2> <table border="1"> <tr> <th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr> <xsl:for-each
select="students/student">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="age"/></td>
<td><xsl:value-of
select="grade"/></td> </tr>
</xsl:for-each> </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
HTML Syntax:
<!-- HTML File to display transformation (index.html) --><!DOCTYPE
html><html>
<head>
<title>XML to HTML Transformation</title>
</head>
<body>
<script>
if (window.ActiveXObject || "ActiveXObject" in window) { // For IE
var xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.load("students.xml");
var xsl = new ActiveXObject("Microsoft.XMLDOM");
xsl.async = false;
xsl.load("style.xsl");
document.write(xml.transformNode(xsl));
} else if (document.implementation &&
document.implementation.createDocument) { // For modern browsers
var xsltProcessor = new XSLTProcessor();
var xmlDoc = new DOMParser().parseFromString(<?xml
version='1.0'?><students><student><name>John
Doe</name><age>20</age><grade>A</grade></student><student><nam
e>Jane
Smith</name><age>22</age><grade>B</grade></student><student><na
me>Mark
Johnson</name><age>21</age><grade>A</grade></student></students>
, 'text/xml');
var xslDoc = new DOMParser().parseFromString(<?xml
version='1.0'?> <xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:template
match='/'> <html><head><title>Student
List</title></head><body><h2>Student Information</h2><table
border='1'><tr><th>Name</th><th>Age</th><th>Grade</th></tr><xsl:foreach select='students/student'><tr><td><xsl:value-of
select='name'/></td><td><xsl:value-of select='age'/></td><td><xsl:valueof
select='grade'/></td></tr></xsl:foreach></table></body></html></xsl:template></xsl:stylesheet>,
'text/xml');
xsltProcessor.importStylesheet(xslDoc);
var resultDocument = xsltProcessor.transformToFragment(xmlDoc,
document);
document.body.appendChild(resultDocument);
}
</script>
</body>
</html>
Output:
Q.3 Write an HTML page with an script that loads an XML file
containing a list of employees. Parse the XML data with JavaScript and
display the employee names and departments in the list of the web
page.
Syntax:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Employee List</title>

<style>

body {

font-family: Arial, sans-serif;

padding: 20px;

h1 {

text-align: center;

#employeeList {

margin-top: 20px;

.employee {

margin: 10px 0;

padding: 10px;

border: 1px solid #ccc;

border-radius: 5px;

}
.employee .name {

font-weight: bold;

.employee .department {

font-style: italic;

</style>

</head>

<body>

<h1>Employee List</h1>

<div id="employeeList"></div>

<script>

// Simulated XML data (In real scenario, you would load it from a file or server)

const xmlData = `<?xml version="1.0" encoding="UTF-8"?>

<employees>

<employee>

<name>John Doe</name>

<department>HR</department>

</employee>

<employee>

<name>Jane Smith</name>

<department>IT</department>

</employee>

<employee>

<name>George Brown</name>

<department>Finance</department>

</employee>

<employee>
<name>Lisa White</name>

<department>Marketing</department>

</employee>

</employees>`;

// Function to parse XML and display data

function displayEmployees(xmlString) {

const parser = new DOMParser();

const xmlDoc = parser.parseFromString(xmlString, "application/xml");

const employees = xmlDoc.getElementsByTagName("employee");

const employeeList = document.getElementById("employeeList");

// Clear any existing list

employeeList.innerHTML = '';

for (let i = 0; i < employees.length; i++) {

const name = employees[i].getElementsByTagName("name")[0].textContent;

const department = employees[i].getElementsByTagName("department")[0].textContent;

const employeeDiv = document.createElement("div");

employeeDiv.classList.add("employee");

const nameElement = document.createElement("div");

nameElement.classList.add("name");

nameElement.textContent = name;

const departmentElement = document.createElement("div");

departmentElement.classList.add("department");

departmentElement.textContent = department;

employeeDiv.appendChild(nameElement);

employeeDiv.appendChild(departmentElement);
employeeList.appendChild(employeeDiv);

// Display the employees when the page loads

displayEmployees(xmlData);

</script>

</body>

</html>
Output:
Q.4 Develop a form that allows users to submit their contact
information (name, email, message). Use AJAX to send the form data
to a server-side Script (e.g., a PHP Script) that echoes the received
data. Display the server’s response on the web page.
Syntax:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Contact Form</title>

<script>

function sendForm(event) {

event.preventDefault();

let formData = new FormData(document.getElementById("contactForm"));

fetch("process.php", {

method: "POST",

body: formData

})

.then(response => response.text())

.then(data => document.getElementById("response").innerHTML = data);

</script>

</head>

<body>

<h2>Contact Us</h2>

<form id="contactForm" onsubmit="sendForm(event)">

<input type="text" name="name" placeholder="Name" required><br><br>


<input type="email" name="email" placeholder="Email" required><br><br>

<textarea name="message" placeholder="Your Message" required></textarea><br><br>

<button type="submit">Send</button>

</form>

<div id="response"></div>

</body>

</html>
Output:
Q.5 Write a Ajax Script to get player details from xml file when user
select player name game. Also create xml file to store details of
player(name, country, wickets and runs).
Xml Syntax:
<?xml version="1.0" encoding="UTF-8"?>

<players>

<player>

<name>Virat Kohli</name>

<country>India</country>

<wickets>0</wickets>

<runs>12000</runs>

</player>

<player>

<name>Steve Smith</name>

<country>Australia</country>

<wickets>0</wickets>

<runs>8000</runs>

</player>

<player>

<name>Ben Stokes</name>

<country>England</country>

<wickets>150</wickets>

<runs>5000</runs>

</player>

<player>

<name>Shakib Al Hasan</name>

<country>Bangladesh</country>

<wickets>250</wickets>

<runs>6000</runs>

</player>

</players>
Output:
XML+Ajax:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Player Details</title>

<style>

body {

font-family: Arial, sans-serif;

padding: 20px;

h1 {

text-align: center;

#playerDetails {

margin-top: 20px;

padding: 10px;

border: 1px solid #ccc;

border-radius: 5px;

</style>

</head>

<body>

<h1>Player Details</h1>

<label for="playerSelect">Select Player:</label>

<select id="playerSelect">

<option value="">Select a player</option>

<option value="Virat Kohli">Virat Kohli</option>

<option value="Steve Smith">Steve Smith</option>


<option value="Ben Stokes">Ben Stokes</option>

<option value="Shakib Al Hasan">Shakib Al Hasan</option>

</select>

<div id="playerDetails"></div>

<script>

// Function to load player details from XML using Ajax

function loadPlayerDetails(playerName) {

if (!playerName) {

document.getElementById('playerDetails').innerHTML = '';

return;

const xhr = new XMLHttpRequest();

xhr.open('GET', 'player-details.xml', true); // Change this path if XML file is elsewhere

xhr.onreadystatechange = function() {

if (xhr.readyState === 4 && xhr.status === 200) {

const xmlDoc = xhr.responseXML;

const players = xmlDoc.getElementsByTagName('player');

let playerInfo = '';

for (let i = 0; i < players.length; i++) {

const name = players[i].getElementsByTagName('name')[0].textContent;

if (name === playerName) {

const country = players[i].getElementsByTagName('country')[0].textContent;

const wickets = players[i].getElementsByTagName('wickets')[0].textContent;

const runs = players[i].getElementsByTagName('runs')[0].textContent;

playerInfo = `

<h2>Player: ${name}</h2>

<p><strong>Country:</strong> ${country}</p>

<p><strong>Wickets:</strong> ${wickets}</p>
<p><strong>Runs:</strong> ${runs}</p>

`;

break;

if (playerInfo === '') {

playerInfo = `<p>No details found for ${playerName}.</p>`;

document.getElementById('playerDetails').innerHTML = playerInfo;

};

xhr.send();

// Event listener for player selection

document.getElementById('playerSelect').addEventListener('change', function() {

const selectedPlayer = this.value;

loadPlayerDetails(selectedPlayer);

});

</script>

</body>

</html>
Output:
Q.6 Write a AJAX request to URL that does not exist. Implement error
handling to display a user friendly message when the request fails.
Syntax:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>AJAX Error Handling</title>

<script>

function fetchData() {

let xhr = new XMLHttpRequest();

xhr.open("GET", "nonexistent_url.php", true); // URL that does not exist

xhr.onreadystatechange = function () {

if (xhr.readyState === 4) {

if (xhr.status === 200) {

document.getElementById("result").innerHTML = xhr.responseText;

} else {

document.getElementById("result").innerHTML =

"Error: Unable to fetch data. Please try again later.";

};

xhr.send();

</script>

</head>

<body>

<h2>AJAX Error Handling Example</h2>


<button onclick="fetchData()">Fetch Data</button>

<div id="result"></div>

</body>

</html>
Output:
Q.7 Write a jQuery code to select values from a JSONobject. Also Write
a jQuery code to remove all CSS classes from an Applications.
HTML Syntax:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>jQuery Select from JSON</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body>

<script>

$(document).ready(function() {

var jsonObject = {

"name": "John",

"age": 30,

"city": "New York"

};

// Accessing values from JSON object

console.log("Name: " + jsonObject.name); // Output: Name: John

console.log("Age: " + jsonObject.age); // Output: Age: 30

console.log("City: " + jsonObject.city); // Output: City: New York

});

</script>

</body>

</html>
Output:
Q.8 Create a php Script that defines variable of different data types
(string, integer, float, Boolean, array). Output the values and types of
these variables using echo and var_dump.
Syntax:
<?php

// Defining variables with different data types

// String

$name = "John Doe";

// Integer

$age = 30;

// Float

$price = 19.99;

// Boolean

$is_active = true;

// Array

$colors = array("red", "green", "blue");

// Output values and types using echo and var_dump

// Output string with echo

echo "Name: $name<br>";

// Output string type using var_dump

var_dump($name);

echo "<br><br>";

// Output integer with echo

echo "Age: $age<br>";

// Output integer type using var_dump

var_dump($age);

echo "<br><br>";

// Output float with echo

echo "Price: $price<br>";

// Output float type using var_dump

var_dump($price);
echo "<br><br>";

// Output boolean with echo

echo "Is active: " . ($is_active ? 'True' : 'False') . "<br>";

// Output boolean type using var_dump

var_dump($is_active);

echo "<br><br>";

// Output array with echo (only the value)

echo "Colors: ";

echo implode(", ", $colors) . "<br>";

// Output array type using var_dump

var_dump($colors);

?>
Output:
Q.9 Develop an HTML form to upload a file. Write a php script to
handle the file upload, save the file on the server, and display a
message indicating the file upload status.
Syntax:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>File Upload Form</title>

</head>

<body>

<h2>Upload a File</h2>

<!-- The enctype attribute is important for file uploads -->

<form action="upload.php" method="POST" enctype="multipart/form-data">

<label for="fileToUpload">Choose a file to upload:</label>

<input type="file" name="fileToUpload" id="fileToUpload">

<br><br>

<input type="submit" value="Upload File" name="submit">

</form>

</body>

</html>
Output:
Q.10 Create a MySQL database and table to store user information
(name, email). Write a PHP Script to connect to the database and
insert a new user record. Display a success message upon successful
insertion.
Syntax:
-- Create the database

CREATE DATABASE user_database;

-- Use the created database

USE user_database;

-- Create a table to store user information

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

email VARCHAR(100) NOT NULL UNIQUE

);
Output:
Q.11 Create a web page for travel agency using PHP.

Syntax:
<?php

// Initialize variables for form data

$name = $email = $destination = "";

$nameErr = $emailErr = $destinationErr = "";

$successMessage = "";

// Process form submission

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Validate name

if (empty($_POST["name"])) {

$nameErr = "Name is required";

} else {

$name = sanitize_input($_POST["name"]);

// Validate email

if (empty($_POST["email"])) {

$emailErr = "Email is required";

} else {

$email = sanitize_input($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$emailErr = "Invalid email format";

// Validate destination

if (empty($_POST["destination"])) {

$destinationErr = "Destination is required";

} else {
$destination = sanitize_input($_POST["destination"]);

// If no errors, display a success message

if (empty($nameErr) && empty($emailErr) && empty($destinationErr)) {

$successMessage = "Thank you, $name! We have received your request to travel to $destination. We will contact you at
$email.";

// Function to sanitize input data

function sanitize_input($data) {

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

return $data;

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Travel Agency</title>

<style>

body {

font-family: Arial, sans-serif;

background-color: #f0f8ff;

margin: 0;

padding: 0;

header {
background-color: #4CAF50;

color: white;

text-align: center;

padding: 10px 0;

.container {

width: 60%;

margin: 0 auto;

padding: 20px;

background-color: #fff;

box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);

border-radius: 8px;

form {

display: flex;

flex-direction: column;

label {

margin-top: 10px;

font-weight: bold;

input[type="text"], input[type="email"], select {

padding: 8px;

margin: 5px 0;

border: 1px solid #ccc;

border-radius: 4px;

input[type="submit"] {

padding: 10px;

background-color: #4CAF50;

color: white;

border: none;

cursor: pointer;
}

.error {

color: red;

.success {

color: green;

font-weight: bold;

</style>

</head>

<body>

<header>

<h1>Welcome to the Travel Agency</h1>

<p>Your dream vacation is just a few steps away!</p>

</header>

<div class="container">

<h2>Book Your Next Adventure</h2>

<?php

if ($successMessage != "") {

echo "<p class='success'>$successMessage</p>";

?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

<label for="name">Full Name:</label>

<input type="text" id="name" name="name" value="<?php echo $name;?>">

<span class="error"><?php echo $nameErr;?></span>

<label for="email">Email:</label>

<input type="email" id="email" name="email" value="<?php echo $email;?>">

<span class="error"><?php echo $emailErr;?></span>

<label for="destination">Choose Your Destination:</label>


<select id="destination" name="destination">

<option value="">Select a destination</option>

<option value="Paris" <?php if ($destination == "Paris") echo "selected";?>>Paris</option>

<option value="New York" <?php if ($destination == "New York") echo "selected";?>>New York</option>

<option value="Tokyo" <?php if ($destination == "Tokyo") echo "selected";?>>Tokyo</option>

<option value="Sydney" <?php if ($destination == "Sydney") echo "selected";?>>Sydney</option>

</select>

<span class="error"><?php echo $destinationErr;?></span>

<input type="submit" value="Submit">

</form>

</div>

</body>

</html>
Output:

Form after submission(without error)


Thank you, John Doe! We have received your request to travel to
Paris. We will contact you at [email protected].

You might also like