[go: up one dir, main page]

0% found this document useful (0 votes)
9 views51 pages

Wpassignment

The document discusses various topics related to HTML, CSS, and JavaScript, including semantic HTML tags, the CSS box model, class vs. id selectors, z-index, responsive design with media queries, and JavaScript concepts such as closures and asynchronous programming. It emphasizes the importance of semantic HTML for SEO and accessibility, explains the CSS box model components, and differentiates between JavaScript variable declarations. Additionally, it covers event handling in JavaScript, including event bubbling and capturing.

Uploaded by

arbhayla03
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)
9 views51 pages

Wpassignment

The document discusses various topics related to HTML, CSS, and JavaScript, including semantic HTML tags, the CSS box model, class vs. id selectors, z-index, responsive design with media queries, and JavaScript concepts such as closures and asynchronous programming. It emphasizes the importance of semantic HTML for SEO and accessibility, explains the CSS box model components, and differentiates between JavaScript variable declarations. Additionally, it covers event handling in JavaScript, including event bubbling and capturing.

Uploaded by

arbhayla03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

220280107008 BHAYALA ABDULREHMAN

Assignment
CO-1: Use the various HTML tags with appropriate styles to display the
various types of contents effectively.

Q.1) What are semantic HTML tags? Provide examples and explain their importance in
SEO and accessibility.
Ans. Semantic HTML tags are elements that clearly define the meaning of the content they contain. Unlike
non-semantic tags (e.g., <div> and <span>), which do not provide any context about their content, semantic
tags improve readability, accessibility, and search engine optimization (SEO).
1. <header> – Represents the introductory content or navigational links of a webpage.
<header>
<h1>Welcome to My Website</h1>
<ul>
<li><a href="#">Home</a></li>
</ul>
</header>
2. <nav> – Defines a section for navigation links.
<nav>
<ul>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
3. <footer> – Defines the footer section of a webpage, usually containing copyright information, links, or
contact details.
<footer>
<p> 2025 MyWebsite. All rights reserved.</p>
</footer>
Importance of Semantic HTML in SEO and Accessibility

C.E., LDCE 1
BHAYALA ABDULREHMAN
220280107008

1. SEO Benefits
• Helps search engines understand page structure, improving indexing and ranking.
• Increases the chances of content appearing in rich snippets.
• Enhances readability for search engine crawlers.
2. Accessibility Benefits
• Improves user experience for screen readers and assistive technologies.
• Helps visually impaired users navigate web content easily.
• Ensures a structured and meaningful layout for all users.
3. Maintainability and Readability
• Makes the code more readable and maintainable for developers.
• Reduces the need for excessive div elements (commonly known as "div soup").

Q.2) What is the box model in CSS? Explain the different components of the box model.
Ans. The CSS Box Model is a fundamental concept that defines how elements are structured and
displayed on a webpage. It consists of four main components: Content, Padding, Border, and
Margin, each contributing to the overall size and spacing of an element.
1. Content
• This is the innermost part of the box where text, images, or other elements are placed.
• Its size is controlled by width and height properties.
2. Padding

• The space between the content and the border.


• Increases the spacing inside the box without affecting the border or margin.

3. Border

• Wraps around the padding and content, defining the outer edge of the box.
• Can be styled using properties like border-width, border-style, and border-color.

4. Margin

• The space outside the border that separates the element from other elements.
• Used for spacing between elements.

C.E., LDCE 2
220280107008 BHAYALA ABDULREHMAN

Q.3) What is the difference between class and id in CSS? Provide examples of when to use
each.
Ans.

Aspect Class Selector (“.”) Id Selector (“#”)

Targets elements with a specific class Targets an element with a unique id


Usage
attribute attribute

Must be unique within a page, used for


Uniqueness Can be applied to multiple elements
one element

Multiplicity An element can have multiple classes An element can have only one id

Used for general styling across multiple


Application Used for specific, single-element styling
elements

Syntax .class_name { /* properties */ } #id_name { /* properties */ }

Using Class (.) - When Styling Multiple Elements


A class is ideal for applying the same style to multiple elements.
<html lang="en">
<head>
<style>
.button {
background-color: blue;

C.E., LDCE 3
220280107008 BHAYALA ABDULREHMAN

color: white;
}
</style>
</head>
<body>
<button class="button">Submit</button>
<button class="button">Cancel</button>
</body>
</html>
Using ID (#) - When Styling a Unique Element
An ID is meant for a single element that should have a unique style.
<html lang="en">
<head>
<style>
#main-title {
font-size: 24px;
color: darkgreen;
}
</style>
</head>
<body>
<h1 id="main-title">Welcome to My Website</h1>
</body>
</html>

Q.4) What is the purpose of the z-index property in CSS? How does it affect positioning?
Ans. The z-index property in CSS is used to control the stacking order of overlapping elements. It
determines which elements appear in front and which ones appear behind when they overlap on a
webpage.

C.E., LDCE 4
220280107008 BHAYALA ABDULREHMAN

How z-index Affects Positioning


1. Positive z-index Values → Move the element closer to the user (front).
2. Negative z-index Values → Move the element further back (behind other elements).
3. Default auto Value → Elements are stacked based on the HTML source order.
4. Stacking Context → z-index works within the same stacking context. If an element’s parent has a z-
index, child elements are positioned relative to it.
<html lang="en">
<head>
<style>
.box {
width: 200px;
height: 200px;
}
.box1 {
background-color: red;
top: 50px;
z-index: 1;
}
.box2 {
top: 100px;
z-index: 2; /* This box will appear in front */
}
</style>
</head>
<body>
<div class="box box1"></div>
<div class="box box2"></div>
</body>
</html>

C.E., LDCE 5
BHAYALA ABDULREHMAN
220280107008

Q.5) How would you create a responsive web page layout that adjusts to different screen sizes
using CSS? Explain the use of media queries.
Ans. Techniques for Responsive Design
1. Fluid Layouts – Using relative units (%, vw, vh) instead of fixed units (px).
2. Flexible Images – Ensuring images resize with max-width: 100%.
3. CSS Flexbox & Grid – Creating adaptable layouts.
4. Media Queries – Applying different styles based on screen width.
Media queries allow you to apply CSS rules conditionally based on screen width, height, orientation, or
device type.
@media (max-width: 768px) {
/* CSS rules for screens 768px or smaller */
}
Q.6) Explain the differences between inline, block, and inline-block elements in CSS with
examples.
Ans.

Inline (display: Inline-Block (display:


Property Block (display: block)
inline) inline-block)

Starts on a new
No Yes No
line?

No (only as wide as Yes (expands to full No (only as wide as


Takes full width?
content) width) content)

Height & Width


No (ignored) Yes Yes
Work?

