KEMBAR78
Lab Manual Web Desigining 3rd Sem-1 | PDF | World Wide Web | Internet & Web
0% found this document useful (0 votes)
57 views50 pages

Lab Manual Web Desigining 3rd Sem-1

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)
57 views50 pages

Lab Manual Web Desigining 3rd Sem-1

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/ 50

WEB DEVELOPMENT

(LAB MANUAL)
Semester Course Code Name of the course L T P Credit
s
III IT Web Development Lab 0 0 2 1

Sr. No Course CO statement


Outcome
number
1 CO1 The students will be able to Analyze a web page and identify its elements and attributes.
2 CO2 The students will be able to Create web pages using XHTML and Cascading Style
Sheets.
3 CO3 The students will be able to Build dynamic web pages using JavaScript (Client-side
programming).

List of Experiment
1. Design an html form for displaying information using interactive css including images, tables.
2. Create a webpage with HTML describing your department with following specification:
a.Change the background color of the page. At the bottom create a link to take user to the top of the page.
b. Insert an image and create a link such that clicking on image takes user to other page.
c. Also apply font styling like italics, underline and two other fonts to words you find appropriate. Also use header
tags.
3. Write a JavaScript to design a simple calculator to perform the following operations: sum, product, difference and
quotient.
4. Write a JavaScript to validate the following fields of employee on html form: email, name, mobile no., address,
salary.
5. Develop and demonstrate a HTML file that includes JavaScript script that uses functions for the following
problems
Parameter: A string Output: Length of the String
Parameter: A number Output: The number with its digits in the reverse order
6. Develop and demonstrate a HTML file that includes JavaScript for the following problems:
Input: A starting and ending number
Output: find all the prime numbers between starting and ending number.
7. Write a PHP program to display a digital clock which displays the current time of the server.
8. Write a PHP program to implement sign-In and Sign-out functionality.
9. Write a PHP program to keep track of the number of visitors visiting the Web page and to display this count of
visitors, with proper headings.
10. Write a PHP code to implement AJAX functionality.
Experiment No : 0

Aim : Introduction to Web development .

Theory : Web technology refers to the tools, languages, protocols, and


standards that are used to create and maintain websites and web
applications. It encompasses both the front-end (client-side) and back-
end (server-side) aspects of web development. Here’s an overview of
key components and concepts in web technology.

Front-End Technologies:

1. HTML (Hypertext Markup Language):


o HTML is the standard markup language for creating web
pages. It defines the structure and content of a webpage
using tags and elements.
2. CSS (Cascading Style Sheets):
o CSS is used for styling HTML elements. It controls the
layout, appearance, and presentation of web pages, making
them visually appealing and responsive.
3. JavaScript:
o JavaScript is a scripting language that adds interactivity to
web pages. It allows for dynamic content, user interactions,
form validation, and more.
4. Responsive Design:
o Responsive web design ensures that websites adapt to
different screen sizes and devices, providing a consistent
user experience across desktops, tablets, and smartphones.
5. Front-End Frameworks and Libraries:
o Frameworks like React, Angular, and Vue.js provide
structured environments and pre-built components to
simplify and accelerate front-end development.
Back-End Technologies:

1. Server-Side Languages:
o Languages like PHP, Python, Ruby, Java, and Node.js are
used for server-side scripting. They handle data processing,
database interactions, and business logic.
2. Web Servers:
o Web servers (e.g., Apache, Nginx) deliver web content to
users' browsers. They handle incoming requests, execute
server-side code, and send back responses.
3. Databases:
o Databases (e.g., MySQL, PostgreSQL, MongoDB) store
and manage structured data used by web applications. They
enable data persistence and retrieval.
4. Server-Side Frameworks:
o Frameworks such as Django (Python), Ruby on Rails
(Ruby), Express.js (Node.js), and Spring (Java) provide
tools and libraries to streamline back-end development.

Types of Websites:

1.E-commerce Websites:

Examples: Amazon, eBay, Etsy.

2. Social Media Websites:

Examples: Facebook, Twitter, Instagram, LinkedIn.

3. Informational Websites:

Examples: Wikipedia, news websites, educational websites.

4. Blog or Personal Websites:

Examples: Medium, WordPress blogs, personal portfolios.

5. Portfolio Websites:
Examples: Behance, Dribbble, photographer portfolios.

6. Educational Websites:

Examples: Coursera, Khan Academy, Udemy.

7. News and Media Websites:

Examples: BBC News, CNN, The New York Times.

8. Corporate or Business Websites:

Examples: Apple, Microsoft, IBM.

9. Nonprofit or Charity Websites:

Examples: UNICEF, Amnesty International, Red Cross.

10. Government Websites:

Examples: USA.gov, gov.uk, WhiteHouse.gov.

11. Entertainment Websites:

Examples: Netflix, Spotify, IGN, Buzzfeed.

12. Forum or Community Websites:

Purpose: Foster discussion and interaction among users on various


topics.

Web Standards and Protocols:

