# GTU IT Sem 5 Web Development (WD) WINTER 2022 Paper Solution | 3151606

Q1.

(a) - Define term: WWW (3 marks)**

  • WWW stands for World Wide Web. It's a system of linked web pages and various content you access on the internet.
  • These pages can contain text, images, videos, and other types of multimedia content.
  • When you open your web browser, you're essentially tapping into this web of information.
  • Beyond information retrieval, the WWW serves as a platform for communication.

(b) Explain the Architecture of Web Browser.

what-is-browser.png

The architecture of a web browser contains various components that collaboratively enable the user's interaction with the internet.

  1. User Interface (UI): The graphical interface presenting buttons, address bar, and bookmarks for user interaction.
  2. Browser Engine: Manages communication between the UI and the rendering engine, determining actions in response to user inputs.
  3. Rendering Engine: Responsible for displaying content on the screen, interpreting HTML, CSS, and other web languages.
  4. Networking: Handles communication with the server, fetching files, and managing data transfer.
  5. JavaScript Interpreter: Executes JavaScript code embedded in web pages, enabling dynamic and interactive content.
  6. UI Backend: Manages basic UI elements like buttons and text boxes.
  7. Data Storage: Stores cookies, cache, and other data, contributing to user preferences and browsing history.

Q1. (c) - Elaborate HTTP Protocol Header, HTTP Request, and HTTP Response (7 marks)

1. HTTP Protocol Header:

The HTTP protocol header is a set of rules that govern the communication between a client (e.g., a web browser) and a server. It is a crucial part of the HTTP protocol as it contains metadata about the HTTP message being sent. The header is composed of key-value pairs, where each key provides information about the associated value.

Common components of the HTTP header include:

  • Request/Response Line: Specifies whether it's a request or a response, along with the HTTP version.
  • Headers: These include additional information about the message, such as:
    • Host: The domain name of the server.
    • User-Agent: Information about the client making the request.
    • Accept: The types of media that the client can process.
    • Content-Type: The media type of the resource in the body of the request or response.
  • Cookies: Information stored on the client-side and sent with each subsequent request.

2. HTTP Request:

An HTTP request is a message sent by the client to request a particular action from the server. It comprises several parts:

  • Request Line: Specifies the HTTP method (e.g., GET, POST) and the target resource (Uniform Resource Identifier, URI).
  • Request Headers: Provide additional information about the request, such as:
    • Accept: The expected content types.
    • Authorization: Credentials for access control.
    • Content-Type: The media type of the request body.
  • Request Body (Optional): Some requests, like POST or PUT, may include data in the body. For example, when submitting a form or sending JSON data.

3. HTTP Response:

An HTTP response is a message sent by the server to fulfill the client's request. It also consists of several parts:

  • Status Line: Contains the HTTP version, a status code (indicating the result of the request), and a corresponding status message.
  • Response Headers: Provide additional information about the response, similar to request headers. Common headers include:
    • Content-Type: The media type of the response body.
    • Content-Length: The size of the response body in bytes.
    • Server: Information about the server software.
  • Response Body (Optional): Contains the requested data or a message. For example, HTML content for a web page or JSON data.

Q2.

(a) Define term: SEO (3 marks)

SEO (Search Engine Optimization):

SEO, which stands for Search Engine Optimization, is a set of practices and strategies aimed at improving the visibility and ranking of a website or web page on search engine results pages (SERPs).

The primary goal of SEO is to enhance the likelihood of a website being found by users when they search for relevant keywords or phrases on search engines like Google, Bing, or Yahoo.

It involves practices such as keyword optimization, content improvement, and technical enhancements. The goal is to increase organic traffic by ranking higher for relevant search queries.

(b) Explain ordered and unordered list with example. (4 marks)

Ordered List:

An ordered list is a list in which the sequence or order of items is important. Each item in the list is preceded by a numerical or alphabetical identifier. In HTML, the <ol> (ordered list) tag is used to create an ordered list, and each list item is defined using the <li> (list item) tag.

Example of an ordered list in HTML:

<ol>
  <li>First item</li>
  <li>Second item</li>
  <li>Third item</li>
</ol>

The rendered output would be:

  1. First item
  2. Second item
  3. Third item

Unordered List:

An unordered list is a list where the sequence or order of items is not crucial. In an unordered list, each item is typically preceded by a bullet point or some other marker. In HTML, the <ul> (unordered list) tag is used to create an unordered list, and each list item is defined using the <li> (list item) tag.