Margin & Padding Partial (horizontal Yes (both horizontal & Yes (both horizontal &
Work? only) vertical) vertical)

1. Inline:
<html lang="en">
<head>

C.E., LDCE 6
220280107008 BHAYALA ABDULREHMAN

<style>
span {
background-color: lightblue;
width: 200px; /* Won't work */
padding: 10px; /* Works, but only horizontally */
}
</style>
</head>
<body>
<p>This is an <span>inline element</span> inside a paragraph.</p>
</body>
</html>
2. Block:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
background-color: lightcoral;
width: 300px;
height: 100px;
}
</style>
</head>
<body>
<div>This is a block element.</div>
<div>Another block element below.</div>
</body>

C.E., LDCE 7
220280107008 BHAYALA ABDULREHMAN

</html>
3. Inline Block:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.inline-block {
display: inline-block;
background-color: lightgreen;
width: 200px;
height: 100px;
}
</style>
</head>
<body>
<div class="inline-block">Box 1</div>
<div class="inline-block">Box 2</div>
</body>
</html>
Q.7) What are pseudo-classes in CSS? List some commonly used pseudo-classes and explain
their functions.
Ans. A pseudo-class in CSS is a special keyword added to a selector that defines a specific state of
an element. It allows styling elements based on user interactions, position in the document, or their
current state without modifying the HTML structure.
Syntax:
selector:pseudo-class {
property: value;
}

C.E., LDCE 8
220280107008 BHAYALA ABDULREHMAN

Pseudo-Class Description Example


:hover Styles an element when hovered over. a:hover { color: red; }
Styles an element when it is focused (e.g., clicked
:focus input:focus { border-color: blue; }
input field).
button:active { background-color:
:active Styles an element when it is being clicked.
green; }
:first-child Targets the first child of a parent element. p:first-child { font-weight: bold; }
:last-child Targets the last child of a parent element. p:last-child { color: blue; }
:nth-child(n) Targets the nth child of a parent. li:nth-child(2) { color: red; }
:nth-of- p:nth-of-type(3) { text-decoration:
Targets the nth child of a specific type.
type(n) underline; }
:not(selector) Excludes elements from styling. p:not(.special) { color: gray; }
input:checked { border: 2px solid
:checked Styles checked checkboxes or radio buttons.
green; }
button:disabled { background-color:
:disabled Styles disabled input fields.
gray; }

Q.8) How do you center a div element horizontally and vertically using CSS?
Ans. Flexbox is the easiest and most modern way to center a div.
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 100vh; /* Full viewport height */
background-color: lightgray;
}
Q.9) What is the difference between the visibility: hidden and display: none properties in CSS?
Ans.

Property Element Visible? Takes Up Space? Affects Layout?

visibility: hidden; No Yes No

display: none; No No Yes (removes element)

C.E., LDCE 9
220280107008 BHAYALA ABDULREHMAN

CO-2: Develop the dynamic web pages using HTML, CSS and JavaScript
applying web design principles to make pages effective.

Q.1) Explain the difference between let, const, and var in JavaScript. When would you use
each?
Ans.

Feature var let const


Scope Function-scoped Block-scoped Block-scoped
Hoisting Hoisted with undefined Hoisted but not initialized Hoisted but not initialized
Re-declaration Allowed Not allowed in the same scope Not allowed in the same scope
Re-assignment Allowed Allowed Not allowed
Mutability Mutable Mutable Immutable (for primitive values)

1. var (Function Scoped)


• Use case: When you need a function-scoped variable (older JavaScript versions).
2. let (Block Scoped)
• Use case: When you need a mutable variable within a block scope.
3. const (Block Scoped & Immutable)
• Use case: When you need a variable that should not be reassigned.

Q.2) What is a closure in JavaScript? Provide an example to illustrate how closures work.
Ans. A closure in JavaScript is a function that remembers the variables from its outer scope even after the
outer function has finished executing. This allows inner functions to access and manipulate variables from
an enclosing function's scope, even after the enclosing function has returned.
function outerFunction(name) {
let greeting = "Hello, ";

return function innerFunction() {


console.log(greeting + name); // Accessing 'greeting' from outer scope
};
}

const greetJohn = outerFunction("John");

C.E., LDCE 10
BHAYALA ABDULREHMAN
220280107008

greetJohn(); // Output: Hello, John

Explanation:
• outerFunction("John") executes, storing "Hello, " in greeting.
• It returns innerFunction, which remembers greeting and name even after outerFunction has
finished execution.
• When greetJohn() is called later, it still has access to greeting, demonstrating a closure.

Q.3) Explain the concept of asynchronous programming in JavaScript. How do setTimeout()


and setInterval() work?
Ans. Asynchronous programming in JavaScript allows tasks to be executed without blocking the main
thread. JavaScript is single-threaded, meaning it executes one task at a time. However, with asynchronous
programming, time-consuming operations (e.g., fetching data, timers, API calls) can run in the
background, allowing the main program to continue executing.
The setTimeout() function delays execution of a function by a specified time (in milliseconds). It
executes the function once after the delay.
console.log("Before setTimeout");
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
console.log("After setTimeout");
The setInterval() function repeatedly executes a function at a fixed time interval until explicitly
stopped.
let count = 1;
let interval = setInterval(() => {
console.log("Count:", count);
count++;
if (count > 5) {
clearInterval(interval); // Stops execution after 5 counts
}
}, 1000);

Q.4) What is the difference between == and === in JavaScript? Provide examples.

C.E., LDCE 11
BHAYALA ABDULREHMAN

220280107008

Ans.

Operator Type Comparison Type Converts Data Type?


== Equality Checks value only Yes (Type Coercion)
=== Strict Equality Checks both value & type No

Eg. Of == :
console.log(5 == "5"); // true (string "5" is converted to number 5)
console.log(0 == false); // true (false is converted to 0)
console.log(null == undefined); // true (both are treated as "empty" values)
console.log(1 == true); // true (true is converted to 1)
Eg. Of === :
console.log(5 === "5"); // false (different types: number vs. string)
console.log(0 === false); // false (different types: number vs. boolean)
console.log(null === undefined); // false (different types)
console.log(1 === true); // false (number vs. boolean)
console.log(5 === 5); // true (same type and value)

Q.5) Describe the event bubbling and event capturing phases in JavaScript event handling.
How do you stop event propagation?
Ans. 1. Event Bubbling (Default Behavior)
• The event starts from the target element and bubbles upward through its parent elements.
• Inner elements trigger events first, followed by their ancestors.
Example of Event Bubbling:
<div id="parent" style="padding: 20px; background-color: lightblue;">
<button id="child">Click Me</button>
</div>
<script>
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent Div Clicked!");

