Web Technology LAB MANUAL for Undergraduate Programs

512 views 47 slides May 28, 2024
Slide 1
Slide 1 of 47
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47

About This Presentation

Web Technology LAB MANUAL for Undergraduate Programs


Slide Content

1 | P a g e



Course: Seminar- II
WEB TECHNOLOGIES
LABORATORY MANUAL B.TECH
(II YEAR – IV SEM) (2023-2024)





DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING

Mr. Chandrakant Pandurang Divate
Sanjay Bhokare Group Of Institutes Miraj
(NAAC-A Grade Accredited Institution)

(Affiliated to Dr. Babasaheb Ambedkar Technological University, Lonere, Approved by AICTE - Accredited NAAC – ‘A’)
Tilak Nagar, Miraj-Sangli Road, Post-Wanlesswadi, Miraj, Dist: Sangli - Pin-416410. (Maharashtra State), India

2 | P a g e
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Vision
 To be a well-known and reputed Computer Science and
Engineering department to import technical and moral quality
education.

Mission
 To prepare students with globally competent professionals by
providing academic excellence and human core values.

Program Educational Objectives (PEOs)
PEO1: To provide knowledge of sound mathematical principles underlying various
programming concepts.

PEO2: To develop an ability to understand complex issues in the analysis, design,
implementation and operation of information systems.

PEO3: To provide knowledge of mechanisms for building large-scale computer-based
systems.

PEO4: To develop an ability to provide computer-based solutions to the problems from
other disciplines of science and engineering.

PEO5: To impart skills necessary for adapting rapid changes taking place in the field of
information and communication technologies.

PEO6: To provide knowledge of ethical issues arising due to deployment of information
and communication technologies in the society on large scale.

3 | P a g e
Program Specific Outcomes (PSOs)
PSO1- Proficiency in Hardware and Software Design: Graduates will be proficient in
designing both hardware (like computer chips and circuits) and software (like
computer programs and applications), enabling them to develop integrated
computer systems effectively.

PSO2-Problem-solving Skills in Computer Systems: Graduates will have the ability to
identify, analyze, and solve problems related to computer systems, including
troubleshooting hardware issues, debugging software code, and optimizing system
performance.

PSO3- Effective Communication and Collaboration: Graduates will possess strong
communication skills and the ability to collaborate effectively in multidisciplinary
teams, enabling them to work efficiently on complex computer engineering projects
and effectively communicate their ideas to colleagues and stakeholders.
Program Outcomes (POs): Engineering Graduates will be able to:
1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem Analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

3. Design / Development Of Solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.

4. Conduct Investigation of Complex Problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.

4 | P a g e
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.

7. Environment and Sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.

9. Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.

11. Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary environments.

12. Life-Long Learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

Course Outcomes: Upon successful completion of this course, the students will be able to,
CO1: Students learn web design basics, HTML, and how to create web pages with
hyperlinks, tables, forms, images, and metadata.
CO2: Students master CSS for styling web pages, including text, tables, and
embedded/external style sheets.
CO3: Students are introduced to JavaScript, focusing on variables, operators, strings, arrays,
and basic programming concepts.
CO4: Students explore PHP for form handling, data processing, and session management to
create dynamic web applications.
CO5: Students learn jQuery for web interactivity, AJAX for dynamic updates, and MySQL
for database operations.

5 | P a g e
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab
with the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will
attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out, if
anybody found loitering outside the lab / class without permission during working hours
will be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system /
seat is kept properly.


Subject Teacher Head of the Department

1 | P a g e
INDEX
Sr. No. List of programs
Pg.
No.
Remark
1
Design an html form for displaying information using interactive
css including images, tables.
02
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.
08
3
Write a JavaScript to design a simple calculator to perform the
following operations: sum, product, difference and quotient.
12
4
Write a JavaScript to validate the following fields of employee on
html form: email, name, mobile no., address, salary.
16
5
Develop and demonstrate a HTML file that includes JavaScript
script that uses functions for the following problems:
a) Parameter: A string Output: Length of the String
b) Parameter: A number
Output: The number with its digits in the reverse order
19
6
Develop and demonstrate a HTML file that includes JavaScript
for the following problems:
a) Input: A starting and ending number
b) Output: find all the prime numbers between starting and
ending number.
22
7
Write a PHP program to display a digital clock which displays the
current time of the server.
25
8
Write a PHP program to implement sign-In and Sign-out
functionality.
27
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.
31
10 Write a PHP code to implement AJAX functionality. 33
11
Write a PHP program to perform search operation on the student
records using AJAX.
36
12
Write a PHP program to sort the student records which are stored
in the database using ascending/descending order.
39

2 | P a g e
Experiment No. - 01
Experiment Title:
Design an HTML Form for Displaying Information Using Interactive CSS, Including Images,
and Tables

Aim:
To design and develop a web page using HTML and CSS that includes a form to display
information interactively, with the inclusion of images and tables for a comprehensive user
experience.

Objective:
 To understand the use of basic HTML tags and elements.
 To learn the application of CSS for styling HTML forms.
 To practice creating and styling tables and inserting images.

Learning Outcome:
Students will be able to create a well-structured HTML form and apply CSS to enhance its
presentation, including the display of user information in tables and the insertion of images.
Description:
This experiment involves creating a web page with an HTML form that includes input
elements such as text fields, radio buttons, and checkboxes. The form will be styled using CSS
to enhance its appearance and interactivity. Additionally, images and tables will be
incorporated into the form to display information clearly and attractively.

Stepwise Modules:
Module 1: Setting Up the HTML Structure
 Create a new HTML file.
 Define the basic structure using <html>, <head>, and <body> tags.
 Add a <title> to your web page.
Module 2: Creating the HTML Form
 Inside the <body> tag, create a <form> element.
 Add various input elements within the form:
 Text fields
 Radio buttons
 Checkboxes
 Submit button
Module 3: Incorporating Images
 Use the <img> tag to insert images within the form or elsewhere on the page.

3 | P a g e
 Ensure images are properly formatted and accessible.