Example of an unordered list in HTML:

<ul>
  <li>Red</li>
  <li>Green</li>
  <li>Blue</li>
</ul>

The rendered output would be:

  • Red
  • Green
  • Blue

(c) Give the difference between Client side Scripting and Server Side

Scripting. (7 marks)

FeatureClient-Side ScriptingServer-Side Scripting
DefinitionScripts executed on the client's browser.Scripts executed on the web server.
Execution LocationRuns on the user's browser.Executes on the web server.
Visibility and SecuritySource code is visible, potentially less secure.Source code is not visible, more secure.
ResponsivenessEnhances user interactivity without server communication.Requires server communication, may have slower response time.
Use CasesUI interactions, form validations, dynamic content presentation.Form submissions, database interaction, business logic.
Device IndependenceOffers consistent experience across devices.Experience may vary based on server processing.
ExamplesJavaScript, HTML, CSS.PHP, Python, Ruby, ASP.NET.

OR

(c) What is selector class ? Explain the pseudo class selector in CSS with

example

Selector Class:

A selector class in CSS is a way to select and style HTML elements based on the presence of a specific class attribute. Classes are used to group elements that share a common set of styles or behavior. By applying a class selector in CSS, you can target and style all elements with that particular class.

Example of a selector class in CSS:

.example{ color: red; font-weight: bold; } // This will select all elements in
html having class example like: //
<p class="example">This is just a demo</p>

The paragraph element above will have red text and bold font weight as per the styles defined in the ‘.example' class

Pseudo-Class Selector in CSS:

A pseudo-class selector in CSS is used to select and style elements based on their state or position. Pseudo-classes begin with a colon (:) and are applied to specific elements under certain conditions. Common pseudo-classes include :hover for styling elements when hovered over and :nth-child() for selecting elements based on their position in a parent container.

Example of a pseudo-class selector in CSS:

/* Style a link when hovered over */
a:hover {
  color: blue;
  text-decoration: underline;
}

The :hover pseudo-class is used to style anchor (<a>) elements when they are hovered over (when cursor is on top of the a tag) by the user.

<!-- HTML with a link -->
<a href="#">Hover over me</a>

When the user hovers over the link, the styles defined in the :hover pseudo-class will be applied.

Q3.

(a) What is meta tag? How it is useful by search engine? 03

Meta Tag:

A meta tag is an HTML tag that provides metadata about an HTML document. Placed within the <head> section of an HTML page, meta tags contain information that is not visible on the web page itself but provides instructions or data for browsers, search engines, and other web services.

Some important meta tags:

<meta name="description" content="A brief description of the webpage" />
<meta name="keywords" content="keyword1, keyword2, keyword3" />
<meta charset="UTF-8" />

Page Description:

  • The meta tag is commonly used to specify a brief description of the webpage using the description attribute.

Keywords for Search Indexing:

  • The meta tag with the keywords attribute helps search engines understand the main keywords associated with the webpage.

Character Set Specification:

  • The meta tag is crucial for specifying the character set used in the document (charset).

(b) What is Cascading Style Sheet? Compare inline, embedded and external

style sheet with example (4 marks)

CSS (Cascading Style Sheets):

CSS is a style sheet language that controls the visual presentation of HTML or XML documents, defining how elements are styled and displayed on a webpage.

