Menu

Unit 3: Web Technology II (12 Hours)

Computer Science - Class 12

This unit provides a comprehensive exploration of modern web technologies, covering both client-side scripting with JavaScript and server-side programming with PHP. Students will learn the fundamentals of web architecture, interactive web page development, and database integration, essential for building dynamic and robust web applications.

Unit 3: Web Technology II (12 Hours)

3.1 Introduction

The World Wide Web is a vast network of interconnected documents and other web resources, identified by URLs, and accessed via the Internet. To build and interact with this web, several core technologies are employed. This section provides an overview of these fundamental concepts.

Overview of Web Technologies

  • HTML (HyperText Markup Language): The standard markup language for creating web pages. It provides the structure of the content.
  • CSS (Cascading Style Sheets): Used for describing the presentation of a document written in HTML. It handles the layout, colors, fonts, and overall visual appearance.
  • JavaScript: A high-level, interpreted programming language primarily used to make web pages interactive. It runs on the client-side (in the user's browser).
  • PHP (Hypertext Preprocessor): A popular general-purpose scripting language especially suited to web development. It runs on the server-side, generating dynamic content.

Static vs Dynamic Web Pages

  • Static Web Pages:
    • Content remains constant for every user until a developer manually updates it.
    • Typically built with HTML and CSS.
    • Faster loading times as there's no server-side processing.
    • Examples: Online resumes, portfolios, simple informational sites.
  • Dynamic Web Pages:
    • Content changes based on user interaction, time, or data from a database.
    • Involves server-side scripting (PHP, Python) and often client-side scripting (JavaScript) to interact with databases and generate personalized content.
    • Examples: E-commerce sites, social media platforms, online banking, blogs.

How Web Works: Client-Server Model, HTTP Request/Response Cycle

The web operates on a client-server model. A "client" (typically a web browser) sends a "request" to a "server," which then processes the request and sends back a "response."

  1. Client (Browser) Request: When you type a URL into your browser or click a link, your browser sends an HTTP request to the web server hosting that website. This request includes information like the requested resource (e.g., index.html), browser type, and user preferences.
  2. Server Processing: The web server receives the request.
    • For static pages, the server simply locates the requested HTML, CSS, and JavaScript files.
    • For dynamic pages, the server executes server-side scripts (e.g., PHP scripts) which might interact with databases to fetch or store data.
  3. Server Response: After processing, the server generates an HTTP response. This response includes the requested web page content (HTML, CSS, JavaScript), along with status codes (e.g., 200 OK, 404 Not Found), and other header information.
  4. Client (Browser) Rendering: The browser receives the response. It then parses the HTML, applies the CSS for styling, and executes any JavaScript to render the web page for the user.

This entire cycle is managed by the HTTP (Hypertext Transfer Protocol), which defines how messages are formatted and transmitted, and what actions web servers and browsers should take in response to various commands.

3.2 Server-side and Client-side Scripting

Web development involves two primary environments for executing code: the client-side (user's browser) and the server-side (web server).

Client-side Scripting

  • Runs in: User's web browser.
  • Languages: HTML (markup), CSS (styling), JavaScript (scripting).
  • Purpose: Enhances user experience, handles user interaction, manipulates the DOM, performs client-side validation, and makes asynchronous requests to the server.
  • Characteristics:
    • Fast: Code executes directly in the browser, reducing server load and network latency for interactive elements.
    • Less Secure: Code is visible to the user (view source), making it unsuitable for sensitive operations or storing confidential data.
    • Browser Dependent: Behavior can vary slightly across different browsers.
  • Practical Applications: Interactive forms, animations, dynamic content updates without page reload, client-side form validation.
<!-- Client-side JavaScript example -->
<button onclick="alert('Hello from Client-side!')">Click Me</button>
<script>
    // This JavaScript runs directly in your browser
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM is ready!');
    });
</script>

Server-side Scripting

  • Runs in: Web server.
  • Languages: PHP, Python (with frameworks like Django/Flask), ASP.NET, Node.js (JavaScript on server), Ruby (with Rails).
  • Purpose: Generates dynamic HTML content, interacts with databases, handles user authentication and authorization, processes form submissions, manages sessions, and performs complex business logic.
  • Characteristics:
    • Dynamic Content: Can generate unique HTML for each request based on data or user.
    • Secure: Code is not visible to the client, making it ideal for sensitive operations, database interactions, and business logic.
    • Resource Intensive: Requires server resources (CPU, memory) to execute scripts.
    • Platform Independent: Server-side languages often run on various operating systems.
  • Practical Applications: User registration/login, e-commerce transactions, content management systems (CMS), personalized dashboards.
