WEB TECHNOLOGY CHAPTER WISE QUESTONS COLLECTION

GYAN WALLA
0

 


Unit 1: Introduction

1. Define web clients and web servers with examples.
Solution
Web Client
A web client is a software or device that requests and displays web pages from a web server.

Functions:
Sends HTTP requests to the server
Receives and displays web content (HTML, CSS, etc.)
Acts as an interface between user and web

Examples:
Browsers: Google Chrome, Mozilla Firefox, Opera
Mobile apps, web crawlers

Web Server
A web server is a computer or software that stores, processes, and delivers web pages to clients.

Functions:
Hosts websites and web applications
Processes client requests
Sends HTTP responses with requested data

Examples:
Apache HTTP Server
Nginx
Microsoft IIS

2. Describe client server architecture with its types.
Solution
Client-Server Architecture
Client-server architecture is a computing model in which a client requests services and a server provides services over a network.

Working:
Client sends a request (e.g., HTTP request)
Server processes the request
Server sends a response back to the client


Types of Client-Server Architecture
1. Single-Tier (1-Tier) Architecture
All components (Presentation, Business Logic, Data) are on the same system.

Features:
No network required
Simple and fast for small applications

Limitations:
Poor scalability
Difficult maintenance
Example: Standalone desktop application

2. Two-Tier (2-Tier) Architecture
Client and server are separated.

Features:
Client handles presentation + logic
Server handles database (data layer)

Advantages:
Better than 1-tier in performance
Easy database management

Limitations:
Heavy load on server
Limited scalability

Example: Client app connected directly to a database server

3. Three-Tier (3-Tier) Architecture
System is divided into three layers:
Presentation layer (client)
Business logic layer (application server)
Data layer (database server)

Advantages:
High scalability
Easy maintenance
Better security

Example: Web applications (browser → app server → database)

3. Difference between Static and Dynamic websites.


4. Describe the WWW, web client and web server.
Solution
World Wide Web (WWW)
The World Wide Web is a system of interconnected web pages that can be accessed over the Internet using web browsers.
Invented by Tim Berners-Lee
Uses HTTP protocol for communication
Information is stored in web pages and identified by URLs
Supports multimedia: text, images, audio, video

Web Client
A web client is a software or device that requests and displays web pages from a web server.

Functions:
Sends HTTP requests
Receives and displays content
Acts as an interface between user and web

Examples:
Google Chrome, Mozilla Firefox
Mobile apps, web crawlers


Web Server
A web server is a computer or software that stores, processes, and delivers web pages to clients.

Functions:
Hosts websites
Processes client requests
Sends HTTP responses

Examples:
Apache HTTP Server
Nginx

5. Differentiate Web 1.0 from Web 2.0.
Solution




6. What are the services provided under web 2.0?
Solution 
Web 2.0 refers to the interactive and user-centered web that allows users to create, share, and collaborate on content.

Main Services:

User-Generated Content:-
Users can create and share content (posts, videos, blogs)

Social Networking:-
Platforms for connecting and interacting with others
Example: Facebook

Blogging and Microblogging:-
Users can write and publish articles or short posts

Wikis (Collaborative Editing):-
Multiple users can create and edit content together

Media Sharing:-
Uploading and sharing videos, images, etc.
Example: YouTube

Tagging and Folksonomy:-
Users can tag and organize content
Rich User Interaction
Commenting, liking, reviewing, and feedback

Web Applications:-
Browser-based applications (no installation required)

7. What is HTTP protocol? Define HTTP Request and Response.
Solution 
HTTP Protocol
HTTP (HyperText Transfer Protocol) is an application-layer protocol used to transfer data between a web client and a web server over the Internet.
It is a stateless protocol, meaning each request is independent
It follows a request-response communication model
It works over TCP/IP for reliable data transfer
It is mainly used for transferring web resources like HTML, images, videos

HTTP Request
An HTTP request is a message sent by the client to the server to request a resource or perform an action.
It contains a request line (method, URL, HTTP version)
It includes headers that provide additional information
It may contain a body to send data (mainly in POST)
Common methods are GET (retrieve data) and POST (send data)

HTTP Response
An HTTP response is the message sent by the server back to the client after processing the request.
It contains a status line (status code and message)
It includes headers with information about the response
It has a body containing the requested resource
Common status codes are 200 OK, 404 Not Found, 500 Internal Server Error



Unit 2: Hyper Text Markup Language

1. Write a HTML script using audio tag. Set the autoplay, preload and loop properties to appropriate values.
Solution
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Audio Tag Example</title>
</head>
<body>

  <h2>HTML Audio Tag Demo</h2>

  <audio
    autoplay
    loop
    preload="auto"
    controls>
    <source src="audio/sample.mp3" type="audio/mpeg">
    <source src="audio/sample.ogg" type="audio/ogg">
    Your browser does not support the audio element.
  </audio>