Using CSS, we can select elements based on their id (’#’) or their class (’.’) to style them

  1. Inline Style:
  • Definition: Inline styles are applied directly to individual HTML elements using the style attribute within the HTML tag.
  • Example:
<p style="color: blue; font-size: 16px;">
  This is a paragraph with inline styles.
</p>
  1. Embedded (Internal) Style:
  • Definition: Embedded styles are defined within the HTML document using the <style> tag in the head section. The styles apply to elements on that specific page.
  • Example:
<head>
  <style>
    p {
      color: green;
      font-size: 18px;
    }
  </style>
</head>
<body>
  <p>This is a paragraph with embedded styles.</p>
</body>
  1. External Style:
  • Definition: External styles are stored in a separate CSS file and linked to the HTML document. This promotes a clean separation of content and presentation and allows the same styles to be used across multiple pages.
  • Example:

index.html file

<!-- In the HTML document -->
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="styles.css" />
  </head>
</html>

styles.css file

// In the external CSS file (styles.css)
p {
  color: red;
  font-size: 20px;
}

(c) Define Frameset, Frame Tag. Divide the web page into four equal parts

each individual part displays different web page. (7 marks)

  • Frameset:
    • A frameset in HTML is used to divide a webpage into multiple frames or sections, each capable of displaying a separate HTML document. Framesets provide a way to create a layout with multiple, independent sections.
  • Frame Tag:
    • The <frame> tag is used within a frameset to define each individual frame and specify the content (HTML document) that should be displayed within that frame.

Dividing the Web Page into Four Equal Parts (Example):

<!DOCTYPE html>
<html>
<head>
  <title>Multi-Frame Webpage</title>
</head>
<frameset cols="50%, 50%" rows="50%, 50%">
  <!-- Top-left frame -->
  <frame src="page1.html" name="frame1" scrolling="auto">

  <!-- Top-right frame -->
  <frame src="page2.html" name="frame2" scrolling="auto">

  <!-- Bottom-left frame -->
  <frame src="page3.html" name="frame3" scrolling="auto">

  <!-- Bottom-right frame -->
  <frame src="page4.html" name="frame4" scrolling="auto">
</frameset>
</html>

OR

Q.3 (a) Write CSS code for the following:

i) set the background color for the hover and active link states to "yellow"

/* Hover state */
a:hover {
  background-color: yellow;
}

/* Active state */
a:active {
  background-color: yellow;
}

ii) Set the list style for unordered lists to "square”

ul {
  list-style-type: square;
}

iii) Set "paper.gif" as the background image of the page:

body {
  background-image: url("paper.gif");
}

(b) Explain Wildcard Selectors (*, ^ and $) in CSS. (4 marks)

Asterisk (*) Wildcard Selector:

  • The asterisk (*) is a wildcard selector that targets all elements on a web page. It applies styles to every HTML element, making it a universal selector.
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

Caret (^) Wildcard Selector:

  • The caret (^) is typically used in conjunction with attribute selectors to select elements based on the starting characters of their attribute values.
[class^="prefix"] {
  color: red;
}

This selects elements whose "class" attribute starts with the specified prefix and applies a red color.

Dollar Sign ($) Wildcard Selector:

  • It is used in attribute selectors to select elements based on the ending characters of their attribute values.
[class$="suffix"] {
  font-weight: bold;
}

This selects elements whose "class" attribute ends with the specified suffix and applies bold font-weight.

(c) Write an HTML and JavaScript program which accepts N as input and

print first N odd numbers. (7 marks)

<!DOCTYPE html>
<head>
  <title>Print First N Odd Numbers</title>
</head>
<body>

  <h2>Enter a number (N):</h2>
  <input type="number" id="numberInput" min="1">
  <button onclick="printOddNumbers()">Print Odd Numbers</button>

  <h2>Result:</h2>
  <div id="result"></div>

  <script src="odd.js"></script>

</body>
</html>

odd.js 👇

function printOddNumbers() {
  // Get the value of N from the input field
  var n = document.getElementById("numberInput").value;

  // Initialize variables
  var oddNumbers = [];

  // Loop to find first N odd numbers using a for loop
  for (var i = 1; oddNumbers.length < n; i++) {
    // Loop until oddNumbers have n elements
    if (i % 2 !== 0) oddNumbers.push(i); // If it is not an ODD number (so it's an even number)
  }

  // Display the result
  document.getElementById("result").innerHTML =
    "First " + n + " odd numbers: " + oddNumbers.join(", ");
}

Q4.

(a) Define term : JSON (3 marks)

JSON, or JavaScript Object Notation, is a text-based data format that represents structured data in a key-value pair format. JSON is often used to transmit data between a server and a web application, as well as for configuration files and data storage.

  • JSON is language-independent
  • JSON is easy for humans to read and write

Example:

{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}

(b) Write a java script code to find whether given number is prime or not. (4 marks)

function isPrime(number) {
  if (number <= 1) return false; // Number 1 or less than 1 can't be a PRIME number
  for (var i = 2; i <= Math.sqrt(number); i++) {
    if (number % i === 0) return false;
  }
  return true;
}

// Example usage:
var inputNumber = 17; // Replace with the number you want to check
console.log(
  isPrime(inputNumber)
    ? inputNumber + " is a prime number."
    : inputNumber + " is not a prime number."
);

