0% found this document useful (0 votes)
3 views32 pages

Web Tech 5 Unit q&b

Uploaded by

revathimamse
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)
3 views32 pages

Web Tech 5 Unit q&b

Uploaded by

revathimamse
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

M.A.M.

SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

Department of AIDS & IT


Academic Year 2026-2027(Odd Semester)
Unit - I

[Link]/[Link] : 24ADX05/ Web Technologies Date :

Year/Sem. : III/V Duration :


Max. Marks :

Part A (10 X 2 = 20 Marks)


Answer All the Questions
List the features of PHP.
Ans:
1. PHP is open-source, cross-platform, supports object-oriented programming, embeds directly into
HTML, offers native database engines (MySQL, PostgreSQL), provides robust session management,
and has massive community support.
How do you declare variables in PHP?
Ans:
2.
Variables in PHP are declared using the dollar sign ($) followed by the variable name (e.g.,
$variable_name = value;). They are dynamically typed and must start with a letter or an underscore.
Define string manipulation in PHP.
Ans:
3.
String manipulation refers to the processing, slicing, modifying, or formatting of alphanumeric chains
using built-in string functions like strlen(), str_replace(), substr(), and explode().
Differentiate between GET and POST methods.
Ans:
4. GET appends data parameters to the URL query string, visible to users, limited in data payload size,
and cacheable. POST transmits data through the HTTP message body, hidden from the URL, supports
unlimited lengths, and is secure for sensitive fields.
How can data be read from a textbox in PHP?
Ans:
5. Data can be retrieved from HTML input components using superglobal associative arrays:
$_POST['textbox_name'] if the form method is POST, or $_GET['textbox_name'] if the method is
GET.
What is file uploading in PHP?
Ans:
File uploading is a process where local user storage files are securely transferred to a remote web
server. It uses HTML's enctype='multipart/form-data' and is managed via the $_FILES superglobal in
6.
PHP.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

How do you connect PHP with MySQL?


Ans:
7. By utilizing the modern MySQLi (MySQL Improved) extension or PDO (PHP Data Objects). A basic
procedural example is: $conn = mysqli_connect($host, $user, $pass, $db);

Define session.
Ans:
8.
A session is a server-side storage mechanism used to persist stateful user identity variables across
multiple page requests, tracking users via a temporary session ID token stored in cookies or URLs.
What are cookies?
Ans:
9. Cookies are small text configuration files saved directly on the client side by the user's web browser,
transmitted along with every HTTP request to store preferences or login tracking tokens.

Differentiate between sessions and cookies.


Ans:
10. Sessions store operational data securely on the web server, whereas cookies save data configurations
on the local client browser. Sessions are safe from tempering, while cookies can be modified or
disabled by clients.

Part B
Explain the features and architecture of PHP.
Ans:
Features of PHP:
- Open-Source & Multi-Platform: Free deployment across Linux, Windows, or macOS systems.
- Embedded Engine: Runs alongside standard HTML layouts within standard web views.
- Dynamic Typing: Variables adapt to metadata states automatically.
 Client-Side Scripting:PHP can generate dynamicHTMLthat is sent to the browser.
While it runs on the server, the content it generates can be displayed in the client’s
browser.
 Database Handling: PHP easily connects to
11. databaseslikeMySQL,PostgreSQLandSQLite, allowing for efficient data management
and storage in web applications.
 Simple Learning Curve: PHP’s syntax is easy to learn, especially for those with basic
knowledge of HTML and programming concepts.
 Rich Ecosystem:PHP offers many libraries and frameworks like Laravel and Symfony,
which make development faster and more efficient.
 Scalability: PHP is highly scalable, allowing developers to create websites that can grow
in terms of traffic and functionality.
 Asynchronous Support: PHP, through the use of libraries and frameworks like
ReactPHP, supports asynchronous programming, allowing developers to handle multiple
requests concurrently.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

Architecture & Processing Workflow:

Step 1: User Requests the Page


 The user enters a URL into a web browser or clicks on a link, making an HTTP request to
the web server.