</body>
</html>
2. Write HTML script to demonstrate the onkeydown and onkeypress events.
Solution
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Keyboard Events Demo</title>
</head>
<body>

  <h2>Keyboard Events: onkeydown and onkeypress</h2>

  <input
    type="text"
    id="inputField"
    placeholder="Start typing..."
    onkeydown="handleKeyDown(event)"
    onkeypress="handleKeyPress(event)"
  >
  <p>onkeydown output:</p>
  <div id="keydownOutput">Waiting for key down...</div>

  <p>onkeypress output:</p>
  <div id="keypressOutput">Waiting for key press...</div>

  <script>
    function handleKeyDown(event) {
      document.getElementById("keydownOutput").innerHTML =
        "Key: " + event.key +
        " | Key Code: " + event.keyCode +
        " | Event: onkeydown";
    }
    function handleKeyPress(event) {
      document.getElementById("keypressOutput").innerHTML =
        "Key: " + event.key +
        " | Key Code: " + event.keyCode +
        " | Event: onkeypress";
    }
  </script>
</body>
</html>

3. Create an HTML page containing three paragraphs p1, p2 and p3 with some contents. Write internal CSS to set the position of p1 to relative, p2 to float and p3 to absolute.
Solution
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CSS Positioning Demo</title>
  <style>
    #p1 {
      position: relative;
      top: 20px;
      left: 30px;
      background-color: lightblue;
    }

    #p2 {
      float: left;
      width: 200px;
      background-color: lightgreen;
    }

    #p3 {
      position: absolute;
      top: 100px;
      right: 50px;
      background-color: lightyellow;
    }
  </style>
</head>
<body>

  <h2>CSS Position and Float Demo</h2>

  <p id="p1">
    This is paragraph 1. Its position is set to relative.
    It is shifted 20px from top and 30px from left of its normal position.
  </p>

  <p id="p2">
    This is paragraph 2. It is set to float left.
    It floats to the left side and other content wraps around it.
  </p>

  <p id="p3">
    This is paragraph 3. Its position is set to absolute.
    It is placed 100px from the top and 50px from the right of the page.
  </p>

</body>
</html>
4. Write an HTML script to create a table with three rows and three columns. The second row third column should contain a text “TU” with link set to www.tu.edu.np.
Solution
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Table Demo</title>
</head>
<body>

  <h2>Table with 3 Rows and 3 Columns</h2>

  <table border="1">
    <tr>
      <td>Row 1, Col 1</td>
      <td>Row 1, Col 2</td>
      <td>Row 1, Col 3</td>
    </tr>
    <tr>
      <td>Row 2, Col 1</td>
      <td>Row 2, Col 2</td>
      <td><a href="http://www.tu.edu.np">TU</a></td>
    </tr>
    <tr>
      <td>Row 3, Col 1</td>
      <td>Row 3, Col 2</td>
      <td>Row 3, Col 3</td>
    </tr>
  </table>

</body>
</html>
5. What is onload event in HTML? Write an HTML script that displays alert message “Hello Nepal” in onload event.
Solution 
onload Event in HTML
The onload event is an event in HTML that is triggered when a web page or resource has completely loaded.
It occurs after all HTML elements, images, and scripts are fully loaded
It is commonly used to execute JavaScript automatically after page load
It is usually applied to the <body> tag
It ensures that scripts run only after the page is fully ready

code:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Onload Event Demo</title>
</head>
<body onload="alert('Hello Nepal')">

  <h2>Onload Event Demo</h2>
  <p>An alert box appeared when the page loaded.</p>

</body>
</html>
6. Write HTML script to create HTML form and perform validation using JavaScript.
Solution
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Form Validation</title>
</head>
<body>

  <form onsubmit="return validateForm()">
    Name: <input type="text" id="name"><br><br>
    Email: <input type="text" id="email"><br><br>
    Age: <input type="text" id="age"><br><br>
    Password: <input type="password" id="password"><br><br>
    <input type="submit" value="Submit">
  </form>

  <script>
    function validateForm() {
      var name = document.getElementById("name").value;
      var email = document.getElementById("email").value;
      var age = document.getElementById("age").value;
      var password = document.getElementById("password").value;

      if (name == "") { alert("Name is required."); return false; }
      if (email == "") { alert("Email is required."); return false; }
      if (email.indexOf("@") == -1) { alert("Invalid email."); return false; }
      if (age == "" || isNaN(age) || age <= 0) { alert("Enter valid age."); return false; }
      if (password == "") { alert("Password is required."); return false; }
      if (password.length < 6) { alert("Password min 6 characters."); return false; }

      alert("Form submitted successfully!");
      return true;
    }
  </script>