Module 4: Adding Tables
 Use the <table> tag to create a table.
 Add <tr>, <th>, and <td> tags to structure your table rows and data.
Module 5: Styling with CSS
 Create a new CSS file or add a <style> block within the <head> tag.
 Apply styles to form elements, images, and tables to enhance their appearance.
 Use CSS selectors to target specific elements.
 Experiment with properties like border, padding, margin, font-family, color, and
background.
Example:
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration Form</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h2>User Registration Form</h2>
<form id="registrationForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

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

<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>
<label for="profilePicture">Profile Picture:</label>

4 | P a g e
<input type="file" id="profilePicture" name="profilePicture" accept="image/*" required> <button
type="submit">Register</button>
</form>
</div>

<!-- Displaying User Information -->
<div id="userInfo" class="user-info">
<h3>User Information</h3>
<table id="userTable">
<tr>
<th>Name</th>
<th>Email</th>
<th>Gender</th>
<th>Date of Birth</th>
<th>Profile Picture</th>
</tr>
<tr>
<td>Chandrakant Divate</td>
<td> chandrakant.divate @gmail.com</td>
<td>Male</td>
<td>8446629909</td>
<td><img src="profile-placeholder.png" alt="Profile Picture" style="width:50px;
height:50px;"></td>
</tr>
</table>
</div>
</body>
</html>

CSS Code:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 100vh;
margin: 0;
}
.container {
background-color: white;
padding: 20px;
border-radius: 5px;

5 | P a g e
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h2 {
margin-bottom: 20px;
}

form label {
display: block;
margin-top: 10px;
}

form input, form select, form button {
width: 100%;
padding: 10px;
margin-top: 5px;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 5px;
}

form button {
background-color: #5cb85c;
color: white;
border: none;
cursor: pointer;
}

form button:hover {
background-color: #4cae4c;
}

.user-info {
margin-top: 20px;
}

table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 10px;
text-align: left;

6 | P a g e
}

th {
background-color: #f2f2f2;
}


Example Output:
When the HTML and CSS code is executed, the output should display an interactive form
where users can enter their information. The page will also display an image and a table
summarizing the user's input.



Conclusion:
In this experiment, students successfully created a web page with an interactive form using
HTML and CSS. They learned how to integrate images and tables within a form and style
these elements to enhance the web page's usability and aesthetic appeal. The experiment
demonstrated the importance of combining HTML structure with CSS styling to create
functional and visually appealing web pages.

Problem Statements:
1) Product Feedback Form
 Create a form with fields for name, email, product ID, rating (radio buttons), and

7 | P a g e
comments.
 Style the form and display submitted feedback in a table.

2) Event Registration Form
 Design a form with fields for name, email, phone number, event selection
(checkboxes), and profile picture.
 Apply CSS to match the event theme and display participant information in a table.

3) Job Application Form
 Develop a form with fields for name, email, phone number, job position (dropdown),
resume upload, and cover letter.
 Style the form professionally and summarize applicant details in a table.

4) Student Information Form
 Create a form with fields for name, class, roll number, gender, date of birth, and profile
picture.
 Apply CSS to make the form engaging.
 Display student information in a table.

5) Reservation Form
 Design a form with fields for name, contact number, reservation date and time, number
of guests, and special requests.
 Style the form to be visually appealing.
 Display reservation details in a table.

6) Volunteer Signup Form
 Create a form with fields for name, email, phone number, areas of interest
(checkboxes), and availability.
 Apply CSS to make the form attractive.
 Display volunteer details in a table.

7) Contact Us Form
 Create a form with fields for name, email, phone number, and message.
 Include the company logo and use CSS for form alignment and accessibility.
 Display contact information in a table.

8 | P a g e
Experiment No. - 02
Experiment Title:
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.
Aim
To design a webpage that describes the department, incorporates background color, links,
images, and font styling using HTML and CSS.

Objective
 To learn how to change the background color of a webpage.
 To practice creating internal and external links.
 To insert and link images.
 To apply various font styles and header tags.

Outcome
Students will be able to create a visually appealing and interactive webpage that describes
their department, utilizing HTML for structure and CSS for styling.

Description
This experiment involves creating a descriptive webpage for a department. The webpage
will include a colored background, an image that links to another page, text with various
font styles, and a link to navigate to the top of the page. Header tags will also be used to
organize the content.

Modules
Modules-1: Setup the HTML Structure
Create the basic structure of the HTML document with <!DOCTYPE html>,
<html>, <head>, and <body> tags.
Modules-2: Change Background Color
Use CSS to set the background color of the webpage.
Modules-3: Insert and Link Image
Add an image to the webpage and create a link that redirects to another page

9 | P a g e
when the image is clicked.
Modules-4: Apply Font Styling
Use CSS to apply italics, underline, and different fonts to appropriate words or
phrases.
Modules-5: Create Navigation Links
Add a link at the bottom of the page that takes the user to the top of the page.

Example
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department of Computer Engineering</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Department of Computer Engineering</h1>
</header>
<section>
<h2>Welcome to Our Department</h2>
<p>The <span class="italic">Department of Computer Engineering</span> at our
college offers comprehensive education and research opportunities in the field of
computer science and engineering.</p>

<h3>Our Vision</h3>
<p><u>Empowering students</u> with <span class="font-change">cutting-
edge</span> technology and innovation.</p>
<h3>Our Mission</h3>
<p>We aim to provide <span class="font-change">high-quality education</span>
and foster research to solve <u>complex engineering problems</u>.</p>
<h3>Contact Us</h3>
<p>Email: <a href= "mailto:[email protected]">[email protected]
</a> </p>
<p>Phone: +123 456 7890</p>
<h3>Visit Our Lab</h3>
<a href="lab.html"><img src="lab.jpg" alt="Computer Engineering Lab" style=
"width:300px; height:200px;"> </a>

<footer>
<p><a href="#top">Back to Top</a></p>
</footer>
</section>
</body>
</html>

10 | P a g e
CSS Code (styles.css)
body {
font-family: Arial, sans-serif;
background-color: #e0f7fa;
margin: 0;
padding: 20px;
}