C.E., LDCE 12
220280107008 BHAYALA ABDULREHMAN

});
document.getElementById("child").addEventListener("click", () => {
console.log("Child Button Clicked!");
});
</script>
Output when clicking the button (child):
Child Button Clicked!
Parent Div Clicked!
2. Event Capturing (Trickling Down)
• The event starts from the root element and trickles down to the target element.
• To enable capturing, pass { capture: true } as the third argument in addEventListener().
Example of Event Capturing:
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent Div Clicked!");
}, true); // Capturing mode

document.getElementById("child").addEventListener("click", () => {
console.log("Child Button Clicked!");
}, true); // Capturing mode
Output when clicking the button (child):
Parent Div Clicked!
Child Button Clicked!
• event.stopPropagation()
Stops event bubbling or capturing at the current level.
Example:
document.getElementById("child").addEventListener("click", (event) => {
console.log("Child Button Clicked!");
event.stopPropagation(); // Stops the event from reaching the parent

C.E., LDCE 13
220280107008
BHAYALA ABDULREHMAN

});

Q.6) How do you handle form validation using JavaScript? Provide an example of client-side
validation for an email input.
Ans. Types of Form Validation
1. Built-in HTML Validation (e.g., required, pattern, minlength)
2. JavaScript Client-Side Validation (custom logic for checking input)
3. Server-Side Validation (for security, as JavaScript can be bypassed)
Example: Client-Side Email Validation
<html lang="en">
<head>
<title>Email Validation</title>
<style>
.error { color: red; }
</style>
</head>
<body>

<form id="myForm">
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<span id="emailError" class="error"></span>
<br><br>
<button type="submit">Submit</button>
</form>

<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent form from submitting

let emailInput = document.getElementById("email");


let emailError = document.getElementById("emailError");
let emailValue = emailInput.value.trim();

// Regular expression for email validation


let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

if (emailValue === "") {


emailError.textContent = "Email is required!";
} else if (!emailPattern.test(emailValue)) {
emailError.textContent = "Invalid email format!";

C.E., LDCE 14
220280107008
BHAYALA ABDULREHMAN

} else {
emailError.textContent = "";
alert("Form submitted successfully!");
// You can submit the form using `this.submit();`
}
});
</script>
</body>
</html>

Q.7) Explain the difference between synchronous and asynchronous JavaScript operations.
What is the purpose of Promise in handling asynchronous code?
Ans. 1️ Synchronous JavaScript (Blocking)
• Code runs line by line, waiting for each operation to finish before proceeding.
• Blocking behavior can make the application unresponsive.
Example: Synchronous Code
console.log("Step 1");
alert("Blocking Alert!"); // Execution pauses here until user closes alert
console.log("Step 2"); // Runs only after alert is closed
Output:
Step 1
(Alert appears)
Step 2 (Runs after alert is closed)

2️ Asynchronous JavaScript (Non-Blocking)


• Executes tasks in the background while continuing other operations.
• Uses callbacks, Promises, and async/await to handle tasks like:
o Fetching data from APIs
o Timers (setTimeout, setInterval)
o File I/O operations
Example: Asynchronous Code
console.log("Step 1");
setTimeout(() => {

C.E., LDCE 15
BHAYALA ABDULREHMAN
220280107008

console.log("Step 2 (Runs after 2 seconds)");


}, 2000);
console.log("Step 3"); // Doesn't wait for setTimeout()
Output:
Step 1
Step 3
Step 2 (Runs after 2 seconds)
setTimeout() runs in the background, allowing Step 3 to execute immediately.
Purpose of Promises in Asynchronous JavaScript
A Promise represents a future value (a task that hasn't completed yet). It helps manage asynchronous
operations in a cleaner, more structured way than callbacks.
Promise States:
1. Pending → Initial state, operation not completed
2. Fulfilled (Resolved) → Operation successful (.then())
3. Rejected → Operation failed (.catch())
Example: Using Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let success = true; // Change to `false` to simulate error
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Error fetching data!");
}
}, 2000);
});
}
console.log("Fetching data...");

C.E., LDCE 16
220280107008 BHAYALA ABDULREHMAN

fetchData()
.then((message) => console.log(message)) // Runs if resolved
.catch((error) => console.error(error)); // Runs if rejected
console.log("Other operations continue...");
Output:
Fetching data...
Other operations continue...
(Data fetched successfully! after 2 seconds)

Q.8) What are JavaScript arrays? How would you add, remove, and modify elements in an
array? Provide examples.

Ans. An array in JavaScript is a data structure used to store multiple values in a single variable. Arrays
can hold different data types, including numbers, strings, objects, and even other arrays (nested arrays).

Declaring an Array
let fruits = ["Apple", "Banana", "Cherry"]; // Array of strings
let numbers = [10, 20, 30, 40]; // Array of numbers
let mixed = ["Text", 100, true, { key: "value" }]; // Mixed data types

Adding Elements to an Array


1️ push() – Add to End
fruits.push("Mango");
console.log(fruits); // ["Apple", "Banana", "Cherry", "Mango"]
2️ unshift() – Add to Beginning
fruits.unshift("Grapes");
console.log(fruits); // ["Grapes", "Apple", "Banana", "Cherry", "Mango"]
3️ Using Index (Manual Addition)
fruits[5] = "Pineapple"; // Adds at index 5
console.log(fruits); // ["Grapes", "Apple", "Banana", "Cherry", "Mango", "Pineapple"]

Removing Elements from an Array


1️ pop() – Remove Last Element
fruits.pop();
console.log(fruits); // ["Grapes", "Apple", "Banana", "Cherry"]
2️ shift() – Remove First Element
fruits.shift();

C.E., LDCE 17
BHAYALA ABDULREHMAN
220280107008

console.log(fruits); // ["Apple", "Banana", "Cherry"]


3️ splice(index, count) – Remove at Specific Position
fruits.splice(1, 1); // Removes 1 element at index 1
console.log(fruits); // ["Apple", "Cherry"]

Modifying Elements in an Array


1️ Update Using Index
fruits[0] = "Mango";
console.log(fruits); // ["Mango", "Cherry"]
2️ splice(index, count, newElement) – Replace an Element
fruits.splice(1, 1, "Blueberry"); // Replace "Cherry" with "Blueberry"
console.log(fruits); // ["Mango", "Blueberry"]

Q.9) What is the difference between null and undefined in JavaScript?


Ans.

Feature null undefined


Intentional absence of any A variable that has been declared but has not
Definition
object value been assigned a value
object (due to a historical bug in
Type undefined
JavaScript)
Assigned manually to indicate Default value for uninitialized variables or
When is it Used?
"no value" missing object properties
Example Output in
console.log(null); // null console.log(undefined); // undefined
Console

Q.10) What is DOM manipulation? Write JavaScript code to change the content of a div
element when a button is clicked.