Function isPrime:

  • The function takes a number as an argument (number).
  • It checks if the number is less than or equal to 1. If so, it returns false because numbers less than or equal to 1 are not prime.
  • It then uses a for loop to iterate from 2 to the square root of the given number.
  • Inside the loop, it checks if the number is divisible evenly by any value within the loop (number % i === 0). If so, it means the number has a factor other than 1 and itself, so the function returns false.
  • If no factors are found, the function returns true, indicating that the number is prime.

(c) Explain pop-up boxes in javascript with example. (7 marks)

JavaScript provides three types of pop-up boxes that are commonly used for interacting with users: alert, confirm, and prompt. These pop-up boxes are modal, meaning they pause the execution of the script until the user interacts with them.

Pop-up Boxes in JavaScript:

JavaScript provides three types of pop-up boxes that are commonly used for interacting with users: alert, confirm, and prompt. These pop-up boxes are modal, meaning they pause the execution of the script until the user interacts with them.

  1. alert Box:

    • The alert box is used to display a message to the user. It provides an OK button for the user to acknowledge the message.

    Example:

    alert("This is an alert box!");
  2. confirm Box:

    • The confirm box is used to ask the user for confirmation. It displays a message and provides OK and Cancel buttons.

    Example:

    var userConfirmation = confirm("Do you want to proceed?");
    if (userConfirmation) {
      console.log("User clicked OK.");
    } else {
      console.log("User clicked Cancel.");
    }
  3. prompt Box:

    • The prompt box is used to prompt the user to enter some input. It displays a message, an input field, and OK and Cancel buttons.

    Example:

    var userInput = prompt("Please enter your name:", "John Doe");
    if (userInput !== null) {
      console.log("User entered: " + userInput);
    } else {
      console.log("User clicked Cancel.");
    }

OR

Q.4 (a) Interpret PHP Function: Implode and Explode (03 marks)

In PHP, implode and explode are two functions used to handle strings and arrays.

  1. implode Function:

    • The implode function is used to join elements of an array into a single string. It takes two parameters: the glue string and the array.

    Example:

    $colors = array('red', 'green', 'blue');
    <math>result = implode(', ', </math>colors);
    echo $result;

    Output:

    red, green, blue
  2. explode Function:

  • The explode function is used to split a string into an array. It takes two parameters: the delimiter string and the input string. Example: php $text = "apple, orange, banana"; <math>fruits = explode(', ', </math>text); print_r($fruits); Output: php Array ( [0] => apple [1] => orange [2] => banana )

(b) Differentiate GET and POST methods. (4 marks)

CharacteristicGET MethodPOST Method
Data in URLAppended to the URL as parametersIncluded in the http request body, so not visible in URL
Data LengthLimited by browser and server constraintsTypically allows larger data
CachingCan be cached and bookmarkedNot cached and cannot be bookmarked
SecurityLess secure for sensitive dataMore secure for sensitive data
Use CaseSuitable for retrieving data or navigatingSuitable for submitting sensitive or large data, modifying server-side data

(c) Prepare a java script solution to validate registration form including

email address entered by user. (7 marks)

index.html file

<!DOCTYPE html>
<head>
  <title>Registration Form</title>
</head>
<body>

  <h2>Registration Form</h2>
  <form id="registrationForm" onsubmit="return validateForm()">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>
    <br>

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

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

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

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

  <script src="validation.js" />
</body>
</html>

validation.js file

function validateForm() {
  var username = document.getElementById("username").value;
  var email = document.getElementById("email").value;
  var password = document.getElementById("password").value;
  var confirmPassword = document.getElementById("confirmPassword").value;

  // Simple email validation using a regular expression
  var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    alert("Please enter a valid email address.");
    return false;
  }

  // Basic password confirmation
  if (password !== confirmPassword) {
    alert("Passwords do not match.");
    return false;
  }

  // If all validations pass, the form is submitted
  alert("Registration successful!");
  return true;
}

Q5.

(a) Define term: JQUERY (3 marks)

  1. Definition:
    • jQuery is a fast and lightweight JavaScript library.
  2. DOM Manipulation:
    • Simplifies DOM manipulation, making it easier to select and modify HTML elements.
  3. Event Handling:
    • Provides a concise syntax for attaching event handlers to respond to user interactions.

Example -

$("#myElement").text("Hello, jQuery!");