Step 2: Web Server Receives the Request


 The web server (Apache, Nginx, etc.) receives the HTTP request. The request is directed
to PHP for processing.
 The PHP script located on the server is executed.

Step 3: PHP Processes the Request


 The PHP script processes any server-side logic, such as handling form submissions,
processing data, or making requests to a database.
 If the PHP script requires database interaction, an SQL query is sent to the database.

Step 4: Database Interaction


 The PHP script sends a request to the database (e.g., MySQL) with an SQL query.
 The database processes the query and sends a response (results of the query) back to the
PHP script.

Step 5: PHP Responds with Dynamic Content


 Based on the database response, the PHP script processes and prepares the output
(dynamic HTML or other content) that will be sent back to the user's browser.
 This response is returned as an HTTP response to the web browser.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

Step 6: Web Browser Receives the Response


 The web browser receives the HTTP response, which includes dynamic content generated
by PHP.
 The browser renders the content on the user's screen.
This is how the PHP workflow operates in web applications, where PHP interacts with a
database and a web server to generate dynamic content for the user.

Discuss variables, data types, arrays, and strings in PHP with examples.
Ans:
PHP Variables
Variables are "containers" for storing information.
A variable can have a short name (like$xand$y) or a more descriptive name ($age,$carname,
$total_volume).
Rules for PHP variables:
A variable must start with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)

Remember that PHP variable names are case-sensitive!


12.
Create PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example

Create two variables, named $x and $y:


<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = "John";
echo $x;
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

echo "<br>";
echo $y;
?>
</body>
</html>

Data Types
 Variables can store data of different types, and different data types can do different
things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

Example: The var_dump() function returns the data type and the value:

<!DOCTYPE html>
<html>
<body>
<?php
var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
var_dump([2, 3, 56]);
var_dump(NULL);
?>
</body>
</html>

PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes:
Example:
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

<!DOCTYPE html>
<html>
<body>

<p>Using double quotes:</p>


<pre>
<?php
$x = "John";
echo "Hello $x\n";
echo "\tHow are you?\n";
?>
</pre>

<p>Using single quotes:</p>


<pre>
<?php
$x = 'John';
echo 'Hello $x\n';
echo '\tHow are you?\n';
?>
</pre>

</body>
</html>

PHP Arrays
In PHP, an array is a special variable that can hold many values under a single name, and you
can access the values by referring to an index number or a name.
In PHP, there are three types of arrays:
Indexed arrays- Arrays with a numeric index
Associative arrays- Arrays with named keys
Multidimensional arrays- Arrays containing one or more arrays

Array items can be of any data type.


The most common are strings and numbers, but array items can also be objects, functions or
even arrays.
You can have different data types in the same array.
<!DOCTYPE html>
<html>
<body>
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

<?php
// create array
$myArr = array("Volvo", 15, ["apples", "bananas"]);
echo "$myArr[0]<br>";
echo "$myArr[1]<br>";
echo "$myArr[2]";
?>
</body>
</html>

PHP Array Functions


The real strength of PHP arrays are the built-in array functions.
Here we use the count() function to count the array items:

Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Describe control structures in PHP.
Ans:
PHP supports foundational logical branches and loop iteration sequences:
1. Conditional Branches: if-else statements and switch-case patterns for routing operations based
on data comparisons.
Conditional statements are used to perform different actions based on different conditions.
In PHP, we have the following conditional statements:
if statement - executes some code if one condition is true
a) if...else statement - executes some code if a condition is true and another code if
13.
that condition is false
if...elseif...else statement - executes different codes for more than two
conditions
switch statement - selects one of many blocks of code to be executed

PHP - The if Statement


The if statement executes some code only if the specified condition is true.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

Example:
<?php
$t = 14;

if ($t < 20) {


echo "Have a good day!";
}
?>

PHP - The if...else Statement


The if...else statement executes some code if a condition is true and another code if that
condition is false
Example:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.

<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

The PHP switch Statement


The switch statement is used to perform different actions based on different conditions.