Ans. DOM (Document Object Model) manipulation is the process of dynamically changing the
structure, content, or style of an HTML document using JavaScript. It allows us to add, remove, or
modify elements and attributes in real-time.

Example: Changing Content of a <div> on Button Click

HTML + JavaScript Code

<!DOCTYPE html>
<html lang="en">

C.E., LDCE 18
220280107008
BHAYALA ABDULREHMAN

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation Example</title>
<style>
#content {
font-size: 20px;
color: blue;
padding: 10px;
}
</style>
</head>
<body>

<div id="content">Original Content</div>


<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("content").innerHTML = "Content Updated!";
}
</script>

</body>
</html>

C.E., LDCE 19
BHAYALA ABDULREHMAN
220280107008

CO-3: Develop the server side PHP scripts using various features for
creating customized web services.

Q.1) Explain the difference between include() and require() in PHP. When would you use
each function?
Ans.

Feature include() require()


Error Generates a warning (E_WARNING) if the Generates a fatal error (E_ERROR) if the
Handling file is missing but continues script execution. file is missing and stops script execution.
When the file is optional and the script should When the file is essential and the script
Use Case
continue running even if the file is missing. must not continue without it.

When to Use include() vs. require()?

Use include() when: Use require() when:


The file is not critical (e.g., an optional The file is essential for the script to run (e.g., database
menu or sidebar). connection, authentication).
You want the script to continue even if You want the script to stop if the file is missing to prevent
the file is missing. errors.

Q.2) How do you connect to a MySQL database using PHP? Write a basic PHP script to
connect to a database and display a message if successful.

Ans. To connect to a MySQL database in PHP, we typically use the MySQLi (MySQL Improved)
extension or PDO (PHP Data Objects). Below is an example using MySQLi.

Basic PHP Script to Connect to MySQL Database

<?php
// Database connection details
$servername = "localhost"; // Server name (use an IP address or domain if remote)
$username = "root"; // Database username
$password = ""; // Database password (leave blank if no password)
$database = "test_db"; // Name of the database

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

C.E., LDCE 20
BHAYALA ABDULREHMAN
220280107008

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

echo "Connected successfully!";


?>

Q.3) What is a session in PHP? How do you create, access, and destroy a session in PHP?

Ans. A session in PHP is a way to store user information across multiple pages. Unlike cookies, session
data is stored on the server instead of the user's browser, making it more secure.

Sessions are commonly used for:


- User authentication (e.g., login/logout).
- Storing temporary data (e.g., shopping cart, form inputs).

<?php

session_start(); // Start the session

// Step 1: Create and store session variables

if (!isset($_SESSION["username"])) {

$_SESSION["username"] = "JohnDoe";

$_SESSION["role"] = "Admin";

echo "Session started and variables set.<br>";

} else {

echo "Welcome, " . $_SESSION["username"] . " (" . $_SESSION["role"] . ")<br>";

// Step 2: Access session data

echo "Session ID: " . session_id() . "<br>";

// Step 3: Destroy session on user action

if (isset($_GET['logout'])) {

C.E., LDCE 21
220280107008
BHAYALA ABDULREHMAN

session_unset(); // Remove all session variables

session_destroy(); // Destroy the session

echo "Session destroyed. Refresh the page to start a new session.";

exit();

?>

<a href="?logout=true">Logout (Destroy Session)</a>

Q.4) What is the purpose of $_GET and $_POST in PHP? Provide examples of how data can
be sent and received using these superglobals.
Ans.

Superglobal Purpose How Data is Sent Use Case


Used when data is not
$_GET Retrieves data from Appended in the URL
sensitive (e.g., search
the URL (example.com?name=John)
queries, filters)
Retrieves data sent Used when data is sensitive
$_POST Sent in the request body (hidden from
via HTTP POST (e.g., passwords, form
the URL)
request submissions)

Example: Using $_GET

Sending Data with $_GET

<form action="get_example.php" method="GET">


Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>

Receiving Data with $_GET (get_example.php)

<?php
if (isset($_GET["name"])) {
echo "Hello, " . htmlspecialchars($_GET["name"]);
} else {

C.E., LDCE 22
220280107008

echo "Please enter your name.";


}
?>

Example URL when submitting:

get_example.php?name=John

Example: Using $_POST

<form action="post_example.php" method="POST">


Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>

Receiving Data with $_POST (post_example.php)

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["name"])) {
echo "Hello, " . htmlspecialchars($_POST["name"]);
} else {
echo "Please enter your name.";
}
}
?>

Q.5) Explain the concept of form handling in PHP. How do you handle file uploads using
PHP?

Ans. Form handling in PHP involves collecting, processing, and validating user input from HTML forms.
PHP uses the $_GET, $_POST, and $_FILES superglobals to manage form data.

Steps in Form Handling

1. Create an HTML form with input fields.


2. Send data to a PHP script using POST or GET.
3. Validate and process the submitted data.
4. Display results or perform actions like database insertion.
5. Handle file uploads if necessary.

File Upload Example

C.E., LDCE 23
220280107008 BHAYALA ABDULREHMAN

HTML Form (upload.html)


<form action="upload.php" method="POST" enctype="multipart/form-data">
Select file: <input type="file" name="uploadedFile">
<input type="submit" value="Upload">
</form>
PHP Script to Process File (upload.php)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$targetDir = "uploads/"; // Folder to store files
$targetFile = $targetDir . basename($_FILES["uploadedFile"]["name"]);
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

// Check file size (max 2MB)


if ($_FILES["uploadedFile"]["size"] > 2000000) {
echo "File is too large.";
} elseif ($fileType != "jpg" && $fileType != "png" && $fileType != "pdf") {
echo "Only JPG, PNG, and PDF files are allowed.";
} else {
// Move file to target directory
if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile)) {
echo "File uploaded successfully: " .
htmlspecialchars(basename($_FILES["uploadedFile"]["name"]));
} else {
echo "Error uploading file.";
}
}
}
?>
Q.6) What are cookies in PHP? How do you create and retrieve cookies in PHP?

C.E., LDCE 24
220280107008 BHAYALA ABDULREHMAN

Ans. A cookie is a small piece of data stored on the user's browser. PHP uses cookies to store information
like user preferences, login status, or session identifiers.

Key Features of Cookies

• Stored on the client-side (browser).


• Can hold small amounts of data (up to 4KB).
• Used for tracking and personalization (e.g., "Remember Me" login).
• Expire after a set time or when the browser closes.

<?php
$cookie_name = "username";
$cookie_value = "JohnDoe";
$cookie_expiration = time() + (86400 * 7); // Cookie expires in 7 days

// Set the cookie