</body>
</html>
7. Create a registration form with Name, Country, Gender and submit button which display message “Registered” on keypress event.
SOlution
<!DOCTYPE html>
<html>
<head>
  <title>Registration Form</title>
</head>
<body>

  <h2>Registration Form</h2>

  <form>
    Name: <input type="text" id="name" onkeypress="showMessage()"><br><br>
    Country: <input type="text" id="country" onkeypress="showMessage()"><br><br>
    Gender:
    <input type="radio" name="gender" value="Male"> Male
    <input type="radio" name="gender" value="Female"> Female <br><br>
    <input type="submit" value="Submit">
  </form>

  <p id="msg"></p>

  <script>
    function showMessage() {
      document.getElementById("msg").innerHTML = "Registered";
    }
  </script>

</body>
</html>
8. Write HTML script to generate ordered and unordered lists.
solution 
<!DOCTYPE html>
<html>
<head>
  <title>Lists Demo</title>
</head>
<body>

  <h2>Ordered List</h2>
  <ol>
    <li>HTML</li>
    <li>CSS</li>
    <li>JavaScript</li>
    <li>PHP</li>
  </ol>

  <h2>Unordered List</h2>
  <ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Mango</li>
    <li>Orange</li>
  </ul>

</body>
</html>
9. Create an HTML page containing a div with canvas element and set its height and width.
SOlution
<!DOCTYPE html>
<html>
<head>
  <title>Canvas Demo</title>
</head>
<body>

  <h2>Canvas Element</h2>

  <div>
    <canvas id="myCanvas" width="400" height="300" style="border:1px solid black;">
      Your browser does not support the canvas element.
    </canvas>
  </div>

</body>
</html>
10. Create a HTML page with tags header, article and footer and insert mail link using meta tag.
Solution
<!DOCTYPE html>
<html>
<head>
  <title>Semantic Tags Demo</title>
  <meta http-equiv="reply-to" content="info@example.com">
</head>
<body>

  <header>
    <h1>Welcome to My Website</h1>
    <p>This is the header section.</p>
  </header>

  <article>
    <h2>Article Title</h2>
    <p>This is the article section containing main content.</p>
  </article>

  <footer>
    <p>Contact us: <a href="mailto:info@example.com">info@example.com</a></p>
    <p>This is the footer section.</p>
  </footer>

</body>
</html>
11. Why inline frames are used? Create a HTML page containing iframe within a paragraph.
Solution
Inline frames are used to embed another HTML document within the current web page using the <iframe> tag.
They allow displaying multiple web pages in a single browser window
They can embed external content like websites, videos, maps, etc.
Each frame loads independently without affecting the main page
They help create separate sections within a webpage for different content

Code:
<!DOCTYPE html>
<html>
<head>
  <title>Iframe Demo</title>
</head>
<body>

  <p>
    This is a paragraph containing an iframe below.
    <iframe src="https://www.tu.edu.np" width="500" height="300">
      Your browser does not support iframe.
    </iframe>
    This text appears after the iframe inside the paragraph.
  </p>

</body>
</html>

Unit 3: Cascading Style Sheets

1. Define CSS. What is the use of CSS shadow effects?
Solution 
CSS (Cascading Style Sheets):
CSS is a stylesheet language used to control the appearance and layout of HTML elements on a web page.
It is used to apply styles like color, font, spacing, and layout
It allows separation of content (HTML) and design (CSS)
It supports multiple styles cascading into one final style
It can be applied as inline, internal, or external CSS

Use of CSS Shadow Effects:
CSS shadow effects are used to add shadow to elements and text to create visual depth and styling.
box-shadow is used to add shadow to HTML elements (boxes)
text-shadow is used to add shadow to text
They improve the visual appearance and design of a webpage
They help create a 3D or depth effect for better UI

2. How internal and external CSS differ from each other.
Solution 

3. Explain CSS box model.
Solution
CSS Box Model
The CSS box model is a layout model in which every HTML element is treated as a rectangular box consisting of content, padding, border, and margin.

Components of Box Model
Content:
The inner area where text and images are displayed
Padding:
Space between content and border; transparent and increases element size
Border:
Surrounds padding and content; used to define the boundary of the element
Margin:
Outer space outside the border; used to create space between elements and can be negative

Example:
div {
  width: 300px;
  padding: 20px;
  border: 5px solid black;
  margin: 10px;
}

4. What is text-overflow property in CSS? How can you use clip and ellipsis?
Solution
The text-overflow property in CSS is used to specify how overflowing text that is not displayed should be shown when it exceeds its container.
It works when content overflows the container width
It is used with overflow: hidden and white-space: nowrap
It helps in controlling how extra text is visually represented
Common values are clip and ellipsis

clip Value:
It cuts off the extra text at the boundary
No indication is given that text is hidden

Example:
p {
  width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: clip;
}
ellipsis Value:

It displays three dots (...) to indicate hidden text
It improves user understanding of truncated content

Example:
p {
  width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

5. What is word-wrap property in CSS?
Solution
word-wrap Property in CSS:
The word-wrap property in CSS is used to break long words and wrap them onto the next line when they exceed the width of their container.
It prevents text from overflowing outside the container
It ensures proper layout and readability of content
It is mainly used when words are too long to fit in a single line
It works with fixed width containers

Values:

normal: Words break only at normal break points
break-word: Long words are broken and wrapped to the next line

Example:
p {
  width: 150px;
  border: 1px solid black;
  word-wrap: break-word;
}
6. How positioning of HTML elements can be done using CSS?
Solution
Positioning of HTML Elements using CSS:
Positioning of HTML elements in CSS is done using different properties to control the layout and placement of elements on a webpage.

Methods of Positioning:

a) Normal Flow (Default Positioning):
Elements are placed one after another
Block elements → vertica
Inline elements → horizontal

b) Position Property:
Used to specify exact position of elements
static: Default position (normal flow)
relative: Positioned relative to its normal position
absolute: Positioned relative to the nearest positioned ancestor
fixed: Positioned relative to the browser window

b) Float Property:
Used to move elements to left or right
Values: left, right, none

c) Display Property:
Controls layout behavior of elements
Example: block, inline, inline-block

d) Z-index Property:
Controls stacking order of overlapping elements
Higher value appears on top

7. How web pages can be made responsive using media queries?
Solution
Media queries are a CSS technique used to apply different styles based on device screen size or conditions, making web pages responsive.

How Media Queries Make Web Pages Responsive

They use the @media rule to apply CSS only when certain conditions are met
They adjust layout based on screen width, height, or device type
They help websites adapt to mobile, tablet, and desktop screens
They allow changing font size, layout, images, and colors for different devices

Example:
@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}


Unit 4: Client Side Scripting with JavaScript

1. Write a HTML script with proper JavaScript that will take input from prompt box and display output using alert box.
Solution
<!DOCTYPE html>
<html>
<head>
  <title>Prompt and Alert Demo</title>
</head>
<body>

  <h2>Prompt and Alert Demo</h2>

  <script>
    var name = prompt("Enter your name:");
    alert("Hello, " + name + "!");
  </script>

</body>
</html>

2. What is the use of alert box? Write a JavaScript program to show the use of RegExp object.
Solution
An alert box is a popup window in JavaScript used to display a message to the user.
It is used to show important information or warnings
It requires the user to click OK before continuing
It is created using the alert() function
It is a part of client-side scripting (JavaScript)
It helps in making web pages interactive and user-friendly

code:
<!DOCTYPE html>
<html>
<head>
  <title>RegExp Demo</title>
</head>
<body>

  <h2>RegExp Object Demo</h2>

  <script>
    var str = "Welcome to TU Nepal";
    var pattern = new RegExp("TU");

    var result = pattern.test(str);

    if (result) {
      alert("Pattern found: " + pattern);
    } else {
      alert("Pattern not found.");
    }

    var match = str.match(/Nepal/);
    alert("Match result: " + match);

    var newStr = str.replace(/TU/, "Tribhuvan University");
    alert("After replace: " + newStr);
  </script>

</body>
</html>
3. How can you define array in JavaScript? Create an array Fruit and print it.
Solution
An array in JavaScript is a collection of elements stored in a single variable, where each element is accessed by an index.
Ways to Define an Array

Using Array Literal (Most Common):
var arr = [1, 2, 3, 4];

Using new Array() Constructor:
var arr = new Array(1, 2, 3, 4);

Using Empty Array and Assigning Values:
var arr = [];
arr[0] = 10;
arr[1] = 20;

code:

<!DOCTYPE html>
<html>
<head>
  <title>Array Demo</title>
</head>
<body>

  <script>
    var Fruit = ["Apple", "Banana", "Mango", "Orange", "Grapes"];
    document.write("Fruit Array: " + Fruit);
  </script>

</body>
</html>

4. How HTML elements are accessed using getElementById and getElementByTagName.
Solution
1. getElementById
Accesses a single element using its unique id attribute.

html<!DOCTYPE html>
<html>
<head>
  <title>getElementById Demo</title>
</head>
<body>

  <p id="demo">This is a paragraph.</p>
  <button onclick="changeText()">Click Me</button>

  <script>
    function changeText() {
      document.getElementById("demo").innerHTML = "Text changed!";
    }
  </script>

</body>
</html>

2. getElementsByTagName
Accesses multiple elements using their tag name. Returns a collection.

html<!DOCTYPE html>
<html>
<head>
  <title>getElementsByTagName Demo</title>