Use the switch statement to select one of many blocks of code to be executed.
Example:
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
2. Iteration Loops:
- for loops for executing code blocks a predetermined number of times.
- while and do-while loops for repeating tasks based on boolean status conditions.
- foreach loops, designed for looping through array sets: foreach($arr as $key => $val).
In PHP, we have the following loop types:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as
the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array

Example for while loop


<?php
$i = 1;

while ($i < 6) {


echo $i;
$i++;
}
?>
Example for do...while loop
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

<?php
$i = 1;

do {
echo $i;
$i++;
} while ($i < 6);
?>
Example for for loop
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Example for for..each loop
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>
Explain user-defined functions in PHP with examples.
Ans:
Besides the built-in PHP functions, it is possible to create your own functions.
A function is a block of statements that can be used repeatedly in a program.
A function is not executed automatically when a page loads.
A function is executed only when it is called.
Create a Function
A user-defined function declaration starts with the keyword function, followed by the name
of the function.

b) The opening curly brace{indicates the beginning of the function code, and the closing curly
brace}indicates the end of the function.
Note: A function name is not case-sensitive, and it must start with a letter or an underscore.
The following example creates a function named myMessage():
function myMessage()
{
echo "Hello world!";
}
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

Call a Function
To call a function, just write its name followed by parentheses().
The function below outputs "Hello world!":
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>
PHP Function Parameters
Information can be passed to functions through parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

The following example shows how to use a default parameter.


If we call the function setHeight()without a parameter, it will take the default value:
<?php
function setHeight($height = 50) {
echo "The height is : $height.<br>";
}
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

setHeight(350);
setHeight();
?>

Passing Arguments by Reference


Arguments are usually passed by value, which means that a copy of the value is used in the
function and the variable that was passed into the function cannot be changed.
When a function argument is passed by reference, changes to the argument also change the
variable that was passed in. To turn a function argument into a reference, use the & operator in
front of the argument/parameter:
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>

14. Describe PHP-MySQL connectivity with a sample program.


Ans:
PHP connects to MySQL databases using built-in extensions that allow scripts to perform
CRUD (Create, Read, Update, Delete) operations. Modern PHP supports two secure methods:
MySQLi (MySQL Improved), designed exclusively for MySQL, and
PDO (PHP Data Objects), which offers a cross-database abstraction layer

Step-by-Step Sample Program (MySQLi Object-Oriented)

This standard script demonstrates how to configure credentials, safely open a connection,
execute a data-fetching query, and close the resource properly.

<?php
// 1. Define Database Credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school_db";
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

// 2. Establish the Connection


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

// 3. Verify Connection Integrity


if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
echo "Connected successfully to the database.<br>";

// 4. Execute a SQL Query


$sql = "SELECT id, firstname, lastname FROM students";
$result = $conn->query($sql);

// 5. Process and Display Results


if ($result->num_rows > 0) {
// Fetch row data as an associative array
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results found.";
}

// 6. Release System Resources


$conn->close();
?>
Core Steps Explained

 Credential Initialization: Sets up variables holding the target server hostname, administrative
username, security password, and the specific database layout.
 Instance Instantiation: Invoking new mysqli() fires up the native driver to bridge
communications with the database layer.
 Error Verification: Checking $conn->connect_error catches authorization or network errors
early, halting execution via die() before compiling broken operations.
 Data Loop Processing: The fetch_assoc() mechanism acts as a cursor, outputting one mapped
data row at a time until the query array empties out.
 Resource Cleanup: Explicitly calling $conn->close() terminates the connection thread
immediately, preventing connection pool leaks on the server host.

M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

Discuss session and cookie management in PHP.


Ans:
PHP uses sessions and cookies to overcome the stateless nature of HTTP, allowing web
applications to remember user states, credentials, and preferences between page loads. The core
difference is that cookies store data on the client browser, while sessions store data securely
on the web server

Cookie Management in PHP

Cookies are small text files limited to roughly 4KB of data stored directly on the user’s computer.
Because clients can view and modify cookie data, they must never store sensitive information like
passwords

1. Setting a Cookie
To create a cookie, use the setcookie() function. This function must be executed before any
HTML or text output is sent to the browser