Changes the text content of an element with the ID "myElement" using jQuery.

(b) Prepare a PHP Code to read and write content from File. (4 marks)

<?php
// File path
$filePath = 'example.txt';

// Writing content to a file
$contentToWrite = "This is some content to write to the file.\n";
file_put_contents(<math>filePath, </math>contentToWrite, FILE_APPEND);

// Reading content from a file
<math>readContent = file_get_contents(</math>filePath);

// Displaying the read content
echo "Content read from the file:\n";
echo $readContent;
?>

(c) Prepare a PHP Code to manage online shopping cart using session. (7 marks)

// SIDENOTE: IF PROGRAM SEEMS TO BE VERY LARGE, YOU CAN OMIT THE displayCart() function
<?php
// Start or resume the session
session_start();

// Function to add a product to the cart
function addToCart(<math>productId, </math>productName, <math>price, </math>quantity) {
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = [];
    }

    // Check if the product is already in the cart
    if (isset(<math>_SESSION['cart'][</math>productId])) {
        // Update quantity if the product is already in the cart
        <math>_SESSION['cart'][</math>productId]['quantity'] += $quantity;
    } else {
        // Add the product to the cart
        <math>_SESSION['cart'][</math>productId] = [
            'productName' => $productName,
            'price' => $price,
            'quantity' => $quantity
        ];
    }
}

// Function to display the cart contents
function displayCart() {
    echo "<h2>Shopping Cart</h2>";
    if (isset(<math>_SESSION['cart']) && !empty(</math>_SESSION['cart'])) {
        echo "<ul>";
        foreach (<math>_SESSION['cart'] as </math>productId => $product) {
            echo "<li>{<math>product['productName']} - Quantity: {</math>product['quantity']} - Price: \<math>{</math>product['price']}</li>";
        }
        echo "</ul>";
    } else {
        echo "<p>Your cart is empty.</p>";
    }
}

// Function to clear the cart
function clearCart() {
    $_SESSION['cart'] = [];
    echo "<p>Cart cleared.</p>";
}

// Example usage
addToCart(1, 'Product A', 19.99, 2);
addToCart(2, 'Product B', 29.99, 1);

// Display the cart
displayCart();

// Clear the cart (uncomment the line below to test clearing the cart)
// clearCart();
?>

OR

Q.5 (a) Define term: AJAX (3 marks)

AJAX (Asynchronous JavaScript and XML):

  • AJAX is a web development technique that allows for asynchronous communication between a web browser and a web server.
  • It enables updating parts of a web page without requiring a full page reload.
  • AJAX is commonly used to fetch data from a server and dynamically update content on a web page
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
CharacteristicCookieSession
Storage LocationStored on the client sideStored on the server side
Data PersistenceCan be persistent or session-basedTypically session-based
ExpirationDepends on set expiration (persistent) or session (session-based)Typically expires on browser close or after a defined period of inactivity
SecurityMay pose security risks due to client-side storageGenerally considered more secure as data is stored on the server
Use CasesSuitable for storing small amounts of non-sensitive informationSuitable for storing sensitive information and larger data

(c) Develop a web page which contains two list box. First list ask to select

State and according to state selection second list box loads name of city. Develop it using AJAX. (7 marks)

index.html file

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>State and City Selection</title>
    <script src="script.js"></script>
  </head>
  <body>
    <h2>State and City Selection</h2>

    <label for="stateSelect">Select State:</label>
    <select id="stateSelect">
      <option value="ny">New York</option>
      <option value="ca">California</option>
    </select>

    <label for="citySelect">Select City:</label>
    <select id="citySelect"></select>
  </body>
</html>

script.js file

document.addEventListener("DOMContentLoaded", function () {
  function loadCities(state) {
    var cities =
      state === "ny"
        ? ["New York City", "Albany", "Buffalo"]
        : ["Los Angeles", "San Francisco", "San Diego"];
    var citySelect = document.getElementById("citySelect");
    citySelect.innerHTML = cities
      .map(function (city) {
        return (
          '<option value="' +
          city.toLowerCase().replace(/\s+/g, "") +
          '">' +
          city +
          "</option>"
        );
      })
      .join("");
  }

  var stateSelect = document.getElementById("stateSelect");
  stateSelect.addEventListener("change", function () {
    loadCities(stateSelect.value);
  });

  loadCities(stateSelect.value);
});