</head>
<body>

  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
  <button onclick="changeAll()">Click Me</button>

  <script>
    function changeAll() {
      var items = document.getElementsByTagName("p");
      for (var i = 0; i < items.length; i++) {
        items[i].innerHTML = "Changed Paragraph " + (i + 1);
      }
    }
  </script>

</body>
</html>

5. How can you create objects in JavaScript?
Solution
An object in JavaScript is a collection of key-value pairs used to store related data and functions.

Ways to Create Objects

Using Object Literal (Most Common):
var student = {
  name: "Ram",
  age: 20
};

Using new Object():
var student = new Object();
student.name = "Ram";
student.age = 20;

Using Constructor Function:
function Student(name, age) {
  this.name = name;
  this.age = age;
}
var s1 = new Student("Ram", 20);

6. Write JavaScript function for validating form elements.
Solution 
<!DOCTYPE html>
<html>
<head>
  <title>Form Validation</title>
</head>
<body>

  <form onsubmit="return validate()">
    Name: <input type="text" id="name"><br><br>
    Email: <input type="text" id="email"><br><br>
    <input type="submit" value="Submit">
  </form>

  <script>
    function validate() {
      var name = document.getElementById("name").value;
      var email = document.getElementById("email").value;

      if (name == "") { alert("Name is required."); return false; }
      if (email == "") { alert("Email is required."); return false; }
      if (email.indexOf("@") == -1) { alert("Invalid email."); return false; }

      alert("Form submitted successfully!");
      return true;
    }
  </script>

</body>
</html>
7. How can you handle cookies in JavaScript?
Solution
Handling Cookies:
Cookies are small pieces of data stored in the browser to remember user information such as login details, preferences, etc.

How to Handle Cookies

Creating a Cookie:
Cookies are created using the document.cookie property.

document.cookie = "username=Ram; expires=Fri, 25 Mar 2026 12:00:00 UTC; path=/";

Reading a Cookie:
Cookies can be accessed using document.cookie, which returns all cookies.

var data = document.cookie;

Updating a Cookie:
A cookie can be updated by assigning a new value with the same name.

document.cookie = "username=Hari; path=/";

Deleting a Cookie:
A cookie is deleted by setting its expiration date to the past.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

8. What is the use of JSON? How can you parse JSON?
Solution 
JSON (JavaScript Object Notation) is a lightweight data format used to store and exchange data between a client and a server.
The use of JSON are
It is used to transfer data over the web
It is easy to read and write for humans
It is easy to parse and generate for machines
It is widely used in APIs and web applications

Parsing JSON:
Parsing JSON means converting a JSON string into a JavaScript object.

JSON is parsed using JSON.parse()
It converts JSON data into a usable JavaScript object
Used when receiving data from a server

Example:
var data = '{"name":"Ram","age":20}';
var obj = JSON.parse(data);

9. Discuss about different JSON data types.
Solution
JSON supports a limited set of data types used to represent and exchange structured data.

Different JSON Data Types

String:
Text data enclosed in double quotes
Example: "Hello"

Number:
Represents numeric values (integer or decimal)
Example: 10, 25.5

Boolean:
Logical values used for true/false conditions
Example: true, false

Object:
A collection of key-value pairs enclosed in { }
Example: {"name": "Ram", "age": 20}

Array:
An ordered list of values enclosed in [ ]
Example: ["HTML", "CSS", "JS"]

Null:
Represents an empty or unknown value
Example: null

Unit 5: AJAX and XML

1. What is the use of XML? Create XML file with complex type elements and write equivalent XSD.
Solution
Use of XML
XML (Extensible Markup Language) is used to store and transport data in a structured and platform-independent way.

Uses of XML:
Data Storage: Stores structured data in a readable format.
Data Exchange: Used to transfer data between different systems (platform-independent).
Web Services / AJAX: Used to send and receive data between client and server.
Configuration Files: Used in software settings (e.g., app configurations).

2. XML with Complex Type

A complex type in XML is an element that contains:
child elements, and/or

attributes

Example XML (student.xml)
<?xml version="1.0" encoding="UTF-8"?>
<student_list>
  <student>
    <name>Ram Shrestha</name>
    <roll_no>101</roll_no>
    <address>
      <city>Kathmandu</city>
      <street>Baneshwor</street>
    </address>
  </student>
</student_list>

 Here, <student> and <address> are complex elements because they contain nested elements.

3. Equivalent XSD (XML Schema Definition)
XSD is used to define the structure, data types, and constraints of an XML document.

Example XSD (student.xsd)
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="student_list">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="student" type="studentType" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="studentType">
    <xs:sequence>
      <xs:element name="name" type="xs:string"/>
      <xs:element name="roll_no" type="xs:integer"/>
      <xs:element name="address" type="addressType"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="addressType">
    <xs:sequence>
      <xs:element name="city" type="xs:string"/>
      <xs:element name="street" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