// Syntax: setcookie(name, value, expire, path, domain, secure, httponly)


$expire_time = time() + (86400 * 30); // 30 days from now

setcookie("user_preference", "dark_mode", [
15. a) 'expires' => $expire_time,
'path' => '/',
'domain' => '',
'secure' => true, // Sent only over HTTPS
'httponly' => true, // Inaccessible to JavaScript (prevents XSS cookie theft)
'samesite' => 'Lax' // Mitigates CSRF attacks
]);

2. Reading a Cookie
You can read browser cookies via the $_COOKIE superglobal associative array. Always verify
its existence using isset()

if (isset($_COOKIE['user_preference'])) {
$theme = $_COOKIE['user_preference'];
echo "Your theme is: " . htmlspecialchars($theme);
}
3. Deleting a Cookie
To delete a cookie, use setcookie() with the exact same configuration parameters but set the
expiration time to a past date

setcookie("user_preference", "", time() - 3600, "/");


M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

Session Management in PHP


Sessions provide secure server-side storage capable of holding complex data structures without
size limitations. PHP links a server-side storage file to a specific user by generating a unique
Session ID and dropping a small cookie named PHPSESSID into the user’s browser.

1. Initializing and Writing Sessions


Every page using session data must invoke session_start() before any HTML output. Data is
manipulated using the $_SESSION superglobal

<?php
session_start(); // Initializes or resumes the session

// Storing session variables


$_SESSION['user_id'] = 42;
$_SESSION['username'] = 'Alice';
$_SESSION['role'] = 'admin';

2. Reading Session Data

Once a session is active, variables are instantly readable across any script on the server.

<?php
session_start();

if (isset($_SESSION['user_id'])) {
echo "Welcome back, " . htmlspecialchars($_SESSION['username']);
}

3. Destroying Sessions

To clear a session completely (e.g., during a user logout), free all array entries and wipe the server
file

<?php
session_start();

session_unset(); // Frees all $_SESSION variables


session_destroy(); // Destroys the underlying server-side session data file

Discuss form handling in PHP using textboxes, radio buttons, and list controls.
b) Ans:
Form handling in PHP relies on capturing data submitted via HTML elements using the
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

superglobal arrays $_POST or $_GET . The interaction between HTML input fields and server-side
PHP scripts depends directly on the element's name attribute

1. Core Core Concepts & PHP Collection

The Request Method: Use method="POST" in your HTML <form> tag for data security and
handling larger sets of information.
Superglobal Collection: PHP instantly populates $_POST['element_name'] with the user's
choices once submitted.
Data Validation & Security: Always run data through htmlspecialchars() to sanitize inputs
against Cross-Site Scripting (XSS) injections

2. Comprehensive Implementation Matrix

The table below breaks down the design syntax and data handling models for textboxes, radio
buttons, and list controls.

Form Control HTML Syntax PHP Data Structure Handling


Characteristics

Textbox <input type="text" String (Raw text Captured whether


name="username"> input) populated or empty.
Requires explicit
verification ( isset()
or empty() ).

Radio Button <input type="radio" String (The explicitly Mutually exclusive


name="gender" defined value grouped selections.
value="M"> attribute) Throws a PHP
error if submitted
without any option
checked.

List Control (Single) <select String (Selected Defaults to the first


name="country">... <option> value) item listed if the user
leaves it untouched.

List Control (Multiple) <select name="skills[]" Indexed Array Requires array notation
multiple>... (Array of chosen [] in the name
entries) attribute. Loops are
needed to iterate
through choices.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

3. Consolidated Script Example

This unified layout showcases both the front-end interface structure and the back-end extraction
script required to safely process all three inputs.

<?php
// Initialize output and error monitoring vars
$errors = [];
$formData = [];

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

// 1. Textbox Processing
if (!empty($_POST["username"])) {
$formData['username'] = htmlspecialchars(trim($_POST["username"]));
} else {
$errors[] = "Username textbox is required.";
}

// 2. Radio Button Processing (Always verify option presence via isset)