if (!isset($_COOKIE[$cookie_name])) {
setcookie($cookie_name, $cookie_value, $cookie_expiration, "/");
$message = "Cookie has been set!";
} else {
$message = "Welcome back, " . $_COOKIE[$cookie_name];
}

// Delete the cookie when requested


if (isset($_GET["delete"])) {
setcookie($cookie_name, "", time() - 3600, "/"); // Expire 1 hour ago
$message = "Cookie has been deleted!";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>

C.E., LDCE 25
220280107008 BHAYALA ABDULREHMAN

<title>PHP Cookie Example</title>


</head>
<body>
<h2>PHP Cookie Example</h2>
<p><?php echo $message; ?></p>
<a href="?delete=true"><button>Delete Cookie</button></a>
</body>
</html>

Q.7) What is the difference between foreach(), for(), and while() loops in PHP? When would
you use each?
Ans. 1️ foreach() Loop

Best for looping through arrays


foreach() is specifically used to iterate over arrays or objects.

Syntax:

foreach ($array as $value) {


// Code to execute
}

Example:

<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>

🔹 When to Use?

• When working with arrays or associative arrays.


• When no need for an index counter.

2️ for() Loop

C.E., LDCE 26
220280107008
BHAYALA ABDULREHMAN

Best when the number of iterations is known


Used when you know in advance how many times to loop.

Syntax:

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


// Code to execute
}

Example:

<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "<br>";
}
?>

🔹 When to Use?

• When you have a fixed number of iterations.


• Ideal for looping through numbers, ranges, or indexed arrays.

3️ while() Loop

Best when the number of iterations is unknown


Runs until a condition becomes false.

Syntax:

while (condition) {
// Code to execute
}

Example:

<?php
$number = 1;
while ($number <= 5) {
echo "Number: " . $number . "<br>";
$number++;
}
?>

🔹 When to Use?

C.E., LDCE 27
220280107008 BHAYALA ABDULREHMAN

• When you don’t know how many times to loop beforehand.


• Commonly used for reading files or database records.

Q.8) What is an associative array in PHP? How does it differ from an indexed array?

Ans. An associative array in PHP uses named keys (strings) instead of numbers to identify elements.

🔹 Example of an Associative Array:

<?php
$person = [
"name" => "John",
"age" => 25,
"city" => "New York"
];

echo $person["name"]; // Output: John


?>
Feature Indexed Array Associative Array
Key Type Numeric (0, 1, 2,..) Named keys ("name" => "John")
Usage Simple lists of values Key-value pairs (structured data)
Example $fruits[0] → "Apple" $person["name"] → "John"
Best for Ordered data, lists Structured data (objects, user info, etc.)

Q.9) What is the use of the isset() and empty() functions in PHP?
Ans.

Feature isset() empty()


Checks if a variable is set and not Checks if a variable is empty ("", 0, NULL,
Purpose
NULL false, [])
Returns false
Unset variables, NULL "", 0, NULL, false, [], "0"
for
Validating form inputs or checking meaningful
Best used for Avoiding "undefined variable" errors
values

Q.10) Explain the concept of object-oriented programming (OOP) in PHP. How do you
create a class and instantiate objects in PHP?

C.E., LDCE 28
220280107008 BHAYALA ABDULREHMAN

Ans. Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to
structure code. It helps in organizing complex programs by encapsulating data and behavior together.

🔹 Key OOP Concepts in PHP

1. Class – A blueprint for creating objects.


2. Object – An instance of a class.
3. Properties – Variables that belong to a class (like attributes).
4. Methods – Functions inside a class (behavior of the object).
5. Encapsulation – Protecting data by controlling access to it.
6. Inheritance – A class can inherit properties and methods from another class.
7. Polymorphism – Ability to use a method in different ways.

Creating a Class and Instantiating Objects

🔹 Step 1: Define a Class

<?php
class Car {
// Properties
public $brand;
public $color;
// Constructor Method
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
// Method to Display Car Details
public function displayCar() {
echo "This car is a $this->color $this->brand.<br>";
}
}
?>

🔹 Step 2: Create Objects (Instantiate a Class)

<?php
// Creating objects of Car class
$car1 = new Car("Toyota", "Red");
$car2 = new Car("Honda", "Blue");
// Calling method
$car1->displayCar(); // Output: This car is a Red Toyota.
$car2->displayCar(); // Output: This car is a Blue Honda.
?>

C.E., LDCE 29
220280107008 BHAYALA ABDULREHMAN

CO-4: Write the server side scripts for designing web based services with
database connectivity.

Q.1) What are the functions used to connect to a MySQL database in PHP?
Ans.

Function Type Features


mysqli_connect() Procedural Basic, fast, good for small scripts
new mysqli() Object-Oriented Better structure, ideal for OOP projects
PDO Object-Oriented Secure, supports multiple databases

Q.2) Write a PHP script to connect to a MySQL database using mysqli and check if the
connection is successful.
Ans. <?php
// Database configuration
$servername = "localhost";
$username = "root";
$password = ""; // Update if your MySQL has a password
$database = "your_database_name"; // Replace with your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
?>

Q.3) Explain the difference between mysqli and PDO for database connectivity in PHP.
Which one is preferred for new projects and why?

C.E., LDCE 30
220280107008 BHAYALA ABDULREHMAN

Ans. 1️ MySQLi (MySQL Improved)

Features:
- Supports only MySQL databases
- Offers both Procedural & Object-Oriented approaches
-Supports prepared statements (better security)
- Has faster execution for simple queries

Limitations:
-Works only with MySQL (not portable to other databases)
-Slightly less flexible than PDO
-Lacks advanced database abstraction

Example (Object-Oriented MySQLi):

$mysqli = new mysqli("localhost", "root", "", "test_db");

if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}

echo "Connected successfully!";

2️ PDO (PHP Data Objects)

Features:
-Works with multiple databases (MySQL, PostgreSQL, SQLite, etc.)
-Uses only Object-Oriented approach
-Fully supports prepared statements (prevents SQL injection)
-Provides advanced error handling using exceptions

Limitations:
-Can be slightly slower than MySQLi for simple queries
-More complex syntax compared to MySQLi

Example (PDO Connection with Error Handling):

try {
$pdo = new PDO("mysql:host=localhost;dbname=test_db", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}

C.E., LDCE 31
BHAYALA ABDULREHMAN
220280107008

PDO is recommended for new projects because:

1. Database Flexibility: Works with multiple databases (MySQL, PostgreSQL, SQLite, etc.),
making future migrations easier.
2. Better Security: Uses prepared statements by default, preventing SQL injection.
3. Advanced Error Handling: Uses exceptions for better debugging and error management.

Q.4) What is the purpose of the mysqli_select_db() function in PHP? Provide an example.
Ans. The mysqli_select_db() function is used to select a specific database after establishing a connection
to a MySQL server. It allows you to switch between multiple databases without reconnecting.
<?php
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Select a database
if (mysqli_select_db($conn, "test_database")) {
echo "Database selected successfully!";
} else {
echo "Failed to select database: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>

C.E., LDCE 32
220280107008 BHAYALA ABDULREHMAN

Q.5) Write a PHP script to insert a record into a MySQL database using mysqli (
without prepared statements).
Ans. <?php
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_database";
// Connect to MySQL
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Insert query
$name = "John Doe";
$email = "john@example.com";
$mobile = "9876543210";