2. Describe the rules for creating XML document and write its equivalent XSD.
SOlution
Rules for Creating an XML Document
An XML document must follow these rules to be well-formed:

Single Root Element:
There must be only one root element that contains all other elements.

Proper Closing Tags:
Every opening tag must have a closing tag.

Case Sensitivity:
XML tags are case-sensitive (<Name> ≠ <name>).

Proper Nesting:
Elements must be correctly nested.

Attribute Values in Quotes:
Attribute values must be enclosed in quotes.

Valid Tag Names:
Tags must not start with numbers or contain spaces.

Example XML (note.xml)
<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Ram</to>
  <from>Sita</from>
  <heading>Reminder</heading>
  <body>Complete your assignment</body>
</note>
Equivalent XSD (note.xsd)
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="note">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="to" type="xs:string"/>
        <xs:element name="from" type="xs:string"/>
        <xs:element name="heading" type="xs:string"/>
        <xs:element name="body" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

3. Write the structure of XML file with example and DTD.
Solution
Structure of an XML File
An XML file has a simple and well-defined structure:

XML Declaration:
Defines version and encoding of XML.

Root Element:
The single parent element that contains all other elements.

Child Elements:
Nested elements inside the root containing actual data.

Example XML with DTD
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
  <!ELEMENT note (to, from, heading, body)>
  <!ELEMENT to (#PCDATA)>
  <!ELEMENT from (#PCDATA)>
  <!ELEMENT heading (#PCDATA)>
  <!ELEMENT body (#PCDATA)>
]>
<note>
  <to>Ram</to>
  <from>Sita</from>
  <heading>Reminder</heading>
  <body>Complete the assignment</body>
</note>

4. Compare XML Schema with DTD.
Solution


5. How can you transform XML document into HTML using XSLT?
Solution
XML can be transformed into HTML using XSLT (Extensible Stylesheet Language Transformations), which uses templates to convert XML data into a presentable HTML format.
Steps to Transform XML into HTML

1. Create XML file and link XSLT
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<student_list>
  <student>
    <name>Ram</name>
    <roll>1</roll>
  </student>
</student_list>

The line <?xml-stylesheet ...?> connects XML with the XSL file.

2. Create XSLT file (style.xsl)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
    <html>
      <body>
        <h2>Student List</h2>
        <table border="1">
          <tr>
            <th>Name</th>
            <th>Roll</th>
          </tr>
          <xsl:for-each select="student_list/student">
            <tr>
              <td><xsl:value-of select="name"/></td>
              <td><xsl:value-of select="roll"/></td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

3. How Transformation Works

a. Browser reads the XML file
b. Finds the linked XSLT file
c. XSLT uses:
    <xsl:template> → defines structure
    <xsl:for-each> → loops through XML data
    <xsl:value-of> → extracts values
d. Output is HTML format

6. What is XML Namespace?
Solution
XML Namespace:
An XML Namespace is used to avoid naming conflicts when combining XML documents that may use the same element names.
It ensures that elements with the same name are treated as different if they belong to different namespaces.

Need for Namespace:
Prevents element name conflicts
Allows combining XML documents from different sources
Makes XML documents more structured and organized

Syntax
xmlns:prefix="URI"
xmlns → attribute to declare namespace
prefix → short name used with elements
URI → unique identifier (not necessarily a real link)

Example

<root xmlns:f="http://www.furniture.com"
      xmlns:h="http://www.html.com">

  <f:table>
    <f:name>Chair</f:name>
  </f:table>

  <h:table>
    <h:tr>
      <h:td>Data 1</h:td>
    </h:tr>
  </h:table>
</root>


7. What is XMLHttpRequest object? Write HTML script with AJAX.
Solution
XMLHttpRequest (XHR) Object:
The XMLHttpRequest object is a built-in browser object used in AJAX to exchange data with a server without reloading the entire web page. It enables partial page updates and dynamic web applications.

HTML Script Using AJAX
<!DOCTYPE html>
<html>
<body>

<div id="demo">
  <h2>Click the button to change this text</h2>
  <button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
  // 1. Create XMLHttpRequest object
  var xhttp = new XMLHttpRequest();

  // 2. Define callback function
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };

  // 3. Initialize request (method, URL, asynchronous)
  xhttp.open("GET", "ajax_info.txt", true);

  // 4. Send the request
  xhttp.send();
}
</script>
</body>
</html>

How It Works:-
User Action: Button click triggers loadDoc().
Request Created: XMLHttpRequest object is instantiated.
Asynchronous Communication: Browser sends request to the server without reloading page.
Response Handling: When server responds (readyState == 4 and status == 200), the callback updates the HTML <div> with responseText.


8. What is DTD? Create a XML file and write its equivalent DTD.
Solution
DTD is used to define the structure and rules of an XML document.

It specifies:
what elements can appear in an XML document
the order of elements
which elements are allowed inside others
attributes of elements

 In short, DTD acts as a rulebook for XML documents to ensure they are valid.

Types of DTD

Internal DTD:
Written inside the XML document using <!DOCTYPE>

External DTD:
Stored in a separate .dtd file and linked to XML

Code:
XML File (student.xml):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE student SYSTEM "student.dtd">
<student>
  <name>Ram Kumar</name>
  <age>20</age>
  <course>BScCSIT</course>
  <college>TU</college>
</student>

DTD File (student.dtd):

<!ELEMENT student (name, age, course, college)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT course (#PCDATA)>
<!ELEMENT college (#PCDATA)>

Unit 6: Server Side Scripting using PHP

1. Write a PHP program to demonstrate inheritance.
Solution
<?php
class Animal {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }

  public function speak() {
    echo "I am an animal.<br>";
  }
}
class Dog extends Animal {
  public function speak() {
    echo "I am a dog. My name is " . $this->name . "<br>";
  }
}
class Cat extends Animal {
  public function speak() {
    echo "I am a cat. My name is " . $this->name . "<br>";
  }
}

$dog = new Dog("Bruno");
$dog->speak();

$cat = new Cat("Kitty");
$cat->speak();

?>

2. Write a PHP program to show insertion of multiple data into a database table.
Solution
<?php

$conn = mysqli_connect("localhost", "root", "", "mydb");

$students = array(
  array("Ram", 20, "BScCSIT"),
  array("Sita", 21, "BCA"),
  array("Hari", 22, "BIT")
);

foreach ($students as $student) {
  $sql = "INSERT INTO students (name, age, course) VALUES ('$student[0]', '$student[1]', '$student[2]')";
  mysqli_query($conn, $sql);
}

echo "Multiple records inserted successfully.";

mysqli_close($conn);

?>

3. Create a PHP form and perform form validation.
Solution
<!DOCTYPE html>
<html>
<body>

<form method="post" action="">
  Name: <input type="text" name="name"><br><br>
  Email: <input type="text" name="email"><br><br>
  <input type="submit" name="submit" value="Submit">
</form>

<?php
if (isset($_POST['submit'])) {
  $name = $_POST['name'];
  $email = $_POST['email'];

  if (empty($name)) {
    echo "Name is required.";
  } elseif (empty($email)) {
    echo "Email is required.";
  } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email.";
  } else {
    echo "Form submitted successfully!";
  }
}
?>

</body>
</html>

4. Write a PHP program to create class and object.
Solution
<?php
class Student {
  public $name;
  public $age;
  public $course;

  public function __construct($name, $age, $course) {
    $this->name = $name;
    $this->age = $age;
    $this->course = $course;
  }
  public function display() {
    echo "Name: " . $this->name . "<br>";
    echo "Age: " . $this->age . "<br>";
    echo "Course: " . $this->course . "<br>";
  }
}
$student = new Student("Ram", 20, "BScCSIT");
$student->display();

?>
5. Write a PHP function to add two numbers.
Solution
<?php
function addNumbers($a, $b) {
  return $a + $b;
}
$result = addNumbers(10, 20);
echo "Sum = " . $result;
?>


6. Define cookie. Write PHP program to create and retrieve cookie.
Solution
Cookie:
A cookie is a small piece of data stored in the user’s browser by a website and sent back to the server with every request.
It is used to store user-related information on the client side.

Uses of Cookies:
Session Management → keeps users logged in
Personalization → remembers user preferences
Tracking → tracks user activity on websites
Code
<?php

setcookie("username", "Ram Kumar", time() + 3600);

if (isset($_COOKIE["username"])) {
  echo "Cookie Value: " . $_COOKIE["username"];
} else {
  echo "Cookie not set.";
}

?>


7. How can you handle session in PHP?
Solution
Handling Sessions in PHP:
A session in PHP is used to store user information across multiple pages on the server.
Unlike cookies, session data is stored on the server, making it more secure.

Steps to Handle Session in PHP:

a. Start a Session
session_start();

Must be called at the beginning of the file
Initializes session and allows access to $_SESSION

b. Store Data in Session
$_SESSION["username"] = "Ram";
$_SESSION["email"] = "ram@gmail.com";

Stores user information on the server
Data can be accessed across multiple pages

c. Access Session Data
echo $_SESSION["username"];
Retrieves stored session values using the key

d. Modify Session Data
$_SESSION["username"] = "Sita";
Simply overwrite the existing value

e. Check if Session Variable Exists
if(isset($_SESSION["username"])) {
    echo "Session exists";
}
Prevents errors when accessing undefined session variables

f. Remove Specific Session Variable
unset($_SESSION["username"]);

Deletes a specific session variable

g. Destroy the Session
session_unset();   // Removes all session variables
session_destroy(); // Ends the session

Completely removes session data from the server

8. Write PHP program to insert and select value to and from database.
Solution
<?php

$conn = mysqli_connect("localhost", "root", "", "mydb");

$sql = "INSERT INTO students (name, age) VALUES ('Ram', 20)";
mysqli_query($conn, $sql);
echo "Record inserted successfully.<br>";

$result = mysqli_query($conn, "SELECT * FROM students");

while ($row = mysqli_fetch_array($result)) {
  echo "ID: " . $row['id'] . " Name: " . $row['name'] . " Age: " . $row['age'] . "<br>";
}
mysqli_close($conn);
?>

9. How database connection is created in PHP?
Solution
Syntax:
phpmysqli_connect(host, username, password, database);

Example:
<?php
$conn = mysqli_connect("localhost", "root", "", "mydb");
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
} else {
  echo "Connection successful.";
}
?>

