Web Technology II
Web Technology II
$$
It stores environment variables like system paths, execution settings, and user-defined
values.
It is used to send and receive data asynchronously from a web server without reloading the
page.
xhr.setRequestHeader("Header-Name", "Header-Value");
i) Is a root element required for an XML file? If so, how many root elements are
required?
A controller handles requests, processes data, and loads views in the MVC architecture.
• String
• Number
• Boolean
• Undefined
• Null
• BigInt
• Symbol
f) Define DOM.
The Document Object Model (DOM) is a programming interface that represents an HTML
document as a tree structure where each element is a node. It allows JavaScript to interact
with and modify web pages.
i) What is CodeIgniter?
CodeIgniter is a PHP framework used for building web applications quickly. It follows the
MVC (Model-View-Controller) pattern and provides built-in libraries for common tasks
like database access and session management.
a) Which function is used to print an error message and exit from the current code?
The die() function is used to print an error message and stop script execution. Example:
c) XML Parser cannot alter documents or create new documents. Justify True or False.
True. XML parsers only read and process XML data; they cannot modify or generate new
XML documents.
d) What is DOM?
The Document Object Model (DOM) is a structured representation of an HTML/XML
document as a tree of elements, allowing JavaScript to manipulate web pages dynamically.
• var (function-scoped)
• let (block-scoped)
• const (block-scoped, cannot be reassigned)
f) What is jQuery?
jQuery is a JavaScript library that simplifies tasks like DOM manipulation, event handling,
animations, and AJAX calls.
header("Content-Type: application/json");
<book xmlns:x="https://example.com/books">
<x:title>XML Guide</x:title>
</book>
f) Whether the root element is required for an XML file? If so, how many root elements
are required?
Yes, an XML file must have one and only one root element that contains all other
elements.
console.log(isNaN("Hello")); // true
console.log(isNaN(123)); // false
h) What are different values of readyState property of XMLHttpRequest?
• XML is case-sensitive.
• It is self-descriptive (custom tags).
• It follows a hierarchical structure.
• XML tags must be properly nested and closed.
• It is used for data storage and transfer.
d) Justify True or False - XML Parser cannot alter documents or create new
documents.
True. XML parsers can read and process XML data but cannot modify or generate new
XML documents.
e) What is DOM?
The Document Object Model (DOM) represents an HTML/XML document as a structured
tree, allowing JavaScript to manipulate web pages dynamically.
g) What is jQuery?
jQuery is a JavaScript library that simplifies tasks like DOM manipulation, event handling,
animations, and AJAX calls.
h) What is CodeIgniter?
CodeIgniter is a PHP framework used for developing web applications using the MVC
(Model-View-Controller) pattern, known for its speed and simplicity.
redirect('home');
Q2
• Example:
Advantages:
Disadvantages:
session_start();
This function should be called at the beginning of the script before sending any output.
Since synchronous requests block further execution, they are not commonly used in modern
web applications.
e) What is page redirecting? Write the syntax of the function used for page redirection.
Page redirection automatically sends users to a different URL, either within the same website
or to an external link. It is useful for handling login authentication, error pages, or URL
changes. In PHP, the header() function is used for redirection:
header("Location: newpage.php");
exit();
The exit(); statement ensures that the script stops executing after redirection.
The $_SERVER array contains server and request information. Five key elements are:
A session allows storing user-specific data across multiple pages. Unlike cookies, session
data is stored on the server.
1. Start session:
session_start();
$_SESSION["username"] = "John";
session_start();
echo "Welcome " . $_SESSION["username"];
3. Destroy session:
session_destroy();
Example: When a user logs in, their username is stored in a session, allowing them to stay
logged in across different pages.
<library>
</library>
<library>
<book>
<title>XML Basics</title>
<author>John Doe</author>
</book>
</library>
User -> Browser (JavaScript) -> XMLHttpRequest -> Server -> Response -> Update
Page
Explanation:
1. User Action: A user interacts with the webpage (e.g., clicks a button).
2. JavaScript & XMLHttpRequest: JavaScript sends an asynchronous request to the
server using XMLHttpRequest.
3. Server Processing: The server processes the request and returns a response (e.g.,
JSON, XML).
4. Page Update: JavaScript updates the webpage without reloading.
a) List any four datatypes that JavaScript supports with its usage.
• Start a session:
session_start();
$_SESSION["user"] = "John"; // Store data in session
• Destroy a session:
session_start();
session_destroy(); // Ends the session
c) Draw AJAX web application model.
Explanation:
1. User Action – The user interacts with the webpage (e.g., clicks a button).
2. JavaScript & XMLHttpRequest – Sends an asynchronous request to the server.
3. Server Processing – The server handles the request and responds with data.
4. JavaScript Updates Page – The response updates the page without reloading.
d) What is MVC?
1. Single Root Element – An XML document must have one root element.
2. Proper Nesting – Tags must be correctly nested.
<book>
<title>XML Basics</title>
</book>
<name>John</name>
A session is a way to store user-specific data across multiple web pages. It helps track user
activity, such as login status and shopping cart details. Unlike cookies, session data is stored
on the server.
session_start();
$_SESSION["username"] = "John";
A well-formed XML document follows strict syntax rules to ensure correct parsing. It must
have a single root element that contains all other elements. All tags must be properly
nested and closed correctly. XML is case-sensitive, meaning <Title> and <title> are
different. Attribute values must be enclosed in quotes. Special characters like <, >, & must
be written using character entities (e.g., < for <). Following these rules ensures that the
XML document is readable and processable by parsers.
1. Alert Box (alert()) – Displays a message with an OK button. Used to show warnings
or notifications.
2. Confirm Box (confirm()) – Displays a message with OK and Cancel buttons. Used
to ask for user confirmation (e.g., deleting a record).
3. Prompt Box (prompt()) – Displays a message with a text input field, OK, and
Cancel buttons. Used to take user input.
Similarities:
In asynchronous mode, AJAX enables a web page to send a request to the server and
continue executing other tasks without waiting for the server’s response. This improves user
experience by allowing smooth interactions without freezing or reloading the page.
When an asynchronous request is made, the browser does not block other scripts from
running. Instead, it listens for the server’s response and processes it once received. This is
useful for real-time applications like chat systems, live notifications, and dynamic content
updates.
Q3
The SimpleXML Extension is a built-in feature within PHP that allows developers to easily
read, manipulate, and access data from XML documents by converting them into object-
oriented structures, making it significantly simpler to work with XML compared to
traditional parsing methods like DOM (Document Object Model) by providing a more
intuitive way to navigate and access elements and attributes within an XML file using
standard object syntax
The JavaScript alert box is a modal window that displays a message to the user. It is created
using the alert() method, which takes a single argument: the message to be displayed. When
the alert() method is called, the browser pauses execution of the current script and displays
the alert box. The user must then click the "OK" button to close the alert box and resume
script execution.
Alert boxes are often used to display simple messages to the user, such as error messages or
confirmation messages. However, because they block script execution, they should be used
sparingly, as they can be disruptive to the user experience.
Example:
1. Model – Manages database operations like fetching, inserting, and updating data.
2. View – Handles the user interface and displays the output.
3. Controller – Acts as a bridge between the Model and View, processing requests and
sending data.
4. Helpers & Libraries – Provide additional functionalities like form validation, session
handling, and database queries.
5. Routing – Directs URL requests to the appropriate controller and method.
6. Security – Protects against SQL injection, XSS, and CSRF attacks.
An XML Parser is a software component that reads XML documents and converts them
into a format that applications can process. It ensures that the XML structure is well-formed
and can be used for data exchange between systems.
XML parsers help in data validation, manipulation, and extraction in applications like
web services and configuration files.
b) Explain the Workflow of MVC Architecture.
Advantages of MVC:
1. User Interaction – A user action (e.g., clicking a button) triggers an AJAX request.
2. JavaScript & XMLHttpRequest – JavaScript creates an XMLHttpRequest object to
send a request to the server.
3. Server Processing – The server processes the request and retrieves the necessary data
(e.g., from a database).
4. Server Response – The server sends the requested data back to the browser.
5. Page Update – JavaScript updates only the required parts of the page, without
reloading.
Advantages of AJAX:
A confirm dialog box in JavaScript is used to ask the user for confirmation before
performing an action. It displays a message with two buttons: OK and Cancel.
Example:
var result = confirm("Are you sure you want to delete this item?");
if (result) {
alert("Item deleted successfully.");
} else {
alert("Deletion canceled.");
}
In this example, a confirm box appears. If the user presses OK, an alert confirms deletion;
otherwise, it cancels the action.
In web applications, state maintenance is required to track user activities across multiple
pages. PHP provides several techniques to manage state:
1. Cookies
o Small data files stored on the client’s browser.
o Used to store user preferences, login details, etc.
o Example: setcookie("user", "John", time()+3600);
2. Sessions
o Stores user-specific data on the server instead of the client’s browser.
o More secure than cookies.
o Example:
session_start();
$_SESSION["username"] = "John";
3. Hidden Fields
o Stores data inside HTML forms that persist across requests.
o Example:
1. User Request → The user interacts with the application (e.g., submitting a form).
2. Routing → The request is processed by the Router, which decides which Controller
should handle it.
3. Controller → The Controller receives the request and interacts with the Model for
data processing.
4. Model → The Model retrieves or updates data from the Database.
5. View → The Controller sends the processed data to the View, which generates the
response.
6. User Response → The web page updates with the requested data.
Cookies store user-related data in the browser for session tracking and personalization. When
creating a cookie, several fields can be used:
In JavaScript, scope refers to the accessibility of variables in different parts of the program.
There are three types of scope:
1. Global Scope
o Variables declared outside any function are accessible from anywhere in the
script.
o Example: var globalVar = "I am global";
2. Local (Function) Scope
o Variables declared inside a function are only accessible within that function.
o Example:
js
CopyEdit
function test() {
let localVar = "I am local";
}
console.log(localVar); // Error: not accessible outside the function
js
CopyEdit
if (true) {
let blockVar = "I exist only inside this block";
}
console.log(blockVar); // Error: not accessible outside the block
Understanding scope helps avoid conflicts and improves variable management in JavaScript.
c) What Are the Advantages and Disadvantages of AJAX?
Advantages of AJAX:
1. Faster Page Loading – Only updates specific parts of the page instead of reloading
the entire webpage.
2. Improved User Experience – Creates smooth and interactive applications (e.g., auto-
suggestions, live search).
3. Reduced Server Load – Minimizes data transfer by only requesting necessary data.
4. Asynchronous Processing – Allows users to continue interacting with the webpage
while the request is being processed.
5. Better Performance – Reduces bandwidth usage and speeds up web applications.
Disadvantages of AJAX:
1. SEO Issues – Content loaded via AJAX is not always indexed by search engines.
2. Security Risks – More vulnerable to cross-site scripting (XSS) and CSRF attacks if
not implemented securely.
3. Browser Compatibility – Some older browsers may not fully support AJAX features.
4. Increased Complexity – Debugging and maintaining AJAX-based applications can
be more challenging.
5. JavaScript Dependency – If JavaScript is disabled in the browser, AJAX features
will not work.
Despite its drawbacks, AJAX is widely used in modern web applications like Google Maps,
Gmail, and Facebook notifications to enhance responsiveness and interactivity.
Q4
a) Design the HTML form to accept customer name, age and mobile number.
Write a PHP script to store all the details in different session variable
after clicking Submit button.
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['mobile'] = $_POST['mobile'];
echo "Details stored in session.";
?>
<script>
function validateForm() {
let user = document.getElementById("user").value, pass =
document.getElementById("pass").value;
if (!user || /\d/.test(user)) return alert("Invalid username"), false;
if (pass.length < 8 || !/[a-zA-Z]/.test(pass)) return alert("Invalid password"), false;
alert("Validation Successful!"); return true;
}
</script>
<script>
function showNames(str) {
if (!str) return document.getElementById("result").innerHTML = "";
fetch("suggest.php?q=" + str)
.then(res => res.text()).then(data => document.getElementById("result").innerHTML =
data);
}
</script>
php
<?php
$names = ["Alice", "Bob", "Charlie", "David", "Emma"];
$q = $_GET['q'];
echo implode("<br>", array_filter($names, fn($name) => stripos($name, $q) === 0)) ?: "No
match";
?>
function validateForm() {
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
<?php
$visit_time = date("Y-m-d H:i:s");
setcookie("lastVisit", $visit_time, time() + (86400 * 30), "/");
if (isset($_COOKIE["lastVisit"])) {
echo "Last visited on: " . $_COOKIE["lastVisit"];
} else {
echo "Welcome! This is your first visit.";
}?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(() => {
$("#addText").click(() => $("p").append(" Keep studying!"));
$("#addItem").click(() => $("ol").append("<li>New Item</li>"));
});
</script>
</head>
<body>
<p>Exams are coming soon.</p>
<button id="addText">Add Text</button>
<ol><li>Math</li><li>Science</li></ol>
<button id="addItem">Add List Item</button>
</body>
</html>
c) AJAX Program for Student Name Search Using Arrayshortest possible program
<?php
$students = ["Alice", "Bob", "Charlie", "David", "Eva"];
if (isset($_GET["q"])) echo implode("<br>", array_filter($students, fn($s) => stripos($s,
$_GET["q"]) !== false)) ?: "No match";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function searchStudent(q) {
if (q === "") return document.getElementById("result").innerHTML = "";
fetch("?q=" + q).then(res => res.text()).then(data =>
document.getElementById("result").innerHTML = data);
}
</script>
</head>
<body>
<input type="text" onkeyup="searchStudent(this.value)" placeholder="Search Student">
<div id="result"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function loadCountries() {
fetch("?load=1").then(res => res.text()).then(data =>
document.getElementById("result").innerHTML = data);
}
</script>
</head>
<body>
<button onclick="loadCountries()">OK</button>
<div id="result"></div>
</body>
</html>
b) Design the HTML form to accept Employee name, Age and Mobile no. and perform
the following validation using Java Script: i) No field should be empty. ii) Mobile no.
must contain 10 digits
<script>
function validateForm() {
let name = name.value.trim(), age = age.value.trim(), mobile = mobile.value.trim();
if (!name || !age || !mobile || !/^\d{10}$/.test(mobile)) {
alert("All fields required & Mobile must be 10 digits!");
return false;
}
}
</script>
a) Write a JavaScript code to accept employee’s name and age, validate it with name
and age should not be null and age should be greater than 18 years.
function validateEmployee() {
let name = document.getElementById("name").value.trim();
let age = document.getElementById("age").value.trim();
if (!name || !age || age <= 18) {
alert("Name is required & Age must be above 18!");
return false;
}
}
b) Create Doctor table as follows Doctor (dno, dname, experience).Write Ajax program
to print the doctor’s details of selected doctor.
<?php
$conn = new mysqli("localhost", "root", "", "hospital");
if (isset($_POST["dno"])) exit(json_encode($conn->query("SELECT dname, experience
FROM Doctor WHERE dno=" . $_POST["dno"])->fetch_assoc()));
$doctors = $conn->query("SELECT dno, dname FROM Doctor");
?>
<!DOCTYPE html>
<html>
<head>
<script>
function getDoctor(dno) {
fetch("", { method: "POST", headers: { "Content-Type": "application/x-www-form-
urlencoded" }, body: "dno=" + dno })
.then(res => res.json()).then(data =>
document.getElementById("result").innerHTML = data ? `${data.dname} -
${data.experience} yrs` : "No doctor found.");
}
</script>
</head>
<body>
<select onchange="getDoctor(this.value)">
<option value="">Select Doctor</option>
<?php while ($row = $doctors->fetch_assoc()) echo "<option
value='{$row['dno']}'>{$row['dname']}</option>"; ?>
</select>
<div id="result"></div>
</body>
</html>
c) Write a PHP Script to keep track of number of times the web page has been
accessed. (Use Session Tracking)
<?php
session_start(); // Start the session
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 1; // Initialize counter
} else {
$_SESSION['count']++; // Increment counter
}
echo "This page has been accessed " . $_SESSION['count'] . " times.";
?>
Q5
a) What is a Window object in JavaScript? Explain any two Window object methods.
In JavaScript, the Window object represents the browser window or tab in which the script is
running. It is the top-level object in the browser's object hierarchy, meaning it's the parent of
all other objects, including document, location, and history. Because of its position,
properties and methods of the Window object can be accessed directly without
referencing window. explicitly.
1. Model: Represents the application's data structure and interacts with the database. It
handles data retrieval, insertion, and updates, ensuring business logic is separate from
the user interface.
2. View: Responsible for displaying data to the user. It consists of HTML and
presentation logic, ensuring a clear separation between the application's logic and its
visual representation.
3. Controller: Acts as an intermediary between the Model and View. It processes user
requests, interacts with the Model to fetch or manipulate data, and then passes the data
to the View for rendering.
In CodeIgniter, the MVC pattern promotes separation of concerns, making the code more
organized, maintainable, and scalable. It simplifies development by dividing the application
into logical components, allowing developers to work on individual parts without affecting
the others. This structure is ideal for building dynamic, database-driven web applications.
The setcookie() function in PHP is used to store small data in the user's browser, which can
be accessed later. It helps in user authentication, tracking, and preferences storage.
Syntax:
Arguments:
Example:
This creates a cookie named "user" with value "John" that expires in 1 hour.
Workflow:
XML (Extensible Markup Language) follows strict rules to ensure data is structured
correctly.
1. Well-formed Structure – Every XML document must have a root element that
contains all other elements.
2. Case Sensitivity – XML tags are case-sensitive (<Name> is different from <name>).
3. Proper Nesting – Tags must be properly nested (e.g.,
<book><title>XYZ</title></book> is correct).
4. Closing Tags – Every opening tag must have a closing tag (<name>John</name>).
5. Attribute Quotation – Attribute values must be in quotes (<book
genre="fiction">).
6. No Special Characters – Use entity references (< for <, & for &) to avoid
conflicts.
Query selectors in JavaScript allow you to select and manipulate HTML elements easily.
Common Selectors:
Example:
document.querySelector(".btn").style.color = "red";
a) What is XML Parser? Explain Two Different Types of XML Parsers.
An XML parser is a tool that reads XML documents, checks if they are well-formed, and
makes data accessible for applications. It helps in processing XML data efficiently.
$autoload['helper'] = array('url');
/assets/css/style.css
/assets/js/script.js
$config['base_url'] = 'http://localhost/your_project/';
1. Root Element is Required – Every XML document must have a single root element.
2. Case-Sensitive Tags – <name> and <Name> are treated as different tags.
3. Properly Nested Tags – Tags must open and close in the correct order.
4. Mandatory Closing Tags – Every opening tag must have a closing tag
(<title>Book</title>).
5. Attribute Values in Quotes – <book genre="fiction"> (double or single quotes
required).
6. No Special Characters – Use entities like < for <, > for >, and & for &.
b) What are jQuery Selectors? Explain in Brief.
jQuery selectors are tools that allow the selection and manipulation of HTML elements on a
web page. They use CSS-like syntax to "find" or select elements based on their names, IDs,
classes, types, attributes, and more. Starting with a dollar sign and parentheses $(...), jQuery
selectors provide a concise way to interact with the DOM (Document Object Model). They
are crucial for tasks like creating onboarding goals, triggering actions on specific elements,
extracting values, and checking page conditions