$sql = "INSERT INTO users (name, email, mobile) VALUES ('$name', '$email', '$mobile')";

// Execute the query


if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully!";
} else {
echo "Error inserting record: " . mysqli_error($conn);
}
// Close connection

C.E., LDCE 33
220280107008 BHAYALA ABDULREHMAN

mysqli_close($conn);
?>

Q.6) What is SQL injection? How can you prevent SQL injection when inserting data into a
database in PHP?
Ans. SQL Injection is a web security vulnerability where an attacker manipulates an SQL query by
injecting malicious SQL code into an input field. This can allow unauthorized access, data leaks, or even
deletion of entire databases.

How to Prevent SQL Injection?

1️ Use Prepared Statements (Best Practice)

Prepared statements separate SQL logic from user input, preventing SQL injection.

Secure Code with Prepared Statements

php
CopyEdit
<?php
$conn = mysqli_connect("localhost", "root", "", "test_database");

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

$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");


$stmt->bind_param("ss", $username, $password); // "ss" means both are strings
$stmt->execute();

$result = $stmt->get_result();
?>

Why it’s safe? The user input is treated as data, not part of the SQL query.

2️ Use mysqli_real_escape_string() (Less Secure)

This function escapes special characters to prevent SQL injection.

php
CopyEdit
$username = mysqli_real_escape_string($conn, $_POST['username']);

C.E., LDCE 34
BHAYALA ABDULREHMAN
220280107008

$password = mysqli_real_escape_string($conn, $_POST['password']);

$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";

Warning: This is better than nothing, but prepared statements are much safer.

3️ Validate & Sanitize User Input

• Use filter_var() for emails:

php
CopyEdit
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

• Use ctype_alnum() for usernames:

php
CopyEdit
if (!ctype_alnum($_POST['username'])) {
die("Invalid username!");
}

Q.7) Write a PHP script to fetch all records from the users table using mysqli and display
them in a table.
Ans. <?php
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_database";
// Connect to MySQL
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

C.E., LDCE 35
BHAYALA ABDULREHMAN
220280107008

// SQL query to fetch all users


$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Records</title>
</head>
<body>
<h2 style="text-align: center;">User Records</h2>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
</tr>
<?php
// Fetch and display records
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>
<td>" . $row["id"] . "</td>
<td>" . $row["name"] . "</td>
<td>" . $row["email"] . "</td>

C.E., LDCE 36
BHAYALA ABDULREHMAN
220280107008

<td>" . $row["mobile"] . "</td>


</tr>";
}
} else {
echo "<tr><td colspan='4' style='text-align:center;'>No records found</td></tr>";
}
?>
</table>
</body>
</html>
<?php
// Close the database connection
mysqli_close($conn);
?>

Q.8) Write a PHP script to fetch a single record from the users table by a specific user_id
using mysqli.
Ans. <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_database";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$sql = "SELECT * FROM users WHERE id = $user_id";

C.E., LDCE 37
BHAYALA ABDULREHMAN
220280107008

$result = mysqli_query($conn, $sql);


$user = mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Details</title>
</head>
<body>
<?php if ($user): ?>
<h2>User Details</h2>
<p><strong>ID:</strong> <?php echo $user['id']; ?></p>
<p><strong>Name:</strong> <?php echo htmlspecialchars($user['name']); ?></p>
<p><strong>Email:</strong> <?php echo htmlspecialchars($user['email']); ?></p>
<p><strong>Mobile:</strong> <?php echo htmlspecialchars($user['mobile']); ?></p>
<?php else: ?>
<p>No user found with this ID.</p>
<?php endif; ?>
</body>
</html>
<?php
mysqli_close($conn);
?>

Q.9) Write a PHP script to update a record in the users table using mysqli (without
prepared statements).
Ans. <?php

C.E., LDCE 38
220280107008 BHAYALA ABDULREHMAN

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_database";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$sql = "SELECT * FROM users WHERE id = $user_id";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$update_sql = "UPDATE users SET name='$name', email='$email', mobile='$mobile' WHERE
id=$user_id";
echo mysqli_query($conn, $update_sql) ? "Record updated successfully." : "Error updating
record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update User</title>

C.E., LDCE 39
220280107008
BHAYALA ABDULREHMAN

</head>
<body>
<h2>Update User</h2>
<?php if ($user): ?>
<form method="post">
<label>Name:</label>
<input type="text" name="name" value="<?php echo htmlspecialchars($user['name']); ?>"
required><br><br>
<label>Email:</label>
<input type="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>"
required><br><br>
<label>Mobile:</label>
<input type="text" name="mobile" value="<?php echo htmlspecialchars($user['mobile']);
?>" required><br><br>
<button type="submit">Update</button>
</form>
<?php else: ?>
<p>User not found.</p>
<?php endif; ?>
</body>
</html>

Q.10) What is a stored procedure, and how is it different from regular SQL queries?

Ans. A stored procedure is a precompiled collection of SQL statements that is stored in a database and
can be executed multiple times with different parameters. It helps in automating tasks, improving
performance, and increasing security.

C.E., LDCE 40
220280107008 BHAYALA ABDULREHMAN

Feature Stored Procedure Regular SQL Query

A predefined SQL script stored in the A single SQL command or query executed
Definition
database manually

Execution Called using CALL procedure_name() Directly executed in the SQL engine

Faster (precompiled, reduces parsing


Performance Slower (parsed and compiled every time)
overhead)

Can be reused multiple times with different


Reusability Needs to be rewritten for different cases
inputs

Provides controlled access to database Users must have direct access to the database
Security
operations tables

Can handle multiple queries, loops,


Complexity Executes only a single query at a time
conditions

Q.11) Explain how you would pass parameters to a stored procedure in MySQL using PHP.
Ans. Steps to Pass Parameters

1. Create a Stored Procedure in MySQL.


2. Establish a Database Connection in PHP.
3. Prepare and Execute the CALL Statement with parameters.
4. Fetch and Display the Result.

Example: Fetch User by ID Using a Stored Procedure

Step 1: Create a Stored Procedure in MySQL

DELIMITER //
CREATE PROCEDURE GetUserById(IN user_id INT)
BEGIN
SELECT * FROM users WHERE id = user_id;
END //
DELIMITER ;