if (isset($_POST["gender"])) {
$formData['gender'] = htmlspecialchars($_POST["gender"]);
} else {
$errors[] = "Please select a radio button option for gender.";
}

// 3. List Control Processing (Multiple Selection handling)


if (!empty($_POST["skills"])) {
// Collect choices using array maps for bulk sanitization
$formData['skills'] = array_map('htmlspecialchars', $_POST["skills"]);
} else {
$errors[] = "Please pick at least one entry from the skills list.";
}

// Display validation results


if (empty($errors)) {
echo "<h3>Form Submission Successful</h3>";
echo "User: " . $formData['username'] . "<br>";
echo "Gender: " . $formData['gender'] . "<br>";
echo "Skills: " . implode(", ", $formData['skills']);
} else {
foreach ($errors as $error) {
echo "<p style='color:red;'>$error</p>";
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

}
}
}
?>

<!-- HTML Interface Layout Structure -->


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

<!-- Textbox -->


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

<!-- Radio Buttons (Shared group name creates mutual exclusivity) -->
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="Male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label><br><br>

<!-- List Control (Using bracket arrays to support multiple item selection) -->
<label for="skills">Skills:</label>
<select id="skills" name="skills[]" multiple size="3">
<option value="PHP">PHP Development</option>
<option value="SQL">SQL Database</option>
<option value="HTML">HTML Structure</option>
</select><br><br>

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


</form>
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

Department of AIDS & IT


Academic Year 2026-2027(Odd Semester)
Unit – II

[Link]/[Link] : 24ADX05/ Web Technologies Date :

Year/Sem. : III/V Duration :


Max. Marks :

Part A (10 X 2 = 20 Marks)


Answer All the Questions
What is JavaScript?
Ans:
1.
JavaScript is a lightweight, cross-platform, interpreted, client-side scripting language that adds
dynamic behavior, interactivity, and programmatic logic to static HTML web pages.
What is variable scope?
Ans:
2. Variable scope defines the accessibility and visibility context of a variable within a script. It can be
Global (accessible everywhere) or Local/Block-Scoped (restricted within a specific function or curly
braces)
What is an event handler?
Ans:
3.
An event handler is a registered callback function designed to execute automatically when a specific
browser interaction or event occurs, such as a user clicking a button.
Name any four JavaScript events.
Ans:
1. onclick (mouse click),
4.
2. onsubmit (form submission),
3. onkeyup (keyboard key release),
4. onload (web resource completion).
What is the Document Object Model (DOM)?
Ans:
5.
The DOM is a structural programming interface that treats an HTML document as a node tree graph,
allowing scripting languages to dynamically access, modify, and update layout styles.
What is AJAX?
Ans:
6. Asynchronous JavaScript and XML (AJAX) is a web development approach used to update parts of a
web page asynchronously by exchanging data with a server behind the scenes without requiring a full
page reload
What is a callback function?
Ans:
7.
A callback function is a function passed as an argument into another function, intended to be executed
after a specific asynchronous operation or task finishes.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

What is JSON?
Ans:
8.
JavaScript Object Notation (JSON) is a lightweight, text-based, human-readable data interchange
format used to transmit structured key-value data structures between servers and client applications.
Differentiate between JavaScript and PHP.
Ans:
9.
JavaScript runs directly on the user's client-side browser to handle UI interaction logic, whereas PHP
is a server-side language that executes on backend web servers to process database storage queries.
What is DOM manipulation?
Ans:
10.
DOM manipulation is the process of using JavaScript APIs to add, remove, modify, or reorder HTML
elements, attributes, or CSS classes on a live web page

Part B
11. Explain JavaScript event handling with suitable examples.
Ans:
JavaScript event handling is the process of capturing and responding to user actions or
browser occurrences—such as clicks, keystrokes, or page loads—by executing specific code
blocks

The 3 Ways to Handle Events


1. Inline Event Handlers
You write JavaScript code directly inside the HTML tag using an event attribute (e.g., onclick ,
onchange ).

 Drawback: Mixes logic with structure, making maintenance complex.


Html:
<button onclick="alert('Inline execution!')">Click Me</button>

2. Traditional DOM Properties