header {
text-align: center;
margin-bottom: 20px;
}

h1 {
font-size: 2.5em;
}

h2, h3 {
color: #00796b;
}

p {
line-height: 1.6;
}

.italic {
font-style: italic;
}

.u {
text-decoration: underline;
}

.font-change {
font-family: 'Georgia', serif;
color: #3e2723;
}

footer {
margin-top: 20px;
text-align: center;
}

footer a {
color: #004d40;
text-decoration: none;
}

footer a:hover {
text-decoration: underline;
}

11 | P a g e
Output:


Conclusion
By completing this experiment, students will learn to create a structured and styled
webpage that includes text, images, and links. They will gain practical experience in using
HTML for content structure and CSS for styling.

Problem Statements
1) Department Overview Page: Create a webpage that provides an overview of your
department, including its history, mission, and vision. Use background colors, images,
and links appropriately.

2) Faculty Information Page: Design a webpage that lists the faculty members of your
department, with their photos, designations, and contact details. Ensure the page is well-
organized using header tags and styled with CSS.

3) Course Information Page: Create a webpage that details the courses offered by your
department. Include course descriptions, prerequisites, and links to detailed course
pages. Use tables to organize the information and apply CSS for styling.

4) Student Achievements Page: Develop a webpage that highlights the achievements of
students from your department, such as awards, projects, and internships. Include
images and links to relevant pages or documents.

5) Research and Publications Page: Design a webpage that showcases the research work
and publications from your department. Include links to research papers, project details,
and images of research activities.

12 | P a g e
Experiment No. - 03
Experiment:
Write a JavaScript to Design a Simple Calculator to Perform Sum, Product, Difference, and
Quotient

Aim:
To design a simple calculator using JavaScript that can perform basic arithmetic operations
such as addition, multiplication, subtraction, and division.

Objective:
 To understand the use of JavaScript for performing arithmetic operations.
 To create an interactive web application that takes user input and processes it using
JavaScript.

Outcome:
By the end of this experiment, students will be able to:
 Use HTML to create a form for input.
 Use JavaScript to capture user input and perform arithmetic operations.
 Display the results dynamically on a web page.

Description:
In this experiment, you will create a simple web-based calculator. The calculator will take
two numbers as input and perform the following operations: sum, product, difference, and
quotient. The results will be displayed to the user on the same page.

Modules:
Modules-1: HTML Form Creation:
 Create an HTML form to take two input numbers.
 Add buttons for each arithmetic operation.
Modules-2: JavaScript Functions:
 Write JavaScript functions to perform the arithmetic operations.
 Capture the input values and display the results.
Modules-3: Integration:
 Integrate the JavaScript functions with the HTML form.
 Ensure the results are displayed dynamically on the page.

Example Code:
<!DOCTYPE html>

13 | P a g e
<html>
<head>
<title>Simple Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}
.calculator {
max-width: 300px;
margin: auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
}
input[type="number"] {
width: 100%;
padding: 10px;
margin: 5px 0;
box-sizing: border-box;
}
button {
width: 48%;
padding: 10px;
margin: 5px 1%;
box-sizing: border-box;
}
.result {
margin-top: 20px;
font-weight: bold;
}
</style>
</head>
<body>

<div class="calculator">
<h2>Simple Calculator</h2>
<form id="calcForm">
<input type="number" id="num1" placeholder="Enter first number" required>
<input type="number" id="num2" placeholder="Enter second number" required>
<button type="button" onclick="calculateSum()">Sum</button>
<button type="button" onclick="calculateDifference()">Difference</button>
<button type="button" onclick="calculateProduct()">Product</button>
<button type="button" onclick="calculateQuotient()">Quotient</button>
</form>
<div id="result" class="result"></div>
</div>

<script>
function getNumbers() {
const num1 = parseFloat(document.getElementById('num1').value);
const num2 = parseFloat(document.getElementById('num2').value);
return { num1, num2 };
}
function calculateSum() {
const { num1, num2 } = getNumbers();
const result = num1 + num2;

14 | P a g e
document.getElementById('result').innerText = 'Sum: ' + result;
}

function calculateDifference() {
const { num1, num2 } = getNumbers();
const result = num1 - num2;
document.getElementById('result').innerText = 'Difference: ' + result;
}

function calculateProduct() {
const { num1, num2 } = getNumbers();
const result = num1 * num2;
document.getElementById('result').innerText = 'Product: ' + result;
}

function calculateQuotient() {
const { num1, num2 } = getNumbers();
if (num2 === 0) {
document.getElementById('result').innerText = 'Error: Division by zero';
return;
}
const result = num1 / num2;
document.getElementById('result').innerText = 'Quotient: ' + result;
}
</script>

</body>
</html>

Example Output:
 The user enters two numbers in the input fields.
 The user clicks on one of the buttons (Sum, Difference, Product, Quotient).
 The result of the selected operation is displayed dynamically below the buttons.


Conclusion:
In this experiment, we successfully created a simple web-based calculator using HTML and

15 | P a g e
JavaScript. The calculator can perform basic arithmetic operations and dynamically display
the results. This exercise helped us understand the integration of HTML forms with
JavaScript functions to create interactive web applications.

Examples to be solved:
1. Design a JavaScript Function to Validate a Contact Form: Write a JavaScript function
that validates a contact form. The form should include fields for name, email, phone
number, and message. Ensure that the name is not empty, the email is in a valid format, the
phone number is numeric and 10 digits long, and the message is not empty. Provide
appropriate error messages for each validation failure.
2. Create a JavaScript Countdown Timer: Design a countdown timer using JavaScript. The
timer should take an input value in seconds from the user and display the countdown in the
format MM:SS. Once the timer reaches zero, display an alert saying "Time's up!" Ensure
that the timer can be paused and reset.
3. Create an Image Slider Using JavaScript: Write a JavaScript function to create an image
slider. The slider should automatically transition between images every few seconds and
also provide next and previous buttons to manually navigate through the images. Include a
caption for each image that changes with the slide.
4. Create a JavaScript Tip Calculator: Design a simple tip calculator using JavaScript. The
calculator should take the total bill amount and the desired tip percentage as input and then
calculate the total amount including the tip. It should also display the tip amount
separately. Include a dropdown menu for tip percentage options (e.g., 10%, 15%, 20%) and
an input field for the bill amount.
5. Develop a JavaScript Function for Dynamic Image Gallery: Write a JavaScript function
to create a dynamic image gallery. The gallery should allow users to upload images,
display them in a grid format, and remove images when clicked. Ensure that the uploaded
images are displayed with appropriate styling and that the layout adjusts based on the
number of images.

