JavaScript Client-Side Scripting Lab
JavaScript Client-Side Scripting Lab
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<button Me</button>
<script>
function showAlert() {
alert("Hello, World!");
}
</script>
</body>
</html>
2. Task: Build a form with input fields for name and email. Write JavaScript to
validate the email format when the form is submitted. Alert the user if the email
format is incorrect.
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<style>
.error { color: red; }
</style>
</head>
<body>
<form validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email" required>
<p id="emailError" class="error"></p><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
const emailInput = [Link]("email").value;
const errorElement =
[Link]("emailError");
// Simple regex for email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if () {
[Link] = "Error: Invalid email
format!";
alert("Please correct the email format.");
return false; // Prevent form submission
} else {
[Link] = ""; // Clear error
alert("Form submitted successfully!");
return true; // Allow form submission
}
}
</script>
</body>
</html>
3. Task: Develop a web page with a dropdown menu containing color options. Use
JavaScript to change the background color of the page dynamically when a
different color is selected from the dropdown.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Background Color</title>
</head>
<body>
<h1>Select a Background Color</h1>
<select id="colorSelect" > <option value="white">White</option>
<option value="lightgreen">Light Green</option>
<option value="lightblue">Light Blue</option>
<option value="lightcoral">Light Coral</option>
</select>
<script>
function changeBackground() {
const selectElement =
[Link]("colorSelect");
const selectedColor = [Link];
// Target the <body> element to change the page's
background
[Link] = selectedColor;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Even or Odd</title>
</head>
<body>
<h1>Check Even or Odd</h1>
<label for="numberInput">Enter a number:</label>
<input type="number" id="numberInput"><br><br>
<button > <p id="result"></p>
<script>
function checkEvenOdd() {
const number =
parseInt([Link]("numberInput").value);
const resultElement = [Link]("result");
if (isNaN(number)) {
[Link] = "Please enter a valid
number.";
} else if (number % 2 === 0) {
[Link] = `The number ${number} is
**Even**!`;
} else {
[Link] = `The number ${number} is
**Odd**!`;
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<h1>Simple Calculator</h1>
<label for="num1">Number 1:</label>
<input type="number" id="num1"><br><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2"><br><br>
<label for="operation">Operation:</label>
<select id="operation">
<option value="add">+</option>
<option value="subtract">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
</select><br><br>
<button > <p id="calcResult">Result:</p>
<script>
function calculate() {
const num1 =
parseFloat([Link]("num1").value);
const num2 =
parseFloat([Link]("num2").value);
const operation =
[Link]("operation").value;
let result;
if (isNaN(num1) || isNaN(num2)) {
[Link]("calcResult").textContent =
"Result: Invalid input.";
return;
}
switch (operation) {
case 'add':
result = num1 + num2;
break;
case 'subtract':
result = num1 - num2;
break;
case 'multiply':
result = num1 * num2;
break;
case 'divide':
if (num2 === 0) {
result = "Cannot divide by zero!";
} else {
result = num1 / num2;
}
break;
default:
result = "Invalid operation.";
}
[Link]("calcResult").textContent =
`Result: ${result}`;
}
</script>
</body>
</html>
3. Task: Create a JavaScript array of numbers. Use JavaScript to find and display
the largest number in the array when a button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>Find Largest Number</title>
</head>
<body>
<h1>Largest Number Finder</h1>
<p>The array is: **[12, 45, 6, 88, 23, 71]**</p>
<button Largest</button>
<p id="largestResult"></p>
<script>
const numbers = [12, 45, 6, 88, 23, 71];
function findLargest() {
const largest = [Link](...numbers); // Use spread
operator and [Link]()
// Alternative using a loop:
/*
let largest = numbers[0];
for (let i = 1; i < [Link]; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
*/
[Link]("largestResult").textContent =
`The largest number in the array is: **${largest}**`;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation - Add Element</title>
</head>
<body>
<div id="content">
<p>This is the original paragraph.</p>
</div>
<button New Paragraph</button>
<script>
let count = 1;
function addParagraph() {
// 1. Create the new element
const newParagraph = [Link]("p");
// 2. Set its content
[Link] = `Dynamically created paragraph
#${count}`;
// 3. Append it to an existing container element
[Link]("content").appendChild(newParagraph);
count++;
}
</script>
</body>
</html>
2. Task: Build a form with input fields for first name, last name, and age. Use
JavaScript to validate the form fields and display appropriate error messages
beside each field.
(This is similar to Lab 1.1, Task 2, but requires inline error messages.)
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation - Inline Validation</title>
<style>
.error { color: red; font-size: 0.8em; }
.form-group { margin-bottom: 10px; }
</style>
</head>
<body>
<form validateUserDetails()">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName">
<span id="firstNameError" class="error"></span>
</div>
<div class="form-group">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName">
<span id="lastNameError" class="error"></span>
</div>
<div class="form-group">
<label for="age">Age:</label>
<input type="number" id="age" name="age">
<span id="ageError" class="error"></span>
</div>
<input type="submit" value="Submit">
</form>
<script>
function validateUserDetails() {
let isValid = true;
// Validate First Name (must not be empty)
const fName =
[Link]("firstName").[Link]();
const fNameError =
[Link]("firstNameError");
if (fName === "") {
[Link] = "First name is required.";
isValid = false;
} else {
[Link] = "";
}
// Validate Last Name (must not be empty)
const lName =
[Link]("lastName").[Link]();
const lNameError =
[Link]("lastNameError");
if (lName === "") {
[Link] = "Last name is required.";
isValid = false;
} else {
[Link] = "";
}
// Validate Age (must be a number > 0)
const age =
parseInt([Link]("age").value);
const ageError = [Link]("ageError");
if (isNaN(age) || age <= 0) {
[Link] = "Age must be a positive
number.";
isValid = false;
} else {
[Link] = "";
}
if (isValid) {
alert("Form is valid and ready to submit!");
}
return isValid; // Return false to stop submission if
invalid
}
</script>
</body>
</html>
3. Task: Create an HTML table with some data. Write JavaScript to sort the table
rows alphabetically based on a specific column when a button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation - Table Sorting</title>
</head>
<body>
<h1>Sortable Table</h1>
<button by Name</button>
<button by Country</button>
<table id="myTable" border="1">
<thead>
<tr>
<th>Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr><td>Charlie</td><td>USA</td></tr>
<tr><td>Alice</td><td>Canada</td></tr>
<tr><td>David</td><td>Germany</td></tr>
<tr><td>Bob</td><td>France</td></tr>
</tbody>
</table>
<script>
function sortTable(columnIndex) {
const table = [Link]("myTable");
const tbody = [Link]("tbody");
const rows = [Link]([Link]("tr")); //
Convert NodeList to Array
// Sort the array of rows
[Link]((a, b) => {
// Get the cell content for the specified column index
(0-based)
const aText =
[Link][columnIndex].[Link]().toUpperCase();
const bText =
[Link][columnIndex].[Link]().toUpperCase();
if (aText < bText) return -1;
if (aText > bText) return 1;
return 0; // names are equal
});
// Re-append the sorted rows to the table body
[Link](row => [Link](row));
}
</script>
</body>
</html>
File 1: input_form.html
<!DOCTYPE html>
<html>
<head>
<title>PHP Form Input</title>
</head>
<body>
<form method="POST" action="display_data.php">
<label for="name">Name:</label>
<input type="text" id="name" name="userName" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="userEmail"
required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
File 2: display_data.php
<!DOCTYPE html>
<html>
<head>
<title>Display Data</title>
</head>
<body>
<?php
// Check if the form was submitted using the POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the data from the $_POST superglobal array
$name = htmlspecialchars($_POST['userName']);
$email = htmlspecialchars($_POST['userEmail']);
echo "<h2>Submitted Information:</h2>";
echo "<p>Name: **$name**</p>";
echo "<p>Email: **$email**</p>";
} else {
echo "<p>No data submitted.</p>";
}
?>
</body>
</html>
File 1: password_generator.php
<!DOCTYPE html>
<html>
<head>
<title>Random Password Generator</title>
</head>
<body>
<h1>Random Password Generator</h1>
<form method="POST" action="">
<input type="submit" name="generate" value="Generate
Password">
</form>
<?php
function generateRandomPassword($length = 10) {
$chars =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&
*()';
$password = '';
$max_index = strlen($chars) - 1;
for ($i = 0; $i < $length; $i++) {
// Select a random character from the string
$password .= $chars[rand(0, $max_index)];
}
return $password;
}
// Check if the button was clicked
if (isset($_POST['generate'])) {
$newPassword = generateRandomPassword(12); // Generate a
12-character password
echo "<br><h3>Generated Password:</h3>";
echo "<p style='font-weight: bold; color:
green;'>$newPassword</p>";
}
?>
</body>
</html>
3. Task: Develop a PHP program that calculates the factorial of a number entered
by the user and displays the result.
File 1: factorial_calculator.php
<!DOCTYPE html>
<html>
<head>
<title>Factorial Calculator</title>
</head>
<body>
<h1>Factorial Calculator</h1>
<form method="POST" action="">
<label for="number">Enter a non-negative integer:</label>
<input type="number" id="number" name="number" required
min="0"><br><br>
<input type="submit" value="Calculate Factorial">
</form>
<?php
function calculateFactorial($n) {
if (!is_numeric($n) || $n < 0 || $n != floor($n)) {
return "Invalid input. Please enter a non-negative
integer.";
}
if ($n == 0) {
return 1;
} else {
$factorial = 1;
for ($i = 1; $i <= $n; $i++) {
$factorial *= $i;
}
return $factorial;
}
}
// Check if the form was submitted and the 'number' is set
if (isset($_POST['number'])) {
$inputNumber = $_POST['number'];
$result = calculateFactorial($inputNumber);
echo "<br><h3>Result:</h3>";
echo "<p>The factorial of **$inputNumber** is
**$result**.</p>";
}
?>
</body>
</html>
1. Task: Set up a MySQL database with a table to store student information (name,
age, email). Write PHP code to insert new records into the table from a form.
File: insert_student.php
<?php
// ** 1. Database Configuration **
$servername = "localhost";
$username = "root"; // Default XAMPP/WAMP user
$password = ""; // Default XAMPP/WAMP password
$dbname = "patnisthadb";
// ** 2. Handle Form Submission **
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['name'])) {
$name = htmlspecialchars($_POST['name']);
$age = htmlspecialchars($_POST['age']);
$email = htmlspecialchars($_POST['email']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL to insert data (using prepared statements for security)
$stmt = $conn->prepare("INSERT INTO students (name, age, email)
VALUES (?, ?, ?)");
$stmt->bind_param("sis", $name, $age, $email); // "s" = string,
"i" = integer
if ($stmt->execute()) {
$message = "<span style='color: green;'>New record created
successfully.</span>";
} else {
$message = "<span style='color: red;'>Error: " . $stmt->error
. "</span>";
}
$stmt->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Insert Student Record</title>
</head>
<body>
<h1>Add New Student</h1>
<?php echo $message; ?>
<form method="POST" action="">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required
min="1"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Insert Record">
</form>
</body>
</html>
2. Task: Write PHP code to retrieve and display student records from the MySQL
database in a tabular format on a webpage.
File: view_students.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "patnisthadb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL to select data
$sql = "SELECT id, name, age, email FROM students";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>View Student Records</title>
<style>
table, th, td { border: 1px solid black; border-collapse:
collapse; padding: 8px; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Student Records</h1>
<?php
if ($result->num_rows > 0) {
// Start the table
echo "<table>";
echo
"<thead><tr><th>ID</th><th>Name</th><th>Age</th><th>Email</th></tr></t
head>";
echo "<tbody>";
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["age"] . "</td>";
echo "<td>" . $row["email"] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
} else {
echo "<p>0 results found in the table.</p>";
}
$conn->close();
?>
</body>
</html>
3. Task: Implement a PHP script to update the email address of a student in the
MySQL database based on their ID.
File: update_email.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "patnisthadb";
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST['studentId'])) {
$studentId = htmlspecialchars($_POST['studentId']);
$newEmail = htmlspecialchars($_POST['newEmail']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL to update data (using prepared statements)
$stmt = $conn->prepare("UPDATE students SET email = ? WHERE id =
?");
$stmt->bind_param("si", $newEmail, $studentId);
if ($stmt->execute()) {
if ($stmt->affected_rows > 0) {
$message = "<span style='color: green;'>Record with ID
**$studentId** updated successfully.</span>";
} else {
$message = "<span style='color: orange;'>No record found
with ID **$studentId** or email is the same.</span>";
}
} else {
$message = "<span style='color: red;'>Error updating record: "
. $stmt->error . "</span>";
}
$stmt->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Update Student Email</title>
</head>
<body>
<h1>Update Student Email</h1>
<?php echo $message; ?>
<form method="POST" action="">
<label for="studentId">Student ID to Update:</label>
<input type="number" id="studentId" name="studentId"
required><br><br>
<label for="newEmail">New Email Address:</label>
<input type="email" id="newEmail" name="newEmail"
required><br><br>
<input type="submit" value="Update Email">
</form>
</body>
</html>
🍪 Lab 2.3: PHP Sessions and Cookies
🔐 Lab 2: Advanced Server Side Scripting
Lab 2.3: PHP Sessions and Cookies
1. Task: Create a login form using PHP. Implement session management to
authenticate users and redirect them to a welcome page upon successful login.
2. Task: Write PHP code to set a cookie containing the user's preferred language
choice and display a greeting message in the chosen language on subsequent
visits.
File: language_selector.php
<?php
$default_lang = 'en';
$selected_lang = $default_lang;
$message = "";
$languages = [
'en' => "Hello! Welcome to our site.",
'fr' => "Bonjour! Bienvenue sur notre site.",
'es' => "¡Hola! Bienvenido a nuestro sitio.",
];
// Handle form submission to set the cookie
if (isset($_POST['language'])) {
$selected_lang = $_POST['language'];
// Set the cookie to expire in 30 days
setcookie('user_language', $selected_lang, time() + (86400 * 30),
"/");
$message = "Language preference saved successfully!";
}
// Check for existing cookie
elseif (isset($_COOKIE['user_language'])) {
$selected_lang = $_COOKIE['user_language'];
$message = "Your saved language preference is **" .
strtoupper($selected_lang) . "**.";
}
// Get the greeting message based on the determined language
$greeting = $languages[$selected_lang] ?? $languages[$default_lang];
?>
<!DOCTYPE html>
<html>
<head>
<title>Language Preference Cookie</title>
</head>
<body>
<h1>Language Preference</h1>
<p style="font-weight: bold;"><?php echo $message; ?></p>
<h2>Greeting:</h2>
<p style="color: blue; font-size: 1.2em;">**<?php echo $greeting;
?>**</p>
<form method="POST" action="">
<label for="language">Select Language:</label>
<select id="language" name="language">
<option value="en" <?php echo ($selected_lang == 'en' ?
'selected' : ''); ?>>English</option>
<option value="fr" <?php echo ($selected_lang == 'fr' ?
'selected' : ''); ?>>French</option>
<option value="es" <?php echo ($selected_lang == 'es' ?
'selected' : ''); ?>>Spanish</option>
</select>
<input type="submit" value="Save Preference">
</form>
</body>
</html>
3. Task: Develop a PHP script to track and display the number of times a user has
visited a webpage using cookies.
File: visit_tracker.php
<?php
$visits = 1; // Default visit count
// Check if the 'visit_count' cookie exists
if (isset($_COOKIE['visit_count'])) {
// Retrieve the current count
$visits = $_COOKIE['visit_count'];
// Increment for the current visit
$visits++;
}
// Set or update the cookie. Expires in 1 year.
$expiry_time = time() + (86400 * 365); // 86400 seconds = 1 day
setcookie('visit_count', $visits, $expiry_time, "/");
?>
<!DOCTYPE html>
<html>
<head>
<title>Visit Counter Cookie</title>
</head>
<body>
<h1>Visit Counter</h1>
<p>According to your browser's cookies, this is your:</p>
<?php
echo "<h2 style='color: green;'>**" . number_format($visits) .
"** visit(s) to this page!</h2>";
?>
<p>Try refreshing the page to see the counter increase.</p>
<p style="font-size: 0.9em; color: gray;">
(Note: The cookie will last for 1 year unless cleared by your
browser.)
</p>
</body>
</html>
File: product_oop.php
<?php
class Product {
// Properties (Attributes)
public $name;
public $price;
public $description;
// Constructor method
public function __construct($name, $price, $description) {
$this->name = $name;
$this->price = $price;
$this->description = $description;
}
// Method (Behavior)
public function displayDetails() {
echo "<div>";
echo "<h3>{$this->name}</h3>";
echo "<p><strong>Price:</strong> $" .
number_format($this->price, 2) . "</p>";
echo "<p><strong>Description:</strong>
{$this->description}</p>";
echo "</div>";
}
}
// Create instances (Objects) of the Product class
$laptop = new Product("UltraBook Pro", 1299.99, "A lightweight,
high-performance laptop for professionals.");
$mouse = new Product("Ergo Wireless Mouse", 25.50, "Ergonomic design
with silent clicks.");
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP OOP - Products</title>
</head>
<body>
<h1>Our Products</h1>
<?php
// Call the displayDetails method on each object
$laptop->displayDetails();
$mouse->displayDetails();
?>
</body>
</html>
File: shape_inheritance.php
<?php
// Base Class
abstract class Shape {
abstract public function calculateArea(): float;
abstract public function calculatePerimeter(): float;
public function displayCalculations() {
echo "<div>";
echo "<h4>" . get_class($this) . "</h4>";
echo "<p>Area: **" . number_format($this->calculateArea(), 2)
. "**</p>";
echo "<p>Perimeter: **" .
number_format($this->calculatePerimeter(), 2) . "**</p>";
echo "</div>";
}
}
// Derived Class 1
class Circle extends Shape {
private $radius;
const PI = 3.14159;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea(): float {
return self::PI * $this->radius * $this->radius;
}
public function calculatePerimeter(): float {
return 2 * self::PI * $this->radius; // Circumference
}
}
// Derived Class 2
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function calculateArea(): float {
return $this->width * $this->height;
}
public function calculatePerimeter(): float {
return 2 * ($this->width + $this->height);
}
}
// Create instances
$myCircle = new Circle(5.0);
$myRectangle = new Rectangle(10.0, 4.5);
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP OOP - Inheritance & Shapes</title>
</head>
<body>
<h1>Shape Calculations using Inheritance</h1>
<?php
$myCircle->displayCalculations();
$myRectangle->displayCalculations();
?>
</body>
</html>
3. Task: Create a PHP program to handle exceptions for file operations such as
reading and writing files. Display appropriate error messages when exceptions
occur.
File: file_exception_handler.php
<?php
$filename = "test_file.txt";
$output = "";
function readFileContent($file) {
if (!file_exists($file)) {
// Throw an exception if the file doesn't exist
throw new Exception("File Not Found: The file **'$file'** does
not exist.", 1001);
}
if (!is_readable($file)) {
// Throw an exception if the file is not readable
throw new Exception("Permission Denied: Cannot read file
**'$file'**.", 1002);
}
$content = file_get_contents($file);
return "File **'$file'** read successfully. Content length: " .
strlen($content) . " bytes.";
}
// ----------------------------------------------------
// Example 1: Trying to read a file that exists (should succeed)
// Create the file first for the test to pass
file_put_contents($filename, "This is test content.");
try {
$output .= "<h3>Attempt 1 (Success):</h3>";
$output .= "<p style='color: green;'>" .
readFileContent($filename) . "</p>";
} catch (Exception $e) {
$output .= "<h3>Attempt 1 (Failure):</h3>";
$output .= "<p style='color: red;'>Caught Exception: **Code
{$e->getCode()}** - {$e->getMessage()}</p>";
}
// Example 2: Trying to read a file that does NOT exist (should fail)
try {
$output .= "<h3>Attempt 2 (Failure):</h3>";
$output .= "<p>" . readFileContent("non_existent_file.log") .
"</p>";
} catch (Exception $e) {
$output .= "<h3>Attempt 2 (Failure):</h3>";
$output .= "<p style='color: red;'>Caught Exception: **Code
{$e->getCode()}** - {$e->getMessage()}</p>";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Exception Handling</title>
</head>
<body>
<h1>File Operation Exception Handling</h1>
<?php echo $output; ?>
</body>
</html>
(Note: This requires a publicly available Weather API key, e.g., from OpenWeatherMap. For the
lab, we'll demonstrate the AJAX structure and a dummy data fetch.)
File 1: [Link] (Front-end with AJAX)
<!DOCTYPE html>
<html>
<head>
<title>AJAX Weather App</title>
</head>
<body>
<h1>Real-Time Weather Fetch</h1>
<label for="city">Enter City:</label>
<input type="text" id="city" value="London">
<button Weather</button>
<div id="weather-display" style="border: 1px solid #ccc;
margin-top: 20px; padding: 10px;">
Click 'Get Weather' to load data...
</div>
<script>
function fetchWeather() {
const city = [Link]('city').value;
const display =
[Link]('weather-display');
[Link] = 'Loading weather data for **' + city +
'...**';
// 1. Create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();
// 2. Configure the request: GET request to the PHP
backend
[Link]('GET', 'get_weather.php?city=' +
encodeURIComponent(city), true);
// 3. Define the function to run when the request
completes
[Link] = function() {
// Check if request is done (4) and successful (200)
if ([Link] === 4 && [Link] === 200) {
// Update the DOM with the response data
[Link] = [Link];
} else if ([Link] === 4) {
// Handle errors
[Link] = 'Error fetching data. Status:
' + [Link];
}
};
// 4. Send the request
[Link]();
}
</script>
</body>
</html>
(Pre-requisite: Assume you have a products table with columns id and name.)
File 1: ajax_db_loader.html (Front-end with Button)
<!DOCTYPE html>
<html>
<head>
<title>AJAX Database Loader</title>
</head>
<body>
<h1>AJAX Database Loader</h1>
<button Products</button>
<div id="product-list" style="margin-top: 20px;">
Click the button to load product data from the database...
</div>
<script>
function loadProducts() {
const display = [Link]('product-list');
[Link] = 'Connecting to database and fetching
data...';
const xhr = new XMLHttpRequest();
[Link]('GET', 'fetch_products.php', true);
[Link] = function() {
if ([Link] === 4 && [Link] === 200) {
[Link] = [Link];
} else if ([Link] === 4) {
[Link] = 'Error loading data: ' +
[Link];
}
};
[Link]();
}
</script>
</body>
</html>
3. Task: Implement form validation using AJAX and PHP to check if a username is
already taken in a database when a user tries to register.
(This requires including the jQuery library in the HTML.) File: jquery_slideshow.html
<!DOCTYPE html>
<html>
<head>
<title>jQuery Slideshow</title>
<style>
.slideshow-container { position: relative; max-width: 600px;
margin: auto; }
.mySlides { display: none; } /* Hide all slides by default */
.slide-img { width: 100%; height: auto; }
.prev, .next { cursor: pointer; position: absolute; top: 50%;
width: auto; padding: 16px; margin-top: -22px; color: white;
font-weight: bold; font-size: 18px; transition: 0.6s ease;
border-radius: 0 3px 3px 0; user-select: none; background-color:
rgba(0,0,0,0.8); }
.next { right: 0; border-radius: 3px 0 0 3px; }
</style>
<script
src="[Link]
></script>
</head>
<body>
<h1>jQuery Image Slideshow</h1>
<div class="slideshow-container">
<div class="mySlides fade"><img src="[Link]"
class="slide-img" alt="Image 1"></div>
<div class="mySlides fade"><img src="[Link]"
class="slide-img" alt="Image 2"></div>
<div class="mySlides fade"><img src="[Link]"
class="slide-img" alt="Image 3"></div>
<a class="prev" > <a class="next" > </div>
<script>
let slideIndex = 1;
// Function to show a specific slide
function showSlides(n) {
const $slides = $('.mySlides'); // Select all slides using
jQuery
if (n > $[Link]) { slideIndex = 1 } // Wrap around
to the first slide
if (n < 1) { slideIndex = $[Link] } // Wrap around
to the last slide
$[Link](); // Hide all slides
$($slides[slideIndex - 1]).show(); // Show the current
slide
}
// Function to change the slide index
function plusSlides(n) {
showSlides(slideIndex += n);
}
// Initialize the slideshow when the document is ready
$(document).ready(function() {
showSlides(slideIndex);
});
</script>
</body>
</html>
2. Task: Use jQuery UI widget for a date picker to select a date from a calendar
and display it in a text input field.
File: jquery_hide_show.html
<!DOCTYPE html>
<html>
<head>
<title>jQuery Hide/Show</title>
<script
src="[Link]
></script>
<style>
#secret-message {
background-color: yellow;
padding: 10px;
border: 1px solid orange;
margin-top: 15px;
}
</style>
</head>
<body>
<h1>jQuery Hide/Show Toggle</h1>
<button id="toggle-btn">Toggle Message Visibility</button>
<p>
<input type="checkbox" id="checkbox-toggle">
<label for="checkbox-toggle">Check to Show Message</label>
</p>
<div id="secret-message">
<p>This message is controlled by both the button and the
checkbox!</p>
</div>
<script>
$(document).ready(function() {
// 1. Button Interaction (Using .toggle() for simple
hide/show)
$("#toggle-btn").click(function() {
$("#secret-message").toggle(500); // 500ms slide
animation
});
// 2. Checkbox Interaction (Using .show() and .hide())
$("#checkbox-toggle").change(function() {
if ($(this).is(":checked")) {
$("#secret-message").show(300); // Show quickly
} else {
$("#secret-message").hide(300); // Hide quickly
}
});
// Initial state: hide the message if the checkbox is
unchecked
if (!$("#checkbox-toggle").is(":checked")) {
$("#secret-message").hide();
}
});
</script>
</body>
</html>
1. Installation:
○ Prerequisites: Ensure XAMPP/WAMP/MAMP is running (Apache, MySQL, PHP).
○ Download: Download the latest Joomla package from the official site.
○ Extract: Extract the files into your local server's web root (e.g., htdocs/joomla).
○ Database: Create a new MySQL database (e.g., joomladb).
○ Web Installer: Navigate to [Link] and follow the on-screen steps,
providing site name, superuser credentials, and the database details.
2. Template Customization (Via Administrator Panel):
○ Log into the Joomla Administrator Panel ([Link]
○ Navigate to System -> Templates -> Site Templates.
○ Find the active template (e.g., Cassiopeia) and click on its name to open the editor.
○ Use the editor to change Colors, Fonts, and Layout settings provided by the
template's developer.
○ For advanced layout/style changes: Navigate to System -> Site Template Styles,
find your style, and use the Custom CSS section to add your own CSS rules to
override default styles.
2. Task: Install a new Joomla module that displays a list of recent articles on the
homepage with thumbnails and summaries.
1. Find and Download Module: Search the Joomla Extensions Directory for a "Recent
Articles Module" or similar. Download the .zip file.
2. Installation:
○ In the Joomla Administrator Panel, navigate to System -> Install -> Extensions.
○ Drag and drop the downloaded .zip file or use the "Browse for file" button to upload
and install the module.
3. Module Configuration:
○ Navigate to Content -> Site Modules.
○ Locate the newly installed module (or the built-in Latest Articles module).
○ Position: Set the module's position to one that is visible on the homepage (e.g.,
sidebar-right, position-7).
○ Menu Assignment: Ensure the module is set to display on the Home menu item.
○ Options: Configure the options to include a thumbnail and a short summary (intro
text) for each article.
○ Save & Close. The recent articles list should now appear on the frontend.
1. Installation: (Similar to Joomla, but easier using the Famous 5-Minute Install)
○ Download: Download WordPress from the official site.
○ Extract: Extract into your web root (e.g., htdocs/wordpress).
○ Database: Create a MySQL database (e.g., wp_db).
○ Run Installer: Navigate to [Link] and complete the installation.
2. Install a Custom Theme:
○ Log into the WordPress Dashboard (/wp-admin).
○ Navigate to Appearance -> Themes -> Add New.
○ Search for a custom theme (e.g., Astra, OceanWP, or upload a custom theme
ZIP).
○ Click Install and then Activate.
3. Theme Customization:
○ Navigate to Appearance -> Customize. This opens the WordPress Customizer.
○ Logo: Find the Site Identity section to upload your logo image.
○ Colors: Find the Colors or Global/General section to change the primary and
accent colors.
○ Header/Footer: Use the corresponding sections in the Customizer to change
layouts, add widgets, or modify copyright text.
2. Task: Create a new WordPress Page with custom content and configure it to be
the homepage of the website.
3. Task: Install and activate WordPress plugins for additional functionality, such
as SEO optimization, social media sharing, or site backup. Configure the plugins
according to the site's requirements.