You assign an event handler function directly to the object property of the DOM element using
JavaScript.

 Drawback: You can attach only one function per event type; subsequent definitions overwrite
prior ones.
Javascript:
const btn = [Link]("myBtn");
[Link] = function() {
[Link]("DOM property execution!");
};

3. addEventListener() Method (Recommended)


M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

This approach attaches an event listener to an element without wiping existing listeners. It
supports multiple functions on a single event type and offers granular control over propagation

javascript
const btn = [Link]("myBtn");
[Link]("click", () => {
[Link]("Standard event listener executed!");
});

Code Examples of Common Event Types


Mouse Event ( click )

<button id="colorBtn">Change Color</button>


<script>
const button = [Link]("#colorBtn");
[Link]("click", () => {
[Link] = "lightblue";
});
</script>

Keyboard Event ( keyup )

<input type="text" id="username" placeholder="Type here...">


<script>
const inputField = [Link]("#username");
[Link]("keyup", (e) => {
[Link](`User typed and released: ${[Link]}`); // Accesses event object data
});
</script>
Form Event ( submit )

<form id="loginForm">
<input type="text" required>
<button type="submit">Submit</button>
</form>
<script>
const form = [Link]("#loginForm");
[Link]("submit", (e) => {
[Link](); // Stops page refresh
[Link]("Form validated via JS!");
});
</script>
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

12. Discuss variables, scope, and functions in JavaScript with examples.


Ans:
Variables, scope, and functions are the core building blocks of
JavaScript that work together to store data, control visibility, and execute reusable logic

1. Variables ( var , let , const )

Variables are named containers used to store data values. Modern JavaScript offers three distinct
keywords for variable declaration, differentiated by reassignability and scoping rules

Example:
// var: Function-scoped, can be redeclared and reassigned
var city = "New York";
var city = "London";

// let: Block-scoped, can be reassigned but NOT redeclared


let score = 10;
score = 15;

// const: Block-scoped, cannot be reassigned or redeclared


const pi = 3.1415;
// pi = 3.14; // Throws TypeError

2. Scope
Scope dictates the accessibility and visibility of your variables across different regions of your
code.

Global Scope
Variables declared outside any function or block live in the global scope. They are accessible
from absolutely anywhere in your script

Example:
const globalBonus = 500;

function calculateTotal() {
return 1000 + globalBonus; // Accessible inside functions
}

Function Scope
Variables declared using var inside a function belong strictly to that function. They cannot be
referenced outside of it
Example:
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

function greet() {
var message = "Hello Friend";
[Link](message); // Works
}
greet();
// [Link](message); // Throws ReferenceError
Block Scope
Introduced in ES6, variables declared with let and const inside curly braces {} (such as
ifstatements or loops) are isolated to that block.

Example:
if (true) {
var statusVar = "Visible";
let statusLet = "Hidden Outside";
}
[Link](statusVar); // Logs: "Visible"
// [Link](statusLet); // Throws ReferenceError

3. Functions
Functions are structured, reusable blocks of code engineered to perform isolated actions. They
can take inputs (parameters) and return an explicit output value.

Function Declaration

Traditional named functions that benefit from hoisting (can be called before they are written in
the file).
Example:

function multiply(a, b) {
return a * b; // Exits function and outputs value
}
const result = multiply(5, 4); // result is 20

Function Expression

Functions assigned directly to a variable. These are not hoisted and cannot be called before
definition.

Example:

const divide = function(a, b) {


return a / b;
};
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

[Link](divide(10, 2)); // Logs: 5


Arrow Functions

A modern, concise syntax variant introduced in ES6 that lacks its own bindings to the this
keyword.
Example:

const add = (a, b) => a + b; // Implicit return for one-liners


[Link](add(3, 7)); // Logs: 10

This unified example highlights how variables, scope, and functions interact natively in a
runtime context:

const baseTax = 0.15; // Global scope variable

function computeInvoice(price) { // Function declaration


let processingFee = 5.00; // Function scope variable

if (price > 100) {


const discount = 10.00; // Block scope variable
price = price - discount; // Modifying function-scoped input
}
// [Link](discount); // Error: discount is block-scoped!

return price + (price * baseTax) + processingFee;


}