Instructions for Students:
For each problem statement, students should:
 Design the HTML structure to support the functionality described.
 Write the necessary JavaScript code to implement the functionality.
 Test the solution to ensure it works as expected.
 Comment the code to explain key sections and logic used.

16 | P a g e
Experiment No. - 04
Experiment Title:
JavaScript Form Validation for Employee Details

Aim:
To design a JavaScript function that validates the input fields for employee details on an
HTML form.

Objective:
Validate the email field to ensure it is in the correct format.
 Validate the name field to ensure it is not empty.
 Validate the mobile number field to ensure it is numeric and 10 digits long.
 Validate the address field to ensure it is not empty.
 Validate the salary field to ensure it is a positive numeric value.

Outcome:
After completing this experiment, students should be able to create a JavaScript function that
performs validation checks on specified fields in an HTML form for employee details.

Description:
In this experiment, we will create an HTML form for entering employee details. The form will
include fields for email, name, mobile number, address, and salary. We will then write a
JavaScript function to validate each of these fields based on the specified criteria.

Modules:
 Design the HTML form with input fields for email, name, mobile number, address, and
salary.
 Write the JavaScript function to perform validation checks on each field.
 Use regular expressions to validate the email format and mobile number.
 Display appropriate error messages if any field fails validation.
 Test the form by entering different values and verify that the validation works as
expected.

Example:
<form id="employeeForm" onsubmit="return validateForm()">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>

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

17 | P a g e

<label for="mobile">Mobile Number:</label>
<input type="tel" id="mobile" name="mobile" pattern="[0-9]{10}" required><br>

<label for="address">Address:</label>
<textarea id="address" name="address" required></textarea><br>

<label for="salary">Salary:</label>
<input type="number" id="salary" name="salary" min="0" required><br>

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

<script>
function validateForm() {
var email = document.getElementById('email').value;
var name = document.getElementById('name').value;
var mobile = document.getElementById('mobile').value;
var address = document.getElementById('address').value;
var salary = document.getElementById('salary').value;

var emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var mobileRegex = /^[0-9]{10}$/;

if (!emailRegex.test(email)) {
alert("Please enter a valid email address.");
return false;
}
if (name === '') {
alert("Please enter your name.");
return false;
}
if (!mobileRegex.test(mobile)) {
alert("Please enter a valid 10-digit mobile number.");
return false;
}
if (address === '') {
alert("Please enter your address.");
return false;
}
if (salary <= 0) {
alert("Please enter a valid salary amount.");
return false;
}

return true; // Form submission allowed if all validations pass
}
</script>

Output:
Upon submitting the form, the JavaScript function validateForm() will validate the fields for
email, name, mobile number, address, and salary. If any field fails validation, an appropriate
error message will be displayed, and the form submission will be prevented until the errors
are corrected.

18 | P a g e


Conclusion:
By completing this experiment, students will gain hands-on experience in designing a
JavaScript function to validate input fields in an HTML form, improving their skills in form
validation and user input handling.

Problems Statements:
1. Password Strength Checker: Create a JavaScript function that checks the strength of a
password entered by the user in a form. Define criteria for a strong password (e.g., minimum
length, inclusion of uppercase letters, numbers, and special characters) and provide feedback
to the user indicating whether their password meets the criteria.
2. Date Validation: Design a JavaScript function to validate a date entered in a form. Check if
the date is in a valid format (e.g., MM/DD/YYYY) and falls within a specified range (e.g.,
current year +/- 10 years). Display an error message if the date is invalid.
3. Numeric Input Validation: Write a JavaScript function to validate numeric input fields in a
form. Ensure that the input is a valid number and falls within a specified range (e.g.,
between 0 and 100). Display appropriate error messages if the input is invalid.
4. File Upload Validation: Implement JavaScript validation for a file upload form field. Check
the file type (e.g., allow only images or PDF files), size limits, and ensure that at least one
file is selected before submission. Display error messages for invalid file selections.
5. Conditional Validation: Create a JavaScript function that performs conditional validation
based on user selections in a form. For example, if a user selects a specific option from a
dropdown menu, certain fields become required or optional. Implement this dynamic
validation logic using JavaScript.

19 | P a g e
Experiment No. - 05
Experiment:
JavaScript Functions for String Length and Number Reversal

Aim:
To develop and demonstrate a HTML file that includes JavaScript functions for
determining the length of a string and reversing the digits of a number.

Objective:
 To understand the implementation of JavaScript functions within an HTML file.
 To learn how to manipulate strings and numbers using JavaScript.
 To demonstrate basic form handling and user input validation.

Outcome:
By the end of this experiment, students will be able to:
 Write JavaScript functions to perform specific operations.
 Integrate JavaScript with HTML to create interactive web pages.
 Handle user inputs and display results dynamically.

Description: This experiment involves creating a web page with two functionalities:
 Calculating the length of a user-input string.
 Reversing the digits of a user-input number.

Modules
 HTML Structure
 Create a basic HTML structure with a form to take user inputs.
 Add fields for string input and number input.
 Include buttons to trigger the JavaScript functions for each operation.
 JavaScript Functions
 Write a function to calculate and display the length of a string.
 Write a function to reverse the digits of a number and display the result.

Example
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

20 | P a g e
<title>JavaScript String and Number Operations</title>
<script type="text/javascript">
function getStringLength() {
var str = document.getElementById("stringInput").value;
var length = str.length;
document.getElementById("stringLength").innerText = "Length of the string: " + length;
}