10. How can you define array in PHP?
SOlution
An array in PHP is defined using the array() function or [] syntax.
1. Indexed Array:

<?php
$fruits = array("Apple", "Banana", "Mango");
echo $fruits[0];
?>
2. Associative Array:

<?php
$student = array("name" => "Ram", "age" => 20, "course" => "BScCSIT");
echo $student["name"];
?>
3. Multidimensional Array:

php<?php
$students = array(
  array("Ram", 20, "BScCSIT"),
  array("Sita", 21, "BCA")
);
echo $students[0][0];
?>

11. How can you define function in PHP?
Solution
A function in PHP is defined using the function keyword.

Syntax:
phpfunction functionName() {
  // code
}
1. Simple Function:

<?php
function greet() {
  echo "Hello Nepal!";
}
greet();
?>
2. Function with Parameters:

<?php
function addNumbers($a, $b) {
  echo "Sum = " . ($a + $b);
}
addNumbers(10, 20);
?>
3. Function with Return Value:

<?php
function multiply($a, $b) {
  return $a * $b;
}
$result = multiply(5, 4);
echo "Result = " . $result;
?>


Miscellaneous / Cross-Chapter Questions

1. What is jQuery selector? Explain jQuery callback and chaining effects.
Solution
jQuery Selector:
A jQuery selector is used to select and manipulate HTML elements based on their name, id, class, or attributes.
It is similar to CSS selectors
It is written using the $() symbol
It helps in finding and accessing elements easily