[Link](computeInvoice(120)); // Accessible execution


Explain DOM manipulation techniques using JavaScript.
a)
13. Ans:
What is DOM?✨
DOM is a programming interface that transforms a web page into an object model that the
browser can understand. When the browser loads a web page, it analyzes the content of the page
and creates this content in memory in the form of a DOM tree. This tree structure contains all the
elements of the page (e.g., title, paragraph, image, links), and these elements are related to each
other.
DOM Elements✨
DOM methods are used to access and manipulate HTML elements on web pages using
JavaScript. These methods are used to select and make changes to certain types of elements.
getElementById():
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

This method selects based on the id attribute of an element on the page.


var element = [Link]("myElementId");
getElementsByClassName():
This method is used to select all elements belonging to a particular class.
var elements = [Link]("myClassName");
getElementsByTagName():
This method is used to select all elements with a specific tag.
var elements = [Link]("div");
querySelector() and querySelectorAll():
querySelector() selects the first element that matches a given CSS selector, while
querySelectorAll() selects all matching elements.
var element = [Link]("#myElementId");
var elements = [Link](".myClassName");
DOM Manipulation
Web developers can perform DOM manipulation using JavaScript. This includes dynamically
changing page content, adding new elements, removing existing elements, and updating style
properties.
Changing Element Content:
We can use innerHTML or textContent properties to change the text content of an element
within the DOM.
var element = [Link]("myElementId");
[Link] = "New content"; // or [Link] = "New content";
Creating a New Element:
We can add it to the page by creating a new HTML element.
var newElement = [Link]("div");
[Link] = "New Item";
[Link](newElement);
Removing Elements:
To remove an existing element, we must find the parent element of the element and then use the
removeChild() method.
var elementToRemove = [Link]("myElementId");
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

[Link](elementToRemove);
Changing Element Styles and Properties:
We can change the CSS style properties and other properties of the elements.
var element = [Link]("myElementId");
[Link] = "red";
Discuss client-side form validation with examples.
b)
Ans:
Client-side form validation is the process of checking user-entered data inside the web
browser before it is transmitted to a web server. Its primary goals are providing instant
feedback to users, improving data quality, and reducing server load by blocking
malformed requests

Complete Implementation Example: Html

<form id="registrationForm" novalidate>


<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required minlength="3">
<small class="error-msg" id="usernameError"></small>
</div>

<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<small class="error-msg" id="emailError"></small>
</div>

<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required minlength="6">
<small class="error-msg" id="passwordError"></small>
</div>

<button type="submit">Register</button>
</form>

Javascript Logic example:

[Link]('registrationForm').addEventListener('submit', function(event) {
// 1. Always halt initial submission to run evaluations
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

[Link]();

// 2. Fetch form element nodes and values


const usernameInput = [Link]('username');
const emailInput = [Link]('email');
const passwordInput = [Link]('password');

// 3. Clear previous UI error states


[Link]('.error-msg').forEach(msg => [Link] = '');
let isFormValid = true;

// --- Check Validation Rule 1: Username Length ---


if ([Link]().length < 3) {
[Link]('usernameError').textContent = 'Username must be at least 3
characters long.';
isFormValid = false;
}

// --- Check Validation Rule 2: Email Format via Regex ---


const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (![Link]([Link]())) {
[Link]('emailError').textContent = 'Please enter a valid email address.';
isFormValid = false;
}

// --- Check Validation Rule 3: Native Browser API Strategy ---


// Using checkValidity() to enforce the HTML5 minlength="6" attribute
if (![Link]()) {
[Link]('passwordError').textContent = 'Password must match
requirements (Min 6 characters).';
isFormValid = false;
}

// 4. Final Verdict Processing


if (isFormValid) {
[Link]('Client validation successful. Proceeding with API transmission.');
// You can now execute a secure fetch request or use [Link]();
}
});
Describe AJAX architecture and working principles.
14. Ans:
AJAX =Asynchronous JavaScript And XML.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