function reverseNumber() {
var num = document.getElementById("numberInput").value;
var reversedNum = num.split('').reverse().join('');
document.getElementById("reversedNumber").innerText = "Reversed number: " + reversedNum;
}
</script>
</head>
<body>
<h1>JavaScript String and Number Operations</h1>

<div>
<h2>String Length Calculation</h2>
<label for="stringInput">Enter a string:</label>
<input type="text" id="stringInput">
<button onclick="getStringLength()">Get String Length</button>
<p id="stringLength"></p>
</div>

<div>
<h2>Number Reversal</h2>
<label for="numberInput">Enter a number:</label>
<input type="text" id="numberInput">
<button onclick="reverseNumber()">Reverse Number</button>
<p id="reversedNumber"></p>
</div>
</body>
</html>

Output:
 When the user inputs a string and clicks the "Get String Length" button, the length of
the string is displayed.
 When the user inputs a number and clicks the "Reverse Number" button, the reversed
number is displayed.

Conclusion:
This experiment demonstrated the integration of JavaScript functions within an HTML file
to handle and manipulate user inputs for different operations. The students learned how to
calculate the length of a string and reverse the digits of a number using JavaScript functions.

21 | P a g e


Problem statements:
1. Character Frequency Counter: Write a JavaScript function that takes a string as input and
counts the frequency of each character in the string. Create a web interface with an input
field for the string and a button to display the character frequencies in a readable format.
2. Check for Palindrome: Develop a JavaScript function that checks if a given string is a
palindrome (reads the same backward as forward). Create an HTML form where users can
input a string and receive a message indicating whether the string is a palindrome or not.
3. Sum of Digits: Write a JavaScript function that takes a number as input and returns the sum
of its digits. Implement a web page with an input field for the number and a button that,
when clicked, displays the sum of the digits of the entered number.
4. Count Vowels and Consonants: Create a JavaScript function that takes a string as input and
counts the number of vowels and consonants in the string. Implement an HTML form where
users can input a string and see the counts of vowels and consonants displayed upon form
submission.
5. Convert String to Title Case: Write a JavaScript function that converts a given string into
title case, where the first letter of each word is capitalized. Develop an HTML form where
users can input a string, and upon clicking a button, the title-cased version of the string is
displayed.

22 | P a g e
Experiment No - 06

Experiment:
Prime Numbers Finder Using JavaScript

Aim:
To develop and demonstrate a HTML file that includes JavaScript to find all prime numbers
between a given starting and ending number.

Objective:
 To understand the use of JavaScript functions for numerical operations.
 To learn how to manipulate HTML forms and inputs using JavaScript.
 To practice integrating JavaScript with HTML to create interactive web pages.

Outcome
Students will be able to:
 Create an interactive web page using HTML and JavaScript.
 Develop JavaScript functions to perform numerical operations.
 Use JavaScript to validate and process user inputs from HTML forms.

Description
This experiment involves creating an HTML file with an embedded JavaScript code to find
all prime numbers between a given starting and ending number provided by the user. The
JavaScript function will check each number within the range and determine if it is a prime
number. The prime numbers will then be displayed on the web page.

Modules
1) Create HTML Form:
 Input fields for the starting and ending numbers.
 A button to trigger the JavaScript function.
 Write JavaScript Function:
2) Function to determine if a number is prime.
3) Function to find and display all prime numbers between the given range.
4) Integrate JavaScript with HTML:
5) Attach the JavaScript function to the button click event.
6) Display the results on the web page.

Example

23 | P a g e
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Prime Numbers Finder</title>
<script>
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i < num; i++) {
if (num % i === 0) return false;
}
return true;
}

function findPrimes() {
let start = parseInt(document.getElementById('start').value);
let end = parseInt(document.getElementById('end').value);
let primes = [];

for (let i = start; i <= end; i++) {
if (isPrime(i)) {
primes.push(i);
}
}

document.getElementById('result').innerHTML = 'Prime numbers: ' + primes.join(', ');
}
</script>
</head>
<body>
<h2>Prime Numbers Finder</h2>
<form>
<label for="start">Starting Number:</label>
<input type="number" id="start" required><br><br>
<label for="end">Ending Number:</label>
<input type="number" id="end" required><br><br>
<button type="button" onclick="findPrimes()">Find Primes</button>
</form>
<p id="result"></p>
</body>
</html>


Output:
When the user inputs a starting number and an ending number, and clicks the "Find Primes"
button, the web page will display all the prime numbers between the given range.

Conclusion:
By completing this experiment, students will learn how to integrate JavaScript with HTML
to perform numerical operations and display results dynamically on a web page. They will
also understand the basic concept of prime numbers and how to determine them using
JavaScript functions.

24 | P a g e


Problem Statements
1. Armstrong Number Checker: Problem Statement: Develop and demonstrate a HTML file
that includes a JavaScript script to check if a given number is an Armstrong number.
Input: A single number.
Output: Display whether the number is an Armstrong number or not.
2. Factorial Calculator: Problem Statement: Develop and demonstrate a HTML file that
includes a JavaScript script to calculate the factorial of a given number.
Input: A single number.
Output: Display the factorial of the number.
3. Fibonacci Sequence Generator: Problem Statement: Develop and demonstrate a HTML file
that includes a JavaScript script to generate the Fibonacci sequence up to a given number of
terms.
Input: A single number indicating the number of terms.
Output: Display the Fibonacci sequence up to the given number of terms.
4. Prime Factorization: Problem Statement: Develop and demonstrate a HTML file that
includes a JavaScript script to find all prime factors of a given number.
Input: A single number.
Output: Display all the prime factors of the number.
5. Find GCD (Greatest Common Divisor): Problem Statement: Develop and demonstrate a
HTML file that includes a JavaScript script to find the GCD of two given numbers.
Input: Two numbers.
Output: Display the GCD of the two numbers.

25 | P a g e
Experiment No -07
Experiment Title:
Creating a Digital Clock using PHP
Aim:
To develop a PHP program that displays a digital clock showing the current server time.
Objective:
 To understand how to use PHP to retrieve and display server time.
 To create a dynamic digital clock using PHP.