<!-- Server-side PHP example -->
<?php
    $userName = "Guest";
    // In a real application, this might come from a database or session
    if (isset($_GET['name'])) {
        $userName = htmlspecialchars($_GET['name']);
    }
    echo "<h1>Welcome, " . $userName . "!</h1>";
?>
<p>This content was generated by the server.</p>

Comparison: Performance, Security, Use Cases

Feature Client-side Scripting Server-side Scripting
Execution Location Web browser Web server
Visibility of Code Visible (view source) Not visible
Security Less secure (prone to manipulation) More secure (business logic, database access)
Performance Faster for UI interactions (no server round-trip) Can be slower due to server processing and network latency
Access to Resources Limited to browser capabilities (DOM, local storage) Full access to server resources (database, file system)
Primary Use Cases UI/UX enhancements, client-side validation, dynamic content manipulation Database interaction, user authentication, complex business logic, dynamic page generation
Key Technologies HTML, CSS, JavaScript PHP, Python, Ruby, Node.js, ASP.NET
Both client-side and server-side scripting are crucial for modern web applications, often working in tandem to deliver a rich and secure user experience. Client-side handles immediate interactions, while server-side manages data, security, and complex logic.

3.3 Introduction to Internet Technology

Understanding the underlying technologies that power the internet is fundamental to web development.