Examples:
$("p") → selects all <p> elements
$("#id") → selects element with specific id
$(".class") → selects elements with a class

jQuery Callback Function
A callback function is a function that is executed after an effect or animation is completed.
It ensures **proper sequence of

2. What is jQuery animate? Explain with example.
Solution
jQuery animate() is a method used to create custom animations on HTML elements.
It changes CSS properties gradually over time.
It works mainly with numeric values (width, height, opacity, etc.).
It helps make web pages more interactive and dynamic.

Syntax
$(selector).animate({params}, speed, callback);
params: CSS properties to animate (required)
speed: Duration (slow, fast, milliseconds)
callback: Function after animation (optional)


Example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("div").animate({
      left: '250px',
      opacity: '0.5',
      height: '150px',
      width: '150px'
    }, "slow");
  });
});
</script>
</head>

<body>
<button>Start Animation</button>

<div style="background:blue; height:100px; width:100px; position:relative;">
</div>
</body>
</html>

Explanation:
The <div> moves right (250px)
Changes size and opacity
Animation runs at slow speed

Summary
The animate() method is used to create smooth, custom animations in jQuery.
It enhances user experience by making web pages more interactive.

3. How jQuery animate can be used to create custom animation?
Solution
jQuery animate() is used to create custom animations by gradually changing CSS properties of an element over time.
Multiple properties can be animated together.
The element must have position: relative/absolute/fixed to animate left or top.
Only numeric values can be animated.
Relative values like += and -= can be used.
Callback function runs after animation completes.

It works with the syntax:
$(selector).animate({ properties }, speed, callback);
Using this method, we can animate multiple CSS properties like width, height, margin, opacity, etc.

Example:

$("button").click(function(){
  $("div").animate({
    left: '250px',
    opacity: 0.5
  }, 2000);
});

4. How jQuery id selector can be used to select specific element?
Solution
The jQuery ID selector is used to select a single, unique element on a web page using its ID attribute.

Syntax
$("#id_name")
# → represents an ID selector
id_name → the unique ID of the element

Explanation
An ID must be unique in an HTML document.
The jQuery ID selector selects exactly one element with that ID.
It is faster than class selectors because it targets a single element directly.

Example
<p id="demo">Hello</p>
<script>
$("#demo").css("color", "red");
</script> 
This selects the element with id="demo" and changes its text color to red.

Tags

Post a Comment

0Comments

Post a Comment (0)