Materials Required:
 Text editor (e.g., Notepad++, Visual Studio Code)
 Web server environment (e.g., XAMPP, WAMP)
Procedure:
 Open your preferred text editor.
 Create a new PHP file and save it as "digital_clock.php".
 Begin the PHP script by opening PHP tags: <?php and ?>.
 Inside the PHP tags, use the date() function to fetch the current server time.
 Format the time retrieved from the server to display in a digital clock format.
 Use HTML and CSS to style the digital clock appearance.
 Embed the PHP code for displaying the dynamic server time within the HTML
structure.
 Save the PHP file.
Example PHP Code:
<?php
// Get current server time
$currentTime = date("H:i:s");

// Display the digital clock format
echo "<div style='font-size: 40px; font-weight: bold;'>";
echo "Current Time: $currentTime";
echo "</div>";
?>

Output:
The output of the PHP program will be a webpage displaying the current server time in a
digital clock format.

Conclusion:
In this experiment, we successfully created a PHP program to display a digital clock
showing the current server time. This demonstrates how PHP can be used for dynamic
content generation on webpages.

26 | P a g e


Problems to be solved
1. "Develop a PHP program that fetches and displays the current weather information for
a specified city using an external weather API."
 This program should allow users to input a city name and then fetch and display the
current weather conditions (temperature, humidity, weather description) using a weather
API like OpenWeatherMap.
2. "Create a PHP application that generates and displays a random quote from a
predefined list of quotes each time the page is refreshed."
 2. The program should have a list of inspirational or famous quotes stored in an array,
and each page load should display a randomly selected quote.
3. "Write a PHP script to create a simple task manager where users can add, delete, and
mark tasks as completed."
 This program should provide an interface for users to manage a to-do list, with options
to add new tasks, delete tasks, and mark tasks as done. Tasks can be stored in a text file
or a simple database.
4. "Design a PHP program that calculates and displays the current age of a user based on
their date of birth entered in an HTML form."
 The user should be able to input their date of birth in an HTML form, and upon
submission, the program calculates and displays their current age in years, months, and
days.
5. "Develop a PHP script to display a live updating leaderboard for a quiz competition,
fetching scores from a database."
 4 This program should connect to a database to fetch the latest scores of participants in a
quiz competition and display them in a leaderboard format, updating the scores in real-
time.

27 | P a g e
Experiment No-08

Experiment:
Implement Sign-In and Sign-Out Functionality Using PHP

Aim:
To write a PHP program to implement sign-in and sign-out functionality.

Objectives:
 To understand how to create and manage user sessions in PHP.
 To learn how to authenticate users using PHP and MySQL.
 To implement secure sign-in and sign-out mechanisms.

Outcome:
Students will be able to create a functional sign-in and sign-out system, manage user
sessions, and ensure secure user authentication.

Description:
In this experiment, you will create a PHP web application that allows users to sign in and
sign out. You will use MySQL to store user credentials securely and PHP sessions to
manage user authentication. The application will include a sign-in form, a sign-out button,
and session management logic.

Modules:
1) Create MySQL Database and Table:
 Create a database named userdb.
 Create a table named users with columns id, username, and password.
2) Database Connection:
 Write PHP code to connect to the MySQL database.
3) Sign-Up Form:
 Create a PHP script to handle user sign-up and store credentials in the database.
4) Sign-In Form:
 Create a PHP script to handle user sign-in and start a session.
5) Sign-Out Functionality:
 Create a PHP script to handle user sign-out and destroy the session.
6) Session Management:
 Write code to manage user sessions and restrict access to certain pages.

28 | P a g e
Example Code:
1) Create MySQL Database and Table:

CREATE DATABASE userdb;

USE userdb;

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL
);

2) Database Connection (db.php):
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "userdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>

3) Sign-Up Form (signup.php):

<?php
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

$sql = "INSERT INTO users (username, password) VALUES ('$username',
'$password')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>

<form method="post" action="signup.php">
Username: <input type="text" name="username" required><br>

29 | P a g e
Password: <input type="password" name="password" required><br>
<input type="submit" value="Sign Up">
</form>

4) Sign-In Form (signin.php):

<?php
session_start();
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row['password'])) {
$_SESSION['username'] = $username;
header("Location: welcome.php");
} else {
echo "Invalid password.";
}
} else {
echo "No user found.";
}
}
?>

<form method="post" action="signin.php">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Sign In">
</form>


5) Sign-Out Functionality (signout.php):
<?php
session_start();
session_unset();
session_destroy();
header("Location: signin.php");
?>

6) Session Management (welcome.php):
<?php
session_start();

if (!isset($_SESSION['username'])) {
header("Location: signin.php");

30 | P a g e
exit();
}
?>

<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>
<a href="signout.php">Sign Out</a>


Conclusion:
By completing this experiment, students will learn how to implement basic user
authentication using PHP and MySQL. They will understand session management and how
to secure web applications.

Problem Statements:

1) Password Reset Functionality:
 Implement a password reset feature where users can reset their password via email
verification.

2) Profile Management System:
 Create a system where users can update their profile information (e.g., name, email,
password).

3) Role-Based Access Control:
 Implement role-based access control where users with different roles (e.g., admin,
user) have access to different pages.

4) Multi-Language Support:
 Add multi-language support to the sign-in/sign-out application, allowing users to
select their preferred language.

5) Login Attempt Limitation:
 Implement a feature that limits the number of unsuccessful login attempts to prevent
brute force attacks. Lock the account for a certain period after multiple failed
attempts.

31 | P a g e
Experiment No -09

Experiment:
Visitor Counter Using PHP.

Aim:
To write a PHP program that keeps track of the number of visitors visiting the web page
and displays this count of visitors, with proper headings.

Objective
 To understand how to use PHP sessions and files for storing persistent data.
 To learn how to implement a visitor counter in a web application.
 To practice working with PHP file handling and session management.

Outcome
 Students will be able to create a visitor counter using PHP.
 Students will understand how to read and write data to a file in PHP.
 Students will learn how to use PHP sessions to maintain state information.