WWW (World Wide Web), HTTP/HTTPS, URL Structure

  • WWW (World Wide Web): A system of interlinked hypertext documents and other web resources that are accessed via the Internet. It's an application built on top of the Internet.
  • HTTP (Hypertext Transfer Protocol): The foundation of data communication for the World Wide Web. It's the protocol used by web browsers and servers to communicate.
  • HTTPS (Hypertext Transfer Protocol Secure): An extension of HTTP that adds a layer of security through SSL/TLS encryption. It's essential for protecting sensitive data like passwords and credit card numbers.
  • URL Structure: A Uniform Resource Locator (URL) is an address that specifies the location of a resource on the internet and the mechanism for retrieving it.
    scheme://host:port/path?query#fragment
    • scheme: The protocol (e.g., http, https, ftp).
    • host: The domain name or IP address of the server (e.g., www.example.com).
    • port: The port number (optional, defaults to 80 for HTTP, 443 for HTTPS).
    • path: The specific resource's location on the server (e.g., /products/item123).
    • query: Parameters passed to the server (e.g., ?search=keyword&page=2).
    • fragment: An anchor to a specific part of a document (e.g., #section-two).

Web Servers (Apache, Nginx), Web Browsers, DNS Resolution Process

  • Web Servers: Software that stores website files and delivers web pages to clients (browsers) upon request.
    • Apache HTTP Server: A free and open-source cross-platform web server software, widely used and highly configurable.
    • Nginx (pronounced "engine-x"): A high-performance web server, reverse proxy, and load balancer, known for its efficiency and scalability, especially for high-traffic sites.
  • Web Browsers: Software applications used to access and view websites (e.g., Chrome, Firefox, Edge, Safari). They interpret HTML, CSS, and JavaScript to render web pages.
  • DNS Resolution Process (Domain Name System): The process of translating human-readable domain names (like www.example.com) into machine-readable IP addresses (like 192.0.2.1).
    1. User types a URL into the browser.
    2. The browser checks its local DNS cache. If not found, it queries the operating system.
    3. The OS checks its cache and then queries a local DNS resolver (often provided by your ISP).
    4. If the resolver doesn't have it, it queries a root DNS server.
    5. The root server directs to the Top-Level Domain (TLD) server (e.g., .com, .org).
    6. The TLD server directs to the authoritative name server for the domain (e.g., example.com).
    7. The authoritative name server provides the IP address for www.example.com.
    8. The IP address is returned through the chain to the browser, which then uses it to connect to the web server.

Hosting, Domain Names, Web Hosting Types

  • Hosting: The service of providing space on a server for a website to be stored and accessible on the internet.
  • Domain Names: Human-friendly names that identify websites (e.g., google.com). They are easier to remember than IP addresses.
  • Web Hosting Types:
    • Shared Hosting: Multiple websites share resources on a single server. Cost-effective but performance can be affected by other sites.
    • VPS (Virtual Private Server) Hosting: A physical server is divided into several virtual servers, each with dedicated resources. Offers more control and better performance than shared hosting.
    • Dedicated Hosting: An entire physical server is dedicated to a single website. Provides maximum performance, control, and security, but is more expensive.
    • Cloud Hosting: Resources are spread across multiple interconnected servers, offering high scalability and reliability.

3.4 Adding JavaScript to HTML Page

JavaScript can be integrated into an HTML document in several ways, each with its own advantages and use cases.

Inline JavaScript

JavaScript code is placed directly within an HTML tag's attribute, typically for event handlers.

<button onclick="alert('Hello Inline!')">Click Me</button>
<p onmouseover="this.style.color='red'" onmouseout="this.style.color='black'">Hover over me</p>

Pros: Quick for simple, single-use events. Cons: Not maintainable, mixes structure with behavior, hard to debug, not reusable.

Internal JavaScript

JavaScript code is placed within <script> tags directly inside the HTML document, usually in the <head> or <body> section.

<!DOCTYPE html>
<html>
<head>
    <title>Internal JS</title>
    <script>
        // JavaScript in the head
        function greetHead() {
            alert('Hello from the Head!');
        }
    </script>
</head>
<body>
    <h1>Welcome</h1>
    <button onclick="greetHead()">Greet from Head</button>

    <script>
        // JavaScript in the body
        function greetBody() {
            alert('Hello from the Body!');
        }
        document.write('<p>This text was added by internal JS.</p>');
    </script>
    <button onclick="greetBody()">Greet from Body</button>
</body>
</html>

Pros: Useful for page-specific scripts, no extra HTTP request. Cons: Can make HTML files large and less readable, not reusable across multiple pages.

External JavaScript

JavaScript code is written in a separate .js file and linked to the HTML document using the <script src="file.js"></script> tag.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>External JS</title>
    <!-- Link to external JavaScript file -->
    <script src="scripts.js"></script>
</head>
<body>
    <h1>External JavaScript Example</h1>
    <button id="myButton">Click for External JS</button>
</body>
</html>
// scripts.js
document.getElementById('myButton').onclick = function() {
    alert('Hello from External JS!');
};
console.log('External script loaded.');

Pros: Promotes code reusability, separation of concerns (HTML for structure, JS for behavior), better maintainability, browser caching of JS files. Cons: Requires an extra HTTP request to fetch the script.

Placement Matters (Load Order, DOM Readiness)

The placement of <script> tags significantly affects when the JavaScript code executes and whether it can access HTML elements.

  • In <head>: Scripts here execute before the HTML <body> content is parsed. If the script tries to manipulate DOM elements that haven't been loaded yet, it will fail. To avoid this, use defer or async attributes, or wrap code in DOMContentLoaded event listener.
  • At the end of <body>: This is generally the recommended practice for traditional scripts. The HTML content is fully parsed and available when the script executes, allowing it to safely interact with the DOM.
  • async attribute: (For external scripts) Downloads the script asynchronously and executes it as soon as it's downloaded, without blocking HTML parsing. Order of execution is not guaranteed.
  • defer attribute: (For external scripts) Downloads the script asynchronously but executes it only after the HTML document has been fully parsed. Execution order is preserved for deferred scripts.
<!DOCTYPE html>
<html>
<head>
    <title>JS Placement</title>
    <!-- This script will run AFTER the HTML is parsed -->
    <script src="script_defer.js" defer></script>
    <!-- This script might run before or after the HTML, depending on network -->
    <script src="script_async.js" async></script>
</head>
<body>
    <h1 id="title">Hello World</h1>
    <script>
        // This will work because the h1 is already in the DOM
        document.getElementById('title').style.color = 'blue';
    </script>
</body>
</html>

3.5 JavaScript Fundamentals

JavaScript has a set of core rules and constructs that form the basis of its programming.

Case Sensitivity, Comments, Semicolons

  • Case Sensitivity: JavaScript is case-sensitive. myVariable is different from myvariable.
    let myVar = 10;
    // console.log(MyVar); // This would cause an error (ReferenceError: MyVar is not defined)
    console.log(myVar); // Correct
    
  • Comments: Used to explain code and make it more readable. Ignored by the JavaScript engine.
    • Single-line comments: Start with //
      // This is a single-line comment
      let x = 5; // Assigns 5 to x
      
    • Multi-line comments: Start with /* and end with */
      /*
      This is a multi-line comment.
      It can span across several lines.
      */
      let y = 10;
      
  • Semicolons: Used to terminate statements. While often optional due to Automatic Semicolon Insertion (ASI), it's best practice to use them to avoid potential bugs.
    let a = 10;
    let b = 20; // Semicolon is good practice
    console.log(a + b) // No semicolon here might work, but is risky
    

Variables (var, let, const)

Variables are containers for storing data values.

  • var: (Oldest way) Declares a function-scoped variable. Can be re-declared and re-assigned. Has hoisting issues.
    var oldVar = "I'm old";
    var oldVar = "I can be re-declared"; // Legal but can lead to bugs
    oldVar = "I can be re-assigned";
    
  • let: Declares a block-scoped variable. Cannot be re-declared in the same scope, but can be re-assigned.
    let newVar = "I'm new";
    // let newVar = "Cannot be re-declared"; // SyntaxError
    newVar = "I can be re-assigned";
    
  • const: Declares a block-scoped constant. Cannot be re-declared or re-assigned after initialization. Must be initialized at declaration.
    const myConst = "I'm constant";
    // myConst = "Cannot be re-assigned"; // TypeError
    // const anotherConst; // SyntaxError: Missing initializer
    

Console.log, alert, prompt, document.write

  • console.log(): Outputs messages to the browser's developer console. Essential for debugging.
    console.log("This is a log message.");
    let num = 123;
    console.log("The number is:", num);
    
  • alert(): Displays a modal dialog box with a message and an "OK" button. Blocks further execution until dismissed.
    alert("Warning! This is an alert.");
    
  • prompt(): Displays a modal dialog box asking for user input, with a message, an input field, and "OK"/"Cancel" buttons. Returns the input string or null.
    let userName = prompt("Please enter your name:", "Guest");
    if (userName) {
        console.log("Hello, " + userName);
    } else {
        console.log("User cancelled the prompt.");
    }
    
  • document.write(): Writes HTML expressions or JavaScript code directly to an HTML document. Should generally be avoided after the document has loaded, as it can overwrite existing content.
    document.write("<h2>Content added by JS!</h2>");
    

String Concatenation, Template Literals

  • String Concatenation: Joining two or more strings together using the + operator.
    let firstName = "John";
    let lastName = "Doe";
    let fullName = firstName + " " + lastName; // "John Doe"
    console.log("My name is " + fullName + ".");
    
  • Template Literals (Template Strings): Introduced in ES6, enclosed by backticks (` `). Allow for embedded expressions and multi-line strings.
    let item = "Laptop";
    let price = 1200;
    let message = `The ${item} costs $${price}.`; // Embedded expressions
    console.log(message);
    
    let multiLine = `
        This is a
        multi-line
        string.
    `;
    console.log(multiLine);
    

3.6 JavaScript Data Types

Data types classify the different kinds of values that can be stored and manipulated in a programming language.

Primitive Data Types

Primitive types are immutable and represent a single value.

  • Number: Represents both integer and floating-point numbers.
    let age = 30; // Integer
    let price = 19.99; // Float
    let bigNum = 1000000000000000; // Large number
    
  • String: Represents textual data. Enclosed in single quotes (' '), double quotes (" "), or backticks (` `).
    let name = "Alice";
    let greeting = 'Hello, World!';
    let quote = `He said, "It's a beautiful day."`;
    
  • Boolean: Represents a logical entity, either true or false.
    let isActive = true;
    let hasPermission = false;
    
  • Undefined: Represents a variable that has been declared but not yet assigned a value.
    let myVariable;
    console.log(myVariable); // Output: undefined
    
  • Null: Represents the intentional absence of any object value. It's a primitive value.
    let emptyValue = null;
    console.log(emptyValue); // Output: null
    
  • Symbol (ES6): A unique and immutable data type, often used to create unique object property keys.
    const id = Symbol('id');
    const anotherId = Symbol('id');
    console.log(id