1. HTTP/HTTPS:
o HTTP (Hypertext Transfer Protocol) and HTTPS (Secure
HTTP) are protocols for transferring data between web
servers and browsers. HTTPS ensures secure
communication via encryption.
2. Web Standards:
o Standards like HTML5, CSS3, and ECMAScript
(JavaScript) are defined by organizations like the W3C
(World Wide Web Consortium) to ensure compatibility and
interoperability across different browsers and devices.

Conclusion : Understanding web technology involves mastering these


components and understanding how they work together to create
functional, secure, and user-friendly websites and web applications. As
technology evolves, staying updated with new tools, trends, and best
practices is essential for web developers and designers.
Experiment No:01
Aim : Design an html form for displaying information using
interactive css including images, tables.

Theory :
1. HTML Structure:
o Form Elements: Standard HTML elements such as

text inputs, email inputs, and file inputs.


o Images: Using the <img> tag to display images.

o Tables: Using <table>, <tr>, <th>, and <td> tags to

create a structured data presentation.

2. CSS Interactivity:
o Interactive CSS: Utilize CSS pseudo-classes (like

:hover, :focus) and other properties such as :checked


to create interactivity without JavaScript.
o Styling: Use CSS to enhance the visual design and

responsiveness of the form elements and other


content.
Implementation Plan
1. HTML Structure

The HTML form will include:


• Input fields for text and email.
• A file input to allow image upload.
• A table to display submitted information (without
dynamically updating it since JavaScript is not allowed).
2. CSS for Interactivity

CSS will be used to:


• Style the form and table.
• Implement hover and focus effects to improve user
interaction.
• Display a preview of the uploaded image using CSS tricks
(like :checked or CSS selectors).

Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Information Form</title>
<!-- Link to CSS -->
<link rel="stylesheet" href="styles.css">
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
padding: 20px;
}

.container {
max-width: 800px;
margin: auto;
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

h1, h2 {
text-align: center;
color: #333;
}

.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
color: #555;
}

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


width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
transition: border-color 0.3s;
}

input[type="text"]:focus, input[type="email"]:focus, input[type="file"]:focus {


border-color: #007bff;
}

button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}

button:hover {
background-color: #0056b3;
}

.image-display {
text-align: center;
margin-top: 20px;
}

#preview {
max-width: 100px;
margin-top: 10px;
display: none;
}

.preview-toggle {
display: inline-block;
padding: 10px;
background-color: #007bff;
color: white;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
margin-bottom: 10px;
}

.preview-toggle:hover {
background-color: #0056b3;
}

/* Show image when checkbox is checked */


#showPreview:checked ~ .image-display #preview {
display: inline-block;
}

.table-container {
margin-top: 30px;
}

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

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

th {
background-color: #007bff;
color: white;
}

td img.table-image {
width: 50px;
height: 50px;
border-radius: 50%;
}

</style>
</head>
<body>
<div class="container">
<h1>Interactive Information Form</h1>
<!-- Form Section -->
<form id="infoForm">
<!-- Text Input -->
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>

<!-- Email Input -->


<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>

<!-- Image Upload -->


<div class="form-group">
<label for="profilePic">Upload Profile Picture:</label>
<input type="file" id="profilePic" name="profilePic" accept="image/*">
</div>

<!-- Image Preview Check -->


<input type="checkbox" id="showPreview" hidden>

<!-- Submit Button -->


<div class="form-group">
<label for="showPreview" class="preview-toggle">Show Image Preview</label>
<button type="submit">Submit</button>
</div>
</form>

<!-- Image Display Section -->


<div class="image-display">
<h2>Profile Picture Preview:</h2>
<img id="preview" src="#" alt="Image Preview">
</div>

<!-- Table Display Section -->


<div class="table-container">
<h2>Submitted Information:</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Profile Picture</th>
</tr>
</thead>
<tbody>
<!-- Static row for demonstration -->
<tr>
<td>John Doe</td>
<td>john@example.com</td>
<td><img src="profile.jpg" alt="Profile Picture" class="table-image"></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

Explanation
1. HTML Structure:
o Form Elements: The form contains text input

(<input type="text">), email input (<input


type="email">), and file input (<input type="file">)
elements for data entry.
o Checkbox for Preview: A hidden checkbox (<input

type="checkbox" id="showPreview">) is used to


toggle the image preview without JavaScript.
o Image Display: The <img> tag is used to show the

image preview. By default, it is hidden using CSS


(display: none;).
o Table: A static table displays pre-filled data since

dynamically updating it without JavaScript is not


feasible.

2. CSS Styling and Interactivity:


o Form Inputs: Styled with padding, borders, and
transitions to make the elements more interactive
(e.g., changing border color on focus).
o Buttons: The submit button and toggle button
(.preview-toggle) have hover effects (:hover pseudo-
class) to enhance interactivity.
o Image Preview Toggle: The checkbox input
(#showPreview) is styled with a label (.preview-
toggle) to simulate a button. When checked, it shows
the image preview using the sibling combinator (~).

3. CSS Tricks:
o Image Preview without JavaScript: The checkbox

hack is used here. The image preview is controlled