Description
In this experiment, students will develop a PHP program that increments a counter each
time the web page is visited and displays the updated count. The counter value will be
stored in a text file to maintain persistence between different sessions and browser restarts.

Stepwise Modules
 Initialize the Visitor Counter:
 Create or open a text file to store the visitor count.
 Read the current count from the file.
 Increment the count.
 Write the updated count back to the file.
 Display the Visitor Count:
 Output the visitor count on the web page with proper headings.
 Ensure Persistence:
 Use PHP file handling functions to maintain the count across multiple visits.

Code
<?php
// File to store the count

32 | P a g e
$counterFile = 'counter.txt';

// Check if the file exists
if (!file_exists($counterFile)) {
// Create the file and initialize the count to 0
file_put_contents($counterFile, 0);
}

// Read the current count from the file
$visitorCount = (int)file_get_contents($counterFile);

// Increment the count
$visitorCount++;

// Write the updated count back to the file
file_put_contents($counterFile, $visitorCount);

// Display the visitor count
echo "<h1>Visitor Counter</h1>";
echo "<p>Number of visitors: $visitorCount</p>";
?>


Output
When the script runs, it displays the number of visitors who have visited the web page:
Visitor Counter
Number of visitors: 1

Conclusion
By completing this experiment, students learned how to create a simple visitor counter
using PHP. They understood the concept of file handling in PHP to store and retrieve data
persistently.

Example Problems:
1. Daily Visitor Counter: Modify the script to reset the counter every day. Use a separate
file to store the date of the last reset and compare it with the current date.
2. Unique Visitor Counter: Implement a counter that tracks unique visitors using PHP
sessions. Only increment the counter if the session is new.
3. IP Address Tracker: Create a visitor counter that only increments if the visitor’s IP
address is not already stored in a file.
4. Page-Specific Counter: Develop a script that tracks the number of visits for different
pages on the website. Each page should have its own counter.
5. Visitor Counter with Timestamp: Enhance the visitor counter to log the date and time
of each visit in a separate file. Display the last visit time along with the visitor count.

33 | P a g e
Experiment No-10

Experiment:
Implementing AJAX Functionality Using PHP

Aim:
To write a PHP code that implements AJAX functionality.

Objective:
 To understand how to use AJAX with PHP to create dynamic web applications.
 To learn how to handle asynchronous HTTP requests using JavaScript and PHP.
 To implement a simple and interactive example using AJAX and PHP.

Outcome:
 Students will be able to implement AJAX functionality in their web applications.
 Students will understand how to send and receive data asynchronously using JavaScript
and PHP.
 Students will learn how to update parts of a web page without reloading the entire page.

Description
In this experiment, students will develop a PHP program that demonstrates AJAX
functionality by creating an interactive example where a user can get real-time data without
refreshing the page. The example will be a simple search box that fetches suggestions from
a server-side PHP script as the user types.

Stepwise Modules
1) Create HTML and JavaScript for AJAX:
 Set up a basic HTML form with a search box.
 Write JavaScript code to capture the user's input and send it to the server using
AJAX.
2) PHP Script to Handle AJAX Requests:
 Create a PHP script that processes the AJAX request and returns the matching data.
3) Integrate AJAX with PHP:
 Connect the JavaScript AJAX call with the PHP script to fetch and display data
dynamically.
 Code

Code:

34 | P a g e
HTML and JavaScript (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Search Example</title>
<script>
function showSuggestions(str) {
if (str.length == 0) {
document.getElementById("suggestions").innerHTML = "";
return;
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("suggestions").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "suggestions.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<h1>Search Example</h1>
<form action="">
<label for="search">Search:</label>
<input type="text" id="search" onkeyup="showSuggestions(this.value)">
</form>
<div id="suggestions"></div>
</body>
</html>

PHP Script (suggestions.php)
<?php
// Array with sample data
$suggestions = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew"];

// Get the search query
$q = $_GET["q"];

// Initialize an empty array to hold the matching suggestions
$matches = [];

// Check if the query is not empty
if ($q !== "") {
// Convert the query to lowercase for case-insensitive search
$q = strtolower($q);

// Iterate over the suggestions array
foreach ($suggestions as $suggestion) {
// Check if the suggestion starts with the query
if (strpos(strtolower($suggestion), $q) === 0) {
// Add the matching suggestion to the matches array

35 | P a g e
$matches[] = $suggestion;
}
}
}

// Return the matching suggestions as a list
echo empty($matches) ? "No suggestions" : implode("<br>", $matches);
?>

Output
When the user types in the search box, suggestions from the server will be displayed in
real-time below the input field without refreshing the page.

Conclusion
By completing this experiment, students learned how to create dynamic and interactive
web pages using AJAX and PHP. They understood how to handle asynchronous HTTP
requests and update the web page content without reloading.

Example Problems

1) Live Weather Update: Create a webpage that fetches and displays the current weather
information for a given city using AJAX and a weather API.
2) Live Sports Score: Develop a webpage that shows live sports scores from an API,
updating every few seconds using AJAX.
3) Dynamic Content Loading: Implement a webpage that loads additional content
dynamically as the user scrolls down, using AJAX to fetch data from the server.
4) Real-Time Chat Application: Create a simple chat application where messages are sent
and received in real-time without refreshing the page, using AJAX and PHP.
5) User Registration Validation: Develop a registration form that checks the availability of a
username in real-time using AJAX, providing instant feedback to the user.

36 | P a g e
Experiment No. 11

Experiment:
Searching Student Records Using PHP and AJAX

Aim:
To write a PHP program that performs a search operation on student records using AJAX for
a dynamic and responsive user experience.

Objective:
 To understand how to integrate PHP with AJAX for real-time data retrieval.
 To learn how to handle HTTP requests and responses using AJAX.
 To implement a search functionality on student records stored in a database.

Outcome:
 Students will be able to create a search interface using AJAX and PHP.
 Students will understand how to send asynchronous requests to a server using AJAX.
 Students will learn how to process and display search results dynamically without
reloading the page.