AJAX is not a programming language.


AJAX just uses a combination of:
A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data)
AJAX is a misleading name. AJAX applications might use XML to transport data, but it is
equally common to transport data as plain text or JSON text.
AJAX allows web pages to be updated asynchronously by exchanging data with a web server
behind the scenes. This means that it is possible to update parts of a web page, without reloading
the whole page.

How AJAX Works


M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

1. A user generates an event on the client. This results in a JavaScript technology call.

2. A JavaScript technology function creates and configures an XMLHttpRequest object on


the client, and specifies a JavaScript technology callback function.
3. The XMLHttpRequest object makes a call -- an asynchronous HTTP request -- to the
web server.
4. The web server processes the request and returns an XML document that contains the
result.
5. The XMLHttpRequest object calls the callback function and exposes the response from
the web server so that the request can be processed.
6. The client updates the HTML DOM representing the page with the new data.

Core Technology Stack


AJAX is a design pattern composed of existing web standards rather than a standalone language
 HTML / XHTML & CSS: For structure and presentation layout styling.

 Document Object Model (DOM): The programmatic interface utilized by JavaScript to


dynamically read, change, append, or delete interface elements.
 Data Interchanges: Extensible Markup Language (XML) or JavaScript Object Notation (JSON)
to package data.
 XMLHttpRequest / Fetch API: The network plumbing inside the browser that acts as the
asynchronous gateway to the server.
 JavaScript: The core scripting logic orchestrating the entire cycle from listening to user actions
to updating DOM branches.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

15. Explain the implementation of a simple AJAX application.


Ans:
An AJAX (Asynchronous JavaScript and XML) application is implemented by using a
browser's built-in XMLHttpRequest object (or modern fetch API) to send and receive data from
a web server in the background, updating only specific parts of the webpage without a full page
reload.
Below is the complete architectural workflow and code implementation for a simple AJAX
application that fetches a text message from a server.
The 4-Step AJAX Workflow
 Triggering the Event: A user action (e.g., clicking a button, typing text) executes a
JavaScript function.

 Creating and Configuring the Request: JavaScript instantiates an XMLHttpRequest


object and specifies the HTTP method, targeted URL, and asynchronous flag.
 Server Communication: The request is sent to the server in the background. The user
can continue interacting with the page uninterrupted.
 Handling the Callback: When the server responds, a callback function captures the data,
modifies the HTML Document Object Model (DOM), and updates the UI.

Code Implementation
A functional AJAX setup requires two primary components: the Frontend Client
(HTML/JavaScript) and the Backend Server Target (Data File/Script).
1. Frontend: [Link]

This file builds the basic layout and executes the asynchronous vanilla JavaScript logic
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple AJAX Application</title>
</head>
<body>

<h2>AJAX Demonstration</h2>
<!-- This div will be updated dynamically without refreshing -->
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

<div id="content-box">
<p>Original content loaded from the initial page load.</p>
</div>

<!-- User action to trigger the AJAX call -->


<button type="button" onclick="loadServerData()">Fetch Dynamic Content</button>

<script>
function loadServerData() {
// Step 1: Instantiate the browser's built-in request object
var xhttp = new XMLHttpRequest();

// Step 2: Define the callback handler triggered by state changes


[Link] = function() {
// readyState 4 means the request is fully completed
// status 200 means the server processed it successfully
if ([Link] == 4 && [Link] == 200) {
// Step 4: Inject the text response directly into the target HTML element
[Link]("content-box").innerHTML = [Link];
}
};

// Step 3: Open the request connection (GET method, target URL, Asynchronous=true)
[Link]("GET", "[Link]", true);

// Step 4: Disconnect from the main process thread and send the request
[Link]();
}
</script>
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]

</body>
</html>
2. Backend: [Link]

Create a plain text file named [Link] in the exact same directory as your HTML file. This acts
as the server-side resource containing the data you want to retrieve
<h4>Success!</h4>
<p>This paragraph was securely fetched from the web server via an AJAX request without
reloading the entire page.</p>

FACULTY HOD PRINCIPAL

You might also like