Step 2: Write PHP Code to Call the Stored Procedure

C.E., LDCE 41
220280107008 BHAYALA ABDULREHMAN

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }

$user_id = 3; // Example: Fetch user with ID = 3


$sql = "CALL GetUserById(?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if ($user) {
echo "User Found: " . $user['name'] . " - " . $user['email'];
} else {
echo "No user found.";
}

$stmt->close();
$conn->close();
?>

Q.12) What is the difference between a function and a stored procedure in MySQL? Can a
stored procedure return a value?
Ans.

Feature Stored Procedure Function


A set of SQL statements that perform a A set of SQL statements that return a
Definition
specific task single value
Can return multiple values using OUT Always returns a single value using
Returns Value
parameters RETURN
Used for complex operations like inserting, Used for calculations and returning
Usage
updating, or deleting data computed values
Used inside SQL queries like
Call Method Called using CALL procedure_name()
SELECT function_name()
Can Modify Yes, it can use INSERT, UPDATE, and No, it cannot modify data (only read
Data? DELETE data)
Can Use in No, stored procedures cannot be used in Yes, functions can be used inside
SELECT? SELECT statements SELECT queries

C.E., LDCE 42
220280107008 BHAYALA ABDULREHMAN

CO-5: Develop a web application using advanced web programming


features including AJAX and JQuery using concepts of Web API.

Q.1) What is the difference between synchronous and asynchronous web programming?
Ans.

Feature Synchronous Asynchronous


Code executes without waiting, moving to the
Code executes line by line, waiting
Execution next task while waiting for the previous one to
for each operation to complete
finish
Yes, it blocks execution until the
Blocking? No, it does not block execution
task completes
Slower if tasks take too long
Performance Faster, as multiple tasks can run in parallel
(waiting for each task to finish)
User Can cause page freezing in long
Improves responsiveness, preventing UI freezes
Experience operations
Example PHP, Python (traditional), JavaScript (Node.js), Python (asyncio), AJAX
Languages JavaScript (in blocking mode) requests
Suitable for simple tasks where Needed for tasks like API calls, file reading, and
Use Case
waiting is acceptable database operations

Q.2) Why is asynchronous programming important in modern web applications?


Ans.

Benefit Explanation
Prevents the application from freezing while waiting for tasks like API calls
1️ Non-Blocking Execution
or database queries.
2️ Improved Performance Multiple tasks can execute simultaneously, reducing overall processing time.
Ensures smooth UI interactions by running background tasks without
3️ Better User Experience
affecting user interactions.
Enables live notifications, chat systems, and stock price updates without
4️ Real-Time Updates
page reloads.
5️ Efficient Resource Servers can handle multiple requests at once (important for Node.js and
Utilization high-traffic applications).
6️ Faster Data Fetching Speeds up API requests and database queries, making web pages load faster.

Q.3) Explain the concept of an event loop in asynchronous programming.

C.E., LDCE 43
220280107008 BHAYALA ABDULREHMAN

Ans. The event loop is a mechanism in JavaScript and Node.js that allows non-blocking execution of
tasks. It ensures that JavaScript can handle multiple operations without freezing the application.

How the Event Loop Works?

1️ Call Stack – Executes synchronous code line by line.


2️ Web APIs – Sends async tasks (e.g., setTimeout, fetch()) to the browser.
3️ Callback Queue – Stores completed async callbacks.
4️ Event Loop – Moves tasks from the queue to the call stack when it's empty.

Q.4) What are the key benefits of using asynchronous web programming in web
development?

Ans.

Benefit Explanation
Allows tasks to run in the background while other operations
1️ Non-Blocking Execution
continue.
2️ Faster Performance Multiple operations can execute simultaneously, reducing wait time.
3️ Better User Experience Keeps the UI responsive, preventing page freezing.
4️ Efficient API Calls Handles multiple API requests without waiting for each to finish.
5️ Real-Time Updates Enables live chat, notifications, stock prices, and dashboards.
Handles many requests efficiently, making it ideal for high-traffic
6️ Scalability
apps.
7️⃣ Improved Resource Servers can process multiple requests simultaneously, improving
Utilization speed.

Q.5) What are some challenges associated with asynchronous programming?

Ans.

Challenge Explanation Solution


Too many nested callbacks make code Use Promises or Async/Await to simplify
1️ Callback Hell
unreadable. code.
2️ Debugging Use proper logging and debugging tools
Errors are harder to trace in async code.
Difficulty like console.log() or breakpoints.

C.E., LDCE 44
220280107008 BHAYALA ABDULREHMAN

Challenge Explanation Solution


3️ Race Multiple async tasks accessing shared
Use locks, mutexes, or queue mechanisms.
Conditions resources can cause conflicts.
4️ Error Errors in async code may not be caught Use .catch() with Promises or try-catch with
Handling properly. Async/Await.
5️ Ordering Tasks may complete in an unexpected Use Promise chaining or async/await to
Issues order. maintain order.
6️ Memory Unmanaged async tasks may consume Always clear intervals, close connections,
Leaks excess memory. and handle timeouts properly.

Q.6) What is AJAX and how does it work?

Ans. AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to update
without reloading by sending and receiving data asynchronously from a server in the background.

How Does AJAX Work?

AJAX works by using the XMLHttpRequest object (or Fetch API) to send and receive data from a web
server asynchronously.

Steps in AJAX Process

1️ User Action – A user triggers an event (e.g., button click).


2️ AJAX Request – JavaScript sends a request to the server.
3️ Server Processing – The server processes the request and returns a response.
4️ AJAX Response – JavaScript updates the webpage without refreshing.

Q.7) What are the advantages of using AJAX in web applications?

Ans.

Advantage Explanation
Only updates specific parts of a page instead of reloading the entire
1️ Faster Page Load
page.
2️ Improved User Experience Provides smooth interactions (e.g., live search, auto-suggestions).
3️ Reduced Server Load Sends and retrieves only necessary data, saving bandwidth.
4️ Asynchronous Processing Fetches data in the background while users interact with the page.
5️ Dynamic Content Updates Enables real-time features like notifications, chat, and live updates.

C.E., LDCE 45
BHAYALA ABDULREHMAN
220280107008

Advantage Explanation
6️ Better Performance Reduces unnecessary data transfer and speeds up responses.
7️ Cross-Browser Compatibility Works with modern browsers using XMLHttpRequest or fetch().
8️ Supports Multiple Data
Can handle JSON, XML, HTML, or plain text.
Formats

Q.8) Explain the role of XMLHttpRequest and fetch() in AJAX.

Ans. AJAX (Asynchronous JavaScript and XML) allows web applications to send and receive data from
a server without reloading the page. The two main ways to perform AJAX requests in JavaScript are:

1️ XMLHttpRequest (Old Method)


2️ fetch() API (Modern Method)

XMLHttpRequest (XHR) - Traditional Approach

The XMLHttpRequest object allows JavaScript to communicate with a server asynchronously. It was the
first method used for AJAX but has a complex syntax.

Example: AJAX with XMLHttpRequest

let xhr = new XMLHttpRequest();


xhr.open("GET", "data.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send();

Q.9) What are the common status codes returned by AJAX requests, and what do they
signify?

Ans. When making an AJAX request using XMLHttpRequest or fetch(), the server responds with an
HTTP status code that indicates the success or failure of the request.

Status Code Category Meaning


Request is received and processing
1XX (Informational)
continues.

C.E., LDCE 46
BHAYALA ABDULREHMAN
220280107008

Status Code Category Meaning


100 Continue Informational Request is okay, continue sending data.
101 Switching Server is changing protocols (e.g., HTTP to
Informational
Protocols WebSocket).

Q.10) What is jQuery and how does it simplify working with AJAX?

Ans. jQuery is a lightweight JavaScript library that simplifies HTML document traversal, event
handling, animations, and AJAX operations. It provides an easier way to interact with the DOM and make
AJAX requests with less code compared to vanilla JavaScript.

How jQuery Simplifies AJAX?

Instead of writing long XMLHttpRequest or fetch() code, jQuery provides a simple, cleaner syntax for
making AJAX requests.

-Less Code & More Features


-Handles Errors & Responses Easily
-Supports Different Request Methods (GET, POST, etc.)
-Automatic JSON Handling

Q.11) What is the difference between the $.get() and $.post() methods in jQuery?

Ans.

Feature $.get() $.post()


Request Type GET POST
Purpose Used to retrieve data from a server. Used to send data to a server.
Data Data is sent in the URL (query Data is sent in the request body (hidden from
Visibility parameters). URL).
Security Less secure (data is visible in the URL). More secure (data is sent in the request body).
Yes, GET requests can be cached by
Cacheable No, POST requests are not cached.
browsers.
Has a URL length limit (varies by
Data Limit No strict data limit.
browser).
Use Case Fetching public data (e.g., search results). Submitting forms, login, saving data.

C.E., LDCE 47
220280107008 BHAYALA ABDULREHMAN

Q.12) What are the benefits of using jQuery for AJAX requests instead of using vanilla
JavaScript?

Ans.

Benefit jQuery AJAX Vanilla JavaScript


Shorter Code Requires fewer lines of code. More lines of code are needed.
Uses easy-to-read methods like Requires fetch() or XMLHttpRequest with
Simpler Syntax
$.get(), $.post(), and $.ajax(). callbacks.
Automatic JSON Automatically converts JSON
Requires manual response.json() parsing.
Handling responses.
Built-in Error Provides .fail() and error: Requires try...catch for fetch(), and
Handling handlers. manual onerror for XMLHttpRequest.
Cross-Browser Works well in older browsers (e.g., Some features (like fetch()) are not
Compatibility IE11). supported in older browsers.
Allows method chaining (e.g.,
Chaining Support Vanilla JS requires separate .then() calls.
.done(), .fail()).
Less Boilerplate No need for complex event handling Requires manual request setup (headers,
Code or manual request setup. methods, etc.).

Q.13) Explain the difference between synchronous and asynchronous behavior in jQuery's
AJAX functions.

Ans.

Feature Synchronous AJAX Asynchronous AJAX


Blocks script execution until the request Runs in the background without
Execution
completes. blocking.
UI
Freezes the UI (bad experience). Keeps the UI responsive.
Responsiveness
Faster (continues executing other
Performance Slower (browser waits for response).
tasks).
Usage Deprecated, not recommended. Default & recommended.

Q.14) What is a web service, and how does it differ from an API?

Ans. A web service is a network-based service that allows applications to communicate over the internet
using standard protocols like HTTP, SOAP, and REST.

C.E., LDCE 48
220280107008 BHAYALA ABDULREHMAN

Feature Web Service API


A service that allows communication A set of rules for communication between
Definition
over a network. software components.
Protocol Used Uses HTTP, SOAP, REST. Can use HTTP, WebSocket, TCP, etc.
Data Format Mostly XML, JSON, or SOAP. Can use JSON, XML, YAML, etc.
Requires Internet? Yes (since it's web-based). No (APIs can be offline or online).
All APIs are Web
No. Yes, web services are a type of API.
Services?

Q.15) What is REST (Representational State Transfer), and how is it used in API
development?

Ans. REST is an architectural style used for building web services and APIs that follow a stateless, client-
server model. It defines a set of constraints that improve scalability, simplicity, and interoperability of web
services.

HTTP Method Purpose Example Endpoint Description


GET Read Data /users Fetch all users
POST Create Data /users Add a new user
PUT Update Data /users/1 Update user with ID 1
DELETE Delete Data /users/1 Remove user with ID 1

Q.16) Explain the basic HTTP methods (GET, POST, PUT, DELETE) used in RESTful API
development.

Ans. 1. GET (Retrieve Data)

• Used to fetch data from the server.


• No request body, only parameters in the URL.
• Safe & idempotent (does not modify data).

Example: Get all users

GET /users HTTP/1.1


Host: api.example.com

Response (JSON):

C.E., LDCE 49
220280107008 BHAYALA ABDULREHMAN

json
CopyEdit
[
{ "id": 1, "name": "John Doe", "email": "john@example.com" },
{ "id": 2, "name": "Jane Doe", "email": "jane@example.com" }
]

2. POST (Create Data)

• Used to send data to the server to create a new resource.


• Request body contains the data in JSON format.
• Not idempotent (multiple requests create multiple records).

Example: Create a new user

POST /users HTTP/1.1


Host: api.example.com
Content-Type: application/json

{
"name": "Alice",
"email": "alice@example.com"
}

Response:

{
"message": "User created successfully",
"id": 3
}

3. PUT (Update Data)

• Used to update an existing resource.


• Requires the entire resource data in the request body.
• Idempotent (repeating the request produces the same result).

Example: Update user with ID 1

PUT /users/1 HTTP/1.1


Host: api.example.com
Content-Type: application/json
{
"name": "John Smith",

C.E., LDCE 50
220280107008 BHAYALA ABDULREHMAN

"email": "johnsmith@example.com"
}

Response:

{
"message": "User updated successfully"
}

4. DELETE (Remove Data)

• Used to delete a resource from the server.


• No request body required.
• Idempotent (deleting the same resource multiple times has no extra effect).

Example: Delete user with ID 1

DELETE /users/1 HTTP/1.1


Host: api.example.com

Response:

{
"message": "User deleted successfully"
}

C.E., LDCE 51

You might also like