Description:
In this experiment, students will develop a web application that allows users to search for
student records stored in a MySQL database. The search operation will be performed using
PHP, and the results will be fetched and displayed using AJAX.

Stepwise Modules
1) Set Up the Database:
 Create a MySQL database and table to store student records.
 Insert sample student data into the table.
2) Create the HTML Form:
 Develop an HTML form to input the search query.
3) AJAX Request:
 Use JavaScript to send the search query to the server asynchronously.
4) PHP Script:
 Process the search query on the server side.
 Retrieve matching records from the database.
 Return the results as a JSON response.
5) Display Results:

37 | P a g e

 Use JavaScript to parse and display the search results dynamically.

Code:
Database Setup
CREATE DATABASE student_db;
USE student_db;

CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
roll_no VARCHAR(50),
class VARCHAR(50)
);

INSERT INTO students (name, roll_no, class) VALUES
('John Doe', '101', '10A'),
('Jane Smith', '102', '10B'),
('Sam Brown', '103', '10A'),
('Lucy Grey', '104', '10B');

HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Search</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Search Student Records</h1>
<input type="text" id="searchQuery" placeholder="Enter student name or roll number">
<button onclick="searchStudent()">Search</button>
<div id="results"></div>

<script>
function searchStudent() {
var query = document.getElementById('searchQuery').value;
$.ajax({
url: 'search.php',
type: 'GET',
data: {q: query},
success: function(response) {
var resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = response;
}
});
}
</script>
</body>
</html>

38 | P a g e
PHP Script (search.php)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$query = $_GET['q'];

$sql = "SELECT * FROM students WHERE name LIKE '%$query%' OR roll_no LIKE
'%$query%'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>" . $row["name"] . " - " . $row["roll_no"] . " - " . $row["class"] . "</p>";
}
} else {
echo "No records found";
}

$conn->close();
?>
Output
When the search form is submitted, the matching student records are displayed dynamically
below the search input without reloading the page.

Conclusion
By completing this experiment, students learned how to create a dynamic search feature
using PHP and AJAX. They understood how to perform asynchronous HTTP requests and
handle the server's response to update the web page dynamically.

Example Problems
1) Search by Multiple Criteria: Modify the script to allow searching by class and roll
number in addition to the name.
2) Pagination of Search Results: Implement pagination to handle large sets of search
results.
3) Highlight Search Terms: Highlight the search terms in the displayed results.
4) Advanced Search Filters: Add filters for students' grades or subjects.
5) Real-Time Search Suggestions: Implement a real-time search suggestion feature that
shows matching student names as the user types.

39 | P a g e
Experiment No. 12
Experiment:
Write a PHP program to perform search operation on the student records using AJAX

Aim
To develop a PHP program that performs a search operation on student records stored in a
database using AJAX for real-time results.

Objective
 To understand how to use AJAX for asynchronous data retrieval.
 To implement a search functionality in PHP.
 To enhance user experience by providing instant search results without reloading the
page.

Outcome
 By the end of this experiment, students will be able to:
 Create a web page that integrates PHP and AJAX.
 Implement real-time search functionality.
 Retrieve and display data asynchronously using AJAX.

Description
In this experiment, we will create a PHP program to search student records stored in a
MySQL database. We will use AJAX to handle the search operation, enabling real-time
results without the need to reload the page. The HTML form will include a search box, and
as the user types, AJAX will send the search query to the server and display matching
results.

Stepwise Modules
1) Create the Database and Table
 Set up a MySQL database named school.
 Create a table named students with fields id, name, age, grade, and email.
2) Insert Sample Data
 Insert some sample student records into the students table.
3) HTML Form
 Create an HTML form with a search input field.
4) AJAX Script
 Write JavaScript code to send the search query to the server using AJAX.
5) PHP Script

40 | P a g e

 Create a PHP script to process the AJAX request and return matching records from
the database.
6) Display Results
7) Update the HTML to display the search results dynamically.

Example
Database Creation and Sample Data (MySQL)
CREATE DATABASE school;
USE school;

CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(10),
email VARCHAR(100)
);

INSERT INTO students (name, age, grade, email) VALUES
('Alice Johnson', 20, 'A', '[email protected]'),
('Bob Smith', 22, 'B', '[email protected]'),
('Charlie Brown', 21, 'C', '[email protected]'),
('David Wilson', 23, 'A', '[email protected]');

HTML Form and AJAX Script
<!DOCTYPE html>
<html>
<head>
<title>AJAX Student Search</title>
<script>
function searchStudent() {
var query = document.getElementById('search').value;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'search.php?query=' + query, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('results').innerHTML = xhr.responseText;
}
};
xhr.send();
}
</script>
</head>
<body>
<h1>Search Student Records</h1>
<input type="text" id="search" onkeyup="searchStudent()" placeholder="Search by name...">
<div id="results"></div>
</body>
</html>

41 | P a g e
PHP Script (search.php)
<?php
$host = 'localhost';
$db = 'school';
$user = 'root';
$pass = '';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}

$query = $_GET['query'];
$sql = "SELECT * FROM students WHERE name LIKE '%$query%'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table border='1'>";
echo
"<tr><th>ID</th><th>Name</th><th>Age</th><th>Grade</th><th>Email</th></tr>";
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['grade'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No results found";
}

$conn->close();
?>

Output
When you type in the search box, matching student records will be displayed in real-time
without reloading the page.

Conclusion
This experiment demonstrated how to integrate PHP and AJAX to perform a real-time
search on a database. By following the steps outlined, students learned how to create a
dynamic and responsive web application that improves user experience.

Problems for Students to Solve
1) Implement Advanced Search Filters: Extend the search functionality to include filtering

42 | P a g e
by age, grade, and email.

2) Pagination of Search Results: Implement pagination for the search results to handle
large datasets efficiently.

3) Autocomplete Feature: Add an autocomplete feature to the search input field using
AJAX.

4) Highlight Search Terms: Highlight the search terms in the displayed results for better
user visibility.

5) Secure Search Queries: Modify the PHP script to use prepared statements to prevent
SQL injection attacks.
Tags