by checking and unchecking the hidden checkbox.
This toggles the display property of the image
(#preview).

Output :
Conclusion :
By utilizing HTML and CSS creatively, we can design an
interactive form that allows users to input information, display
an image, and view data in a structured table format—all
without using JavaScript. The use of CSS pseudo-classes and
properties allows for basic interactivity and a visually
appealing user interface.
Experiment no :02
Aim : Create a webpage with HTML describing your
department with following specification:
a.Change the background color of the page. At the bottom
create a link to take user to the top of the page.
b. Insert an image and create a link such that clicking on image
takes user to other page.

c. Also apply font styling like italics, underline and two other
fonts to words you find appropriate. Also use header tags.

Theory :
Change the Background Color: We will set a background color
for the page using CSS.
Link to Top of the Page: Add a hyperlink at the bottom to allow
the user to scroll back to the top.
Clickable Image: Insert an image that, when clicked, redirects the
user to another page.
Font Styling: Use different font styles, such as italics, underline,
and different font families for specific text. Also, use header tags for
structuring content.

Program :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Overview</title>
<style>
/* Change background color */
body {
background-color: #e8f4f8;
font-family: Arial, sans-serif;
color: #333;
padding: 20px;
}

/* Styling for header tags */


h1, h2, h3 {
color: #005780;
}

/* Add some margin and padding to paragraphs */


p{
margin: 20px 0;
line-height: 1.6;
}

/* Styling for the image link */


.image-link {
display: block;
margin: 20px 0;
text-align: center;
}

/* Styling for the link at the bottom */


.top-link {
display: block;
margin-top: 50px;
text-align: center;
text-decoration: none;
color: #005780;
font-weight: bold;
}

.top-link:hover {
color: #00334d;
}

/* Style for italic, underline, and other font changes */


.italic {
font-style: italic;
}

.underline {
text-decoration: underline;
}

.font-change {
font-family: 'Courier New', Courier, monospace;
}
</style>
</head>
<body>

<!-- Page Title -->


<h1>Welcome to the information technology department </h1>

<!-- Introduction Section -->


<p class="italic">Our department is committed to excellence in teaching and research, and we aim to
prepare students for a successful career in the rapidly evolving field of computer science.</p>

<!-- Mission Section -->


<h2 class="underline">Our Mission</h2>
<p>The mission of the <span class="font-change">information technology department </span> is to
provide a comprehensive education that encompasses the theoretical foundations of computation as well as
the practical aspects of programming and system design.</p>

<!-- Image with link -->


<div class="image-link">
<a href="https://www.example.com" target="_blank">
<img src="department.jpg" alt="Computer Science Department" width="400">
</a>
<p>Click the image to visit our department's website.</p>
</div>

<!-- Research Section -->


<h2>Our Research</h2>
<p>Our faculty and students engage in cutting-edge research in areas such as artificial intelligence, data
science, cybersecurity, and software engineering. We encourage interdisciplinary collaboration and strive to
contribute to the advancement of technology and its applications.</p>

<!-- Courses Section -->


<h3 class="underline">Courses Offered</h3>
<p>We offer a range of undergraduate and graduate courses designed to equip students with the skills
needed to excel in the tech industry. From introductory programming to advanced topics in machine learning,
our curriculum is designed to be both challenging and rewarding.</p>

<!-- Link to Top of the Page -->


<a href="#top" class="top-link">Back to Top</a>

</body>
</html>
Explanation of the HTML Code :

1. Changing the Background Color:


o The <style> section contains CSS that sets the background-
color of the <body> to #e8f4f8, giving a light blue
background to the entire page.
2. Link to the Top of the Page:
o The link at the bottom (<a href="#top" class="top-
link">Back to Top</a>) uses an href attribute set to "#top".
This ID (#top) corresponds to the top of the page or the
<body> tag implicitly, allowing users to click this link to
return to the top.
3. Clickable Image:
o The <a> tag wrapping around the <img> tag creates a
clickable image. Clicking this image will take the user to
https://www.example.com. The target="_blank" attribute
ensures the link opens in a new tab.
4. Font Styling:
o Italics: The class .italic is applied to the first paragraph to
make its font italic.
o Underline: The class .underline is used on headings and text
to underline them.
o Font Change: The class .font-change is used on the word
"Computer Science Department" to change its font to
'Courier New'.
5. Header Tags:
o Various <h1>, <h2>, and <h3> tags are used to structure the
content hierarchically, enhancing readability and SEO.
Output:

Conclusion :
This HTML page is styled and structured to meet the
requirements using HTML and CSS. The use of different font
styles, background color, clickable image, and navigation links
provide a complete and interactive webpage.
Experiment No :03
Aim : Write a JavaScript to design a simple calculator to perform the
following operations: sum, product, difference and quotient.
Theory :
The document type (<!DOCTYPE html>) specifies that this is an HTML5
document.
The <html lang="en"> element specifies that the language of the content is
English.
The <head> section contains metadata about the document, such as character
set (UTF-8) and viewport settings for responsive design.
The <title> tag defines the title of the webpage as "Calculator".
<input type="text" id="text1" placeholder="Enter first number">: A text input
field where the user can enter the first number. The id attribute allows us to access
this element using JavaScript.
<select id="select"> ... </select>: A dropdown menu for selecting the
arithmetic operation (+, -, *).
<input type="text" id="text2" placeholder="Enter second number">: Another
text input field where the user can enter the second number.
<button onclick="ans()">ANS</button>: A button that triggers the ans()
function when clicked.
<input type="text" id="text3" readonly placeholder="Result">: A text input
field that displays the result. It is set to readonly so that users cannot modify its
content manually.

o Function ans(): This function is executed when the user clicks the
"ANS" button.
o Variable Initialization:
▪ var a = parseInt(document.getElementById("text1").value);:
▪ Retrieves the value entered in the first input field
(text1), converts it to an integer using parseInt, and
stores it in the variable a.
▪ var b = parseInt(document.getElementById("text2").value);:
▪ Retrieves the value entered in the second input field
(text2), converts it to an integer, and stores it in the
variable b.
▪ var opt = document.getElementById("select").value;:
Gets the selected operation (+, -, or *) from the

dropdown menu.
▪ var result=document.getElementById("text3").value;:
▪ Initializes the variable result with the current value of
the result input field (text3). However, this line is
unnecessary as it is immediately overwritten in the
subsequent code.
o Conditional Logic for Calculation:
▪ if (opt == "+"): Checks if the selected operation is addition.
▪ else if (opt == "-"): Checks if the selected operation is
subtraction.
▪ else if (opt == "*"): Checks if the selected operation is
multiplication.
▪ For each condition, it performs the corresponding arithmetic
operation and assigns the result to the result variable.
▪ If none of the conditions match, it sets the result to
"Something went wrong" (this should not normally happen
given the dropdown options).
o Display the Result:
▪ document.getElementById("text3").value = result;: Displays
the computed result in the text3 input field.

Program :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<input type="text" id="text1" placeholder="Enter first number"><br>
<select id="select">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
</select><br>
<input type="text" id="text2" placeholder="Enter second number"><br>
<button onclick="ans()">ANS</button><br>
<input type="text" id="text3" readonly placeholder="Result">
</body>
<script>
function ans(){
// Convert input values to numbers
var a = parseInt(document.getElementById("text1").value);
var b = parseInt(document.getElementById("text2").value);
var opt = document.getElementById("select").value;
var result=document.getElementById("text3").value;

if (opt == "+") {a
result = a + b;
} else if (opt == "-") {
result = a - b;
} else if (opt == "*") {
result = a * b;
} else {
result = "Something went wrong";
}

// Display the result in text3


document.getElementById("text3").value = result;
}
</script>
</html>

Output :
Conclusion : The HTML and JavaScript code provided creates a
simple calculator that can perform basic arithmetic operations:
addition, subtraction, and multiplication. The calculator takes two input
numbers from the user and an operation from a dropdown menu. When
the user clicks the "ANS" button, the JavaScript function ans() is
executed to perform the selected arithmetic operation and display the
result.
Experiment No :04
Aim : Write a JavaScript to validate the following fields of
employee on html form: email, name, mobile no., address, salary.

Theory :
1. HTML Form Structure:
o The form consists of input fields for Name, Email, Mobile
Number, Address, and Salary.
o Each input field is wrapped in a .form-group div, with an
accompanying <label> for accessibility.
o Each field has a corresponding <div> with the class="error" to
display validation error messages.
2. CSS Styles:
o Basic styling is provided to make the form look clean and readable.
o The. error class styles the error messages in red color and with a
smaller font size.
o The input fields and the submit button have padding and styling for
a better user experience.
3. JavaScript Validation (validate Form function):
o The function clears any previous error messages by setting the
inner text of all error <div> elements to an empty string.
o It then retrieves the values of each input field and trims any extra
whitespace.
o Each field is validated for:
▪ Name: Ensuring it is not empty.
▪ Email: Ensuring it is not empty and contains both '@' and '.'
characters.
▪ Mobile Number: Ensuring it is not empty, is exactly 10
digits, and contains only numbers.
▪ Address: Ensuring it is not empty.
▪ Salary: Ensuring it is not empty, is a number, and is greater
than 0.
o If any validation fails, an error message is displayed next to the
corresponding field and the function returns false to prevent form
submission.
o If all validations pass, the function returns true and the form is
submitted.
Program :
<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Form</title>
<style>
/* CSS styles for the form */
.form-group {
margin-bottom: 15px;
}

label {
display: block;
margin-bottom: 5px;
}

input[type="text"], textarea {
width: 100%;
padding: 8px;
box-sizing: border-box;
}

.error {
color: red;
font-size: 12px;
margin-top: 5px;
}

input[type="submit"] {
padding: 10px 15px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}

input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<form id="employeeForm" onsubmit="return validateForm()">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<div id="nameError" class="error"></div>
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<div id="emailError" class="error"></div>
</div>

<div class="form-group">
<label for="mobile">Mobile No.:</label>
<input type="text" id="mobile" name="mobile">
<div id="mobileError" class="error"></div>
</div>

<div class="form-group">
<label for="address">Address:</label>
<textarea id="address" name="address"></textarea>
<div id="addressError" class="error"></div>
</div>

<div class="form-group">
<label for="salary">Salary:</label>
<input type="text" id="salary" name="salary">
<div id="salaryError" class="error"></div>
</div>

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


</form>

<script>
function validateForm() {
// Clear previous errors
document.getElementById("nameError").innerText = "";
document.getElementById("emailError").innerText = "";
document.getElementById("mobileError").innerText = "";
document.getElementById("addressError").innerText = "";
document.getElementById("salaryError").innerText = "";

// Get form field values


var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var mobile = document.getElementById("mobile").value;
var address = document.getElementById("address").value;
var salary = document.getElementById("salary").value;
// Initialize validation status
var isValid = true;

// Name validation
if (name === "") {
document.getElementById("nameError").innerText = "Please enter your name.";
isValid = false;
}

// Email validation
if (email === "") {
document.getElementById("emailError").innerText = "Please enter your email.";
isValid = false;
} else if (!email.includes('@') || !email.includes('.')) {
document.getElementById("emailError").innerText = "Please enter a valid email address.";
isValid = false;
}

// Mobile number validation


if (mobile === "") {
document.getElementById("mobileError").innerText = "Please enter your mobile number.";
isValid = false;
} else if (mobile.length !== 10) {
document.getElementById("mobileError").innerText = "Please enter a valid 10-digit mobile
number.";
isValid = false;
}

// Address validation
if (address === "") {
document.getElementById("addressError").innerText = "Please enter your address.";
isValid = false;
}

// Salary validation
if (salary === "") {
document.getElementById("salaryError").innerText = "Please enter your salary.";
isValid = false;
} else if (parseFloat(salary) <= 0) {
document.getElementById("salaryError").innerText = "Please enter a valid salary.";
isValid = false;
}

return isValid;
}
</script>
</body>
</html>
Output :

Conclusion :
The provided HTML form and JavaScript validation script offer a straightforward
way to ensure that users enter valid data into each field before submitting the
form. By using simple checks for each input type—such as verifying the presence
of required fields, correct formatting for emails, appropriate number lengths for
mobile numbers, and valid numerical entries for salaries—this solution helps
prevent incorrect or incomplete submissions. The CSS adds basic styling for a
user-friendly interface and clear error messages. This approach improves the
overall user experience by guiding users to provide accurate and complete
information, reducing errors, and making the form more reliable.
Experiment No : 05
Aim : Develop and demonstrate a HTML file that includes JavaScript script that uses
functions for the following problems
Parameter: A string Output: Length of the String
Parameter: A number Output: The number with its digits in the reverse order

Theory :
Problem 1: Length of a String
Input:
The user provides a string input through an HTML input field (text box).
Process:
The length of a string refers to the number of characters it contains, including spaces and special
characters.
JavaScript provides the .length property, which returns the total count of characters in a string. This is
a simple and efficient way to find the length of any string.

Steps involved:

1. The input string is fetched using the document.getElementById() method.


2. The .length property of the string is used to calculate its length.
3. The result is dynamically updated and displayed on the webpage.

Problem 2: Reverse the Digits of a Number

Input:
The user provides a number input through an HTML number input field.
Process:
Reversing the digits of a number is not directly feasible since numbers do not have a built-in reverse
method in JavaScript. To reverse a number, we need to treat the number as a string, as strings can be
manipulated easily.

Steps involved:

1. Convert the number to a string using the value of the input field.
2. Use the split() function to convert the string into an array of individual digits.
3. Use the reverse() function to reverse the array.
4. Use the join() function to convert the reversed array back into a string.
5. Convert the string back to a number if required or display it directly.

Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String and Number Operations</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
padding: 20px;
}
.container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
margin-bottom: 20px;
}
input[type="text"], input[type="number"] {
width: 100%;
padding: 10px;
margin: 10px 0;
box-sizing: border-box;
}
button {
width: 100%;
padding: 10px;
background-color: #28a745;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
.output {
margin-top: 10px;
font-weight: bold;
}
</style>
</head>
<body>

<div class="container">
<h2>String Length</h2>
<input type="text" id="stringInput" placeholder="Enter a string">
<button onclick="calculateStringLength()">Get Length</button>
<div class="output" id="stringLengthOutput"></div>
</div>

<div class="container">
<h2>Reverse Number</h2>
<input type="number" id="numberInput" placeholder="Enter a number">
<button onclick="reverseNumber()">Reverse Digits</button>
<div class="output" id="numberReverseOutput"></div>
</div>

<script>
// Function to calculate the length of a string
function calculateStringLength() {
const inputString = document.getElementById('stringInput').value;
const length = inputString.length;
document.getElementById('stringLengthOutput').innerText = `Length: ${length}`;
}

// Function to reverse the digits of a number


function reverseNumber() {
const inputNumber = document.getElementById('numberInput').value;
const reversedNumber = inputNumber.split('').reverse().join('');
document.getElementById('numberReverseOutput').innerText = `Reversed: ${reversedNumber}`;
}
</script>

</body>
</html>

Output :
Conclusion: This HTML and JavaScript program successfully demonstrates two
essential JavaScript string and array manipulation techniques:

1. Calculating the length of a string using the. length property.


2. Reversing the digits of a number by treating the number as a string and applying
array manipulation methods.

Through user input and dynamic JavaScript functionality, this program shows the power of
JavaScript in building interactive web applications. It highlights the use of the DOM
(Document Object Model) to interact with HTML elements, retrieve user inputs, process
data, and display results dynamically.
Experiment no :06

Aim: Develop and demonstrate a HTML file that includes JavaScript for the following problems:
Input: A starting and ending number
Output: find all the prime numbers between starting and ending number.

Theory :
1. HTML Structure:
o The user enters a starting number and an ending number into two input boxes.
o There is a button that, when clicked, triggers the findPrimes() function.
2. JavaScript Logic:
o isPrime(n) function:
▪ This function checks if a number is prime. A prime number is a
number greater than 1 that can only be divided by 1 and itself.
▪ It loops from 2 up to the square root of the number (n). If any of these
numbers divide n evenly, it's not prime.
o findPrimes() function:
▪ This function gets the starting and ending numbers from the input
fields.
▪ It loops from the starting number to the ending number and uses the
isPrime(n) function to check if each number is prime.
▪ If a number is prime, it adds it to a list of primes.
▪ Finally, it shows the result on the page by updating the result div with
the list of primes or a message saying no primes were found.

Example:

If the user inputs:

• Start Number: 10
• End Number: 20

After clicking the "Find Prime Numbers" button, the output will be:

Prime numbers: 11, 13, 17, 19

Program:
<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

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

<title>Prime Numbers Finder</title>

</head>

<body>

<h2>Prime Numbers Finder</h2>

<label for="start">Start Number:</label>

<input type="number" id="start">

<br>

<label for="end">End Number:</label>

<input type="number" id="end">

<br>

<button onclick="findPrimes()">Find Prime Numbers</button>

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

<script>

function isPrime(n) {

if (n < 2) return false;

for (let i = 2; i <= Math.sqrt(n); i++) {

if (n % i === 0) return false;

return true;

function findPrimes() {

let start = parseInt(document.getElementById('start').value);

let end = parseInt(document.getElementById('end').value);

let result = document.getElementById('result');

let primes = [];

for (let i = start; i <= end; i++) {


if (isPrime(i)) primes.push(i);

result.innerHTML = "Prime numbers: " + primes.join(", ");

</script>

</body>

</html>

Output:

Conclusion:
This example demonstrates how to use basic HTML and JavaScript to solve the problem of
finding prime numbers in a given range. The code is simple and easy to understand:

• Input Validation: Ensures the user enters valid numbers (start should be smaller than
or equal to end, and both numbers must be positive).
• Prime Number Calculation: Efficiently finds primes using the fact that divisors of a
number only need to be checked up to its square root.
• Output: Clearly displays either the list of prime numbers or a message saying no
primes were found in the range.
Experiment no :07
Aim : Write a PHP program to display a digital clock which displays the current time of the
server.

1. PHP Basics: PHP is a server-side scripting language, which means the code runs on
the server and not in the user's browser.
2. Date and Time Functions in PHP: PHP has built-in functions to handle date and
time, such as date() and time(). We'll use these to get the current time.

Step-by-Step Explanation

1. Use of date() Function: PHP's date() function is used to format the date and time. You
can specify the format you want. For example:
o H for the hour (24-hour format)
o i for minutes
o s for seconds
2. HTML and CSS for Styling: We can use HTML to display the time and basic CSS
for styling to make the clock look digital.
3. Refreshing the Clock: To update the clock every second, we can use JavaScript to
refresh the displayed time dynamically without refreshing the page.

PHP Program to Display Digital Clock

Here’s a simple PHP program that displays the current server time:

Program:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Digital Clock</title>
<style>
.clock {
font-family: 'Courier New', Courier, monospace;
color: #333;
font-size: 50px;
text-align: center;
margin-top: 20%;
}
</style>
</head>
<body>

<div class="clock" id="clock">


<!-- PHP will display the time here -->
<?php
// Display current time in H:i:s format (Hours, Minutes, Seconds)
echo date("H:i:s");
?>
</div>

<script>
// JavaScript to refresh the time every second
setInterval(function() {
// Get the current time
var xhr = new XMLHttpRequest();
xhr.open('GET', 'time.php', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// Update the clock div with the new time
document.getElementById("clock").innerHTML = xhr.responseText;
}
};
xhr.send();
}, 1000);
</script>

</body>
</html>

Breakdown of Code

1. HTML Structure:
o We use a <div> element with the class clock to display the time.
o The id="clock" is used to update the clock every second using JavaScript.
2. PHP Script:
o The date() function is used to fetch the current time. We use the format "H:i:s"
which represents hours, minutes, and seconds in 24-hour format.
o This time is initially displayed on the page when it loads.
3. CSS Styling:
o Basic styling is applied to make the clock text look bigger and centered.
4. JavaScript:
o The setInterval() function is used to execute a piece of code every 1000
milliseconds (1 second). This function sends an asynchronous request to the
server to get the updated time.
o The XMLHttpRequest object is used to send an HTTP request to a separate PHP
file (time.php) that will return the current time without refreshing the page.

Create a time.php file

The time.php file only contains the PHP code that returns the current time, and it will be
requested every second by the JavaScript code in the main file:

<?php
// Return the current time in H:i:s format
echo date("H:i:s");
?>

How This Works

1. When the page is loaded, the initial server time is shown in the clock.
2. Every second, the JavaScript sends a request to time.php to get the updated time and
refresh the clock display.
3. The PHP code ensures that the time is always based on the server's local time, so it
will not depend on the user's local time.

Conclusion : PHP fetches the server time using the date() function.

JavaScript ensures the time is updated every second by fetching new data from the server
using AJAX.
This is a simple, real-time digital clock using a combination of PHP and JavaScript.
Experiment No: 08
Aim : Write a PHP program to implement sign-In and Sign-out functionality.
1. Theory : Session Management: In PHP, sessions are used to store user
information across multiple pages. We use sessions to remember if a user is signed in
or not.
2. Sign-In: A user provides their credentials (username and password), which are
checked against predefined values (or values from a database). If the credentials
match, the user is signed in, and the session is created.
3. Sign-Out: When the user clicks sign-out, the session is destroyed, logging the user
out.
4. Security Note: In real-world applications, passwords should be hashed, and more
advanced authentication techniques should be used (e.g., database authentication). For
simplicity, this example uses hardcoded values.

<?php
// Start the session
session_start();

// Check if the user is already signed in


if (isset($_SESSION['username'])) {
// If signed in, redirect to the welcome page
header('Location: welcome.php');
exit();
}

// If form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Hardcoded credentials (for demonstration purposes)
$valid_username = 'student';
$valid_password = 'password123';

// Retrieve the entered username and password


$username = $_POST['username'];
$password = $_POST['password'];

// Validate the credentials


if ($username == $valid_username && $password == $valid_password) {
// If credentials are correct, create a session and redirect to the welcome page
$_SESSION['username'] = $username;
header('Location: welcome.php');
exit();
} else {
// If credentials are incorrect, show an error message
$error = "Invalid username or password";
}
}
?>

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

<h2>Sign-In</h2>

<?php
// Display the error message if credentials are incorrect
if (isset($error)) {
echo "<p style='color:red;'>$error</p>";
}
?>

<form method="POST" action="">


<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br><br>

<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>

<button type="submit">Sign In</button>


</form>

</body>
</html>

<?php
// Start the session
session_start();

// Check if the user is signed in


if (!isset($_SESSION['username'])) {
// If not signed in, redirect to the sign-in page
header('Location: signin.php');
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>

<h2>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!</h2>

<p>You have successfully signed in.</p>

<!-- Sign out link -->


<form method="POST" action="signout.php">
<button type="submit">Sign Out</button>
</form>

</body>
</html>

<?php
// Start the session
session_start();

// Destroy the session (log the user out)


session_destroy();

// Redirect to the sign-in page


header('Location: signin.php');
exit();
?>

Explanation of the Code

1. Session Management:
o session_start(): This function is used to start the session. Sessions allow us to
store information (like the username) across different pages.
o Sign-In Flow:
▪ When the user submits the form, the script checks the entered
username and password against the hardcoded credentials.
▪ If they match, the user is signed in by storing their username in the
session ($_SESSION['username']), and they are redirected to the welcome
page.
o Sign-Out Flow:
▪ When the user clicks "Sign Out", the session is destroyed using
session_destroy(), and they are redirected back to the sign-in page.
2. HTML Forms:
o The sign-in form collects the username and password.
o When the form is submitted, it triggers a POST request to the same page, where
PHP processes the form data.
3. Redirection:
o If the user is already signed in, they are automatically redirected to the
welcome.php page.
o If a non-signed-in user tries to access the welcome.php page, they are redirected
back to the signin.php page.
4. Security Notes:
o The passwords should not be stored as plain text in a real-world application.
They should be hashed before storing in the database using password_hash() and
verified using password_verify().
o The session should be managed carefully to prevent attacks like Session
Hijacking.

Output :
When the user accesses the sign-in page (signin.php), they will see a simple form:

Conclusion :
This PHP program demonstrates a simple Sign-In and Sign-Out process using sessions. It
includes the following steps:

1. User submits their username and password.


2. PHP validates the credentials and starts a session for authenticated users.
3. The user is redirected to a welcome page upon successful sign-in.
4. Clicking "Sign Out" destroys the session and redirects the user back to the sign-in
page.
Experiment No :09
Aim : Write a PHP program to keep track of the number of visitors visiting the Web page and to
display this count of visitors, with proper headings.

Theory :
File Handling in PHP: PHP provides functions for file operations such as reading from
and writing to files. We'll use these functions to store and update the visitor count.
Visitor Count: Every time someone visits the webpage, the PHP script will read the
current visitor count from a file, increase it by one, and save the updated count back to the
file.
Displaying the Count: The updated visitor count will be displayed on the webpage.

Program :
<?php

// Define the file that will store the visitor count


$file = "counter.txt";

// Check if the file exists


if (file_exists($file)) {
// Read the current count from the file
$visitor_count = file_get_contents($file);
// Increment the count by 1
$visitor_count++;
} else {
// If the file doesn't exist, start the count at 1
$visitor_count = 1;
}

// Write the updated count back to the file


file_put_contents($file, $visitor_count);

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visitor Counter</title>
</head>
<body>
<h1>Welcome to Our Website</h1>
<p>This page has been visited <strong><?php echo $visitor_count; ?></strong> times.</p>

</body>
</html>

Explanation of the Code

1. File Handling:
o file_exists($file): This
function checks if the file (counter.txt) exists. If it exists, we
read the current visitor count from the file.
o file_get_contents($file): This function reads the content of the file. In our case, it
retrieves the current visitor count stored in the counter.txt file.
o Increment the Visitor Count: Each time the page is loaded, we increase the
visitor count by 1.
o file_put_contents($file, $visitor_count): This function writes the updated visitor
count back to the counter.txt file, ensuring that the count persists across page
reloads.
2. Displaying the Count:
o The updated visitor count is displayed in the <p> tag using PHP's echo
statement (<?php echo $visitor_count; ?>).
3. Creating the Counter File:
o When the program is run for the first time, if the file counter.txt does not exist, it
will be created, and the visitor count will start at 1.
4. Page Layout:
o The webpage displays a simple message: "This page has been visited X
times," where X is the current visitor count.

Output :
How It Works

1. First Visit:
o If this is the first time someone is visiting the page, the file counter.txt will not
exist. The script will create the file and initialize the visitor count to 1.
2. Subsequent Visits:
o For every subsequent visit or refresh, the script reads the current count from
counter.txt, increments it by 1, and writes the updated count back to the file.
3. Persistent Storage:
o The visitor count is stored in the file (counter.txt), ensuring that even if the
server is restarted or the page is closed, the count is maintained and updated
across visits.

Conclusion :
PHP File Handling: We used PHP’s file handling functions (file_exists(), file_get_contents(),
and file_put_contents()) to store and update the visitor count.
Visitor Tracking: Every time the webpage is visited, the script updates the visitor count
by reading from and writing to a file.
Simple and Efficient: This method is simple and efficient for tracking visitors in small-
scale applications.
Experiment No :10
Aim : Write a PHP code to implement AJAX functionality.
Introduction to AJAX

AJAX (Asynchronous JavaScript and XML) allows web pages to be updated asynchronously
by exchanging data with the server in the background. This means that parts of a web page
can be updated without reloading the entire page.

In PHP, we use AJAX to send a request to the server (PHP script) and get a response back, all
without refreshing the webpage.

Concept and Explanation

1. AJAX Workflow:
o A JavaScript function sends a request to the server using the XMLHttpRequest
object (or fetch API in modern JavaScript).
o The server processes this request (in our case, using PHP) and sends back a
response.
o JavaScript updates the page with the new data without refreshing the entire
page.
2. Use Case Example:
o We’ll build a simple example where a user clicks a button, and AJAX fetches
the current time from the server using PHP. The result will be displayed on the
webpage without reloading it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX with PHP</title>
<script>
function loadServerTime() {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configure it: GET-request for 'time.php'


xhr.open('GET', 'time.php', true);

// Set up the callback for when the request is complete


xhr.onreadystatechange = function() {
// If the request is completed and was successful
if (xhr.readyState == 4 && xhr.status == 200) {
// Update the content of the div with id "result" with the server response
document.getElementById('result').innerHTML = xhr.responseText;
}
};

// Send the request to the server


xhr.send();
}
</script>
</head>
<body>

<h1>AJAX Example with PHP</h1>

<!-- Button to trigger AJAX request -->


<button onclick="loadServerTime()">Get Server Time</button>

<!-- Div to display the result from the server -->


<p>Server Time: <span id="result">Click the button to see the time</span></p>

</body>
</html>

<?php
// Get the current server time
$time = date('H:i:s');

// Send the time back as the response


echo "The current server time is: " . $time;
?>

Explanation of the Code

1. AJAX (JavaScript):

• XMLHttpRequest(): This is a built-in JavaScript object used to send and receive data from the
server asynchronously.
• xhr.open('GET', 'time.php', true): This function sets up the request to the server. We are using
the GET method to request data from time.php asynchronously (true).
• xhr.onreadystatechange: This event handler is called whenever the state of the request
changes. When the request is complete (readyState == 4) and successful (status == 200), the
response from the server is processed.
• xhr.responseText: This contains the data (the current time) returned by the server (the PHP
script).
• document.getElementById('result').innerHTML = xhr.responseText;: This updates the content
inside the <span> element with the ID result to display the server's response.

2. PHP Script (time.php):

• date('H:i:s'): This PHP function retrieves the current server time in the format
hours:minutes:seconds.
• The time is then sent back to the client (JavaScript) as a response using echo.

3. HTML:

• A simple button triggers the JavaScript function loadServerTime() when clicked.


• The result of the AJAX request is displayed inside the <span> element with the ID result.

How It Works

1. The user loads the HTML page with a button labeled "Get Server Time."
2. When the user clicks the button, JavaScript sends an AJAX request to time.php.
3. time.php returns the current server time as a string.
4. The JavaScript code receives the response and updates the <span id="result"> element to
display the current time without reloading the page.

Output :

Conclusion :
AJAX allows us to send requests to the server and update parts of a web page without
reloading the whole page.
In this example, we used a simple AJAX call to get the current time from the server using
a PHP script.
AJAX Workflow:

1. JavaScript sends a request to time.php using XMLHttpRequest.


2. PHP processes the request and sends back the current server time.
3. JavaScript receives the response and updates the webpage.

You might also like