CSC 318 Web Technology: Navigating Key Terms and Concepts

CSC 318 Web Technology: Navigating Key Terms and Concepts

50+ Must-Know Terms and Complete Web Technology Unpacked

Abstract:

This article provides an overview of over 50 fundamental web technology terms and concepts. It explores various topics and sub-topics related to web technology. This comprehensive detailed overview is a valuable reference for understanding key terms, ideas, and topics simply and concisely.?

1. Introduction to Web Technology

The World Wide Web has undergone a remarkable transformation since its inception, evolving from static HTML pages to dynamic, interactive platforms that power much of our daily digital interactions. This evolution has been driven by a continuous stream of innovative web technologies, each pushing the boundaries of what’s possible in online experiences.

1.1 Web Basics: Internet, Intranet, WWW, Static and Dynamic Web?Page

1.1.1 Internet

  • A global network of interconnected computers that enables communication and access to information worldwide.
  • Uses various protocols (TCP/IP, HTTP, etc.) to facilitate data transmission.
  • Offers diverse services like email, web browsing, file sharing, and online gaming.

1.1.2 Intranet

  • A private network within an organization that uses Internet technologies but is accessible only to authorized users within the organization.
  • Provides a secure platform for internal communication, collaboration, and resource sharing.
  • Often includes features like company directories, document repositories, and project management tools.

1.1.3 World Wide Web?(WWW)

The World Wide Web, often simply called the Web, is a system of interconnected documents and other resources accessed via the Internet. It’s a vast collection of information, multimedia, and applications accessible through web browsers. The key to the Web is its use of hypertext links, which allow users to navigate seamlessly from one document to another.

Key components of the WWW:

  • Hypertext: Text with embedded links that allow users to jump to other related documents.
  • HTTP (Hypertext Transfer Protocol): The protocol used for communication between web clients and servers.
  • HTML (Hypertext Markup Language): The standard markup language for creating web pages.
  • URL (Uniform Resource Locator): The address of a resource on the internet.

1.1.4 Static Web?Page

  • A web page with fixed content that remains the same for all users and does not change dynamically in response to user interactions or server-side processes.
  • Typically created using HTML (Hypertext Markup Language) and CSS (Cascading Style Sheets).
  • Examples include simple landing pages, brochures, and informational websites.

1.1.5 Dynamic Web?Page

  • A web page whose content can change based on user input, server-side scripts, or database interactions.
  • Often uses programming languages like PHP, JavaScript, and server-side scripting technologies like ASP.NET or JSP.
  • Examples include e-commerce websites, content management systems, and social media platforms.

1.2 Web Client and Web?Server

1.2.1 Web?Client

A web client is a software application that communicates with a web server to access and display web resources. It’s essentially the tool we use to interact with the web.

Common examples of web clients:

  • Web browsers: The most common type, such as Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge.
  • Mobile apps: Many apps access web-based services, acting as clients.
  • Web-based email clients: These use a web browser to access email services.

How it works:

  1. A user interacts with the web client (e.g., clicks a link).
  2. The client sends a request to a web server using HTTP.
  3. The server processes the request and sends back the requested data (e.g., a webpage).
  4. The client displays the data to the user.

1.2.3 Web?Server

A web server is a computer program that serves web pages to users. It stores the website’s files and processes requests from web clients.

Key functions of a web server:

  • Stores website content: Includes HTML files, images, CSS, JavaScript, and other resources.
  • Processes HTTP requests: Receives requests from clients and determines the appropriate response.
  • Delivers content: Sends the requested files to the client.
  • Handles dynamic content: Can process scripts and databases to generate content on the fly.

Popular web server software:

  • Apache HTTP Server
  • Nginx
  • Microsoft IIS

In essence:

  1. The WWW is a vast interconnected network of information.
  2. Web clients are the tools we use to access it.
  3. Web servers are the computers that store and deliver the content.

1.4 HTTP: HTTP Request and?Response

1.4.1 HTTP?Protocol

HTTP (Hypertext Transfer Protocol) is the foundation of the World Wide Web. It’s a protocol for transferring data between a client (usually a web browser) and a server. It defines how messages are formatted and transmitted, and what actions web servers and browsers should take in response to various commands.

1.4.2 HTTP?Request

An HTTP request is a message sent from a client to a server to request a resource. It includes:

  • Method: The action to be performed (GET, POST, PUT, DELETE, etc.)
  • URI (Uniform Resource Identifier): The path to the resource
  • HTTP Version: The version of HTTP being used
  • Headers: Additional information about the request (e.g., content type, cookies)
  • Body: Optional data, often used for POST requests

1.4.3 HTTP?Response

An HTTP response is a message sent from a server to a client in response to a request. It includes:

  • Status Code: Indicates the status of the request (e.g., 200 OK, 404 Not Found)
  • HTTP Version: The version of HTTP being used
  • Headers: Additional information about the response (e.g., content type, content length)
  • Body: The requested data or an error message

1.4.4 Example of a simple HTTP?request:

GET /index.html HTTP/1.1
Host: www.example.com
Example of a simple HTTP response:
HTTP/1.1 200 OK
Content-Type: text/html

<!DOCTYPE html>
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>        

Essentially, HTTP is the language used for communication between web browsers and servers, enabling the seamless exchange of information that powers the internet.

1.5 URL (Uniform Resource?Locator)

  • Definition: A URL is the web address used to locate a resource on the internet. It specifies the protocol, domain name, and path to the desired resource.
  • Example: https://www.example.com/index.html
  • https is the protocol.
  • www.example.com is the domain.
  • /index.html is the file path.

1.5.1 URL (Uniform Resource Locator). Client-Side Scripting

  • Definition: Code that runs directly in the user’s browser to create interactive elements and dynamic web pages. It is typically written in languages like JavaScript.
  • Example: A form validation script that checks if a user has filled in required fields before submitting.
  • Code: A JavaScript function that alerts users to fill out missing fields.

1.5.2 Server-Side Scripting

  • Definition: Code executed on the server before the web page is sent to the user’s browser. It is used to interact with databases, manage user sessions, and generate dynamic content.
  • Example: A PHP script that retrieves user data from a database and displays it on a webpage.
  • Code: PHP code to query a MySQL database for user details and render them in HTML.

1.6 Web 1.0 and Web?2.0

1.6.1 Web?1.0?

Often referred to as the “Read-Only Web,” Web 1.0 was primarily about consuming information. Websites were static, with limited interaction and user-generated content. Key characteristics include:

  • Static content: Information was primarily text-based and rarely updated.
  • Limited interaction: Users could mainly read information but couldn’t contribute.
  • Focus on information: Websites were primarily used as online brochures.
  • Examples: Early websites, and online encyclopedias like Britannica.

1.6.2 Web 2.0 and Its?Services

Web 2.0 is a paradigm shift from passive consumption of content to active participation and collaboration. It introduced bidirectional services that revolutionized how we interact online.

Here are some key Web 2.0 services:

Social Networking

  • Platforms: Facebook, Twitter, Instagram, LinkedIn, TikTok
  • Features: User profiles, friend connections, messaging, content sharing, groups, and communities.

Content Sharing

  • Video sharing: YouTube, Vimeo
  • Image sharing: Flickr, Instagram, Pinterest
  • Audio sharing: SoundCloud, Spotify
  • Document sharing: Google Drive, Dropbox

Web Applications

  • Online productivity: Google Docs, Sheets, Slides
  • Project management: Trello, Asana
  • Communication: Slack, Zoom

User-Generated Content

  • Blogs: WordPress, Blogger
  • Wikis: Wikipedia, MediaWiki
  • Social bookmarking: Delicious, Pinterest
  • Online forums and communities: Reddit, Quora

Other Notable Services

  • Mashups: Combining data from multiple sources to create new applications (e.g., Google Maps with real-time traffic data).
  • Web APIs: Allowing developers to access data and functionality from other websites (e.g., Twitter API).
  • Folksonomies: User-generated tagging systems (e.g., tagging photos on Flickr).

Key characteristics of Web 2.0 services:

  • User-centric: Focus on user participation and interaction.
  • Dynamic content: Content is constantly updated and evolving.
  • Collaboration: Encourages sharing and collaboration among users.
  • Rich media: Incorporates images, videos, and audio.

These services have transformed the way we communicate, consume information, and interact with each other online.

1.7 Client-server architecture

Client-server architecture is a model where clients (user devices) communicate with servers to access services or resources over a network.

1.7.1 Single-Tier Architecture

  • Definition: In single-tier architecture, the client and the server are combined into one system. The application, database, and user interface all reside on the same machine.
  • Example: A desktop application like Microsoft Word that runs entirely on the user’s computer.

1.7.2 Two-Tier Architecture

  • Definition: In a two-tier architecture, the client and server are separate entities. The client interacts directly with the server to access data or services, typically using database connections.
  • Example: A client application (e.g., a desktop database application) connecting directly to a database server (e.g., MySQL).

1.7.3 Multi-Tier (N-Tier) Architecture

  • Definition: Multi-tier architecture separates the application into multiple layers (tiers), often including the client, application server, and database server. This structure improves scalability, maintainability, and security.
  • Example: A web application where the user interacts with a web browser (client), which communicates with a web server (application tier) that retrieves data from a database server (data tier).
  • Common Setup: Three-tier architecture (client, server, database) is the most widely used multi-tier model.

2. Hyper Text Markup Language?(HTML)

2.1 Introduction to HTML; Elements of HTML?Document

HTML is the standard language used to create and design web pages. It structures content on the web by using elements and tags.

2.2 HTML Elements and Attributes

  • Headings: <h1>, <h2>,?..., <h6> for defining headers.
  • Paragraph: <p> to create paragraphs.
  • Division: <div> for sectioning content.

2.3 Formatting

  • Bold: <b> for bold text.
  • Italic: <i> for italicized text.
  • Small: <small> for smaller text.
  • Superscript: <sup> for text positioned above.
  • Subscript: <sub> for text positioned below.
  • Spacing:
  • Preformatted Text: <pre> preserves spaces and line breaks.
  • Line Break: <br> for breaking lines.

2.4 Formatting Text?Phrases

  • Span: <span> for inline elements to group text.
  • Strong: <strong> to emphasize important text.
  • Teletype/Text Typewriter: <tt> for monospaced font.

2.5 Image Element;?Anchors

  • Image: <img> to embed images on the page.
  • Anchors: <a> to create hyperlinks for navigation.

<img src="image.jpg" alt="Description of Image">
<a >This is a link to example.com</a>
<tt>This is teletype (monospaced) text.</tt>
<strong>This is strong (bold) text.</strong>
<span>This is inline text with a span tag.</span>
<br>
<sub>Subscript text</sub>
<small>This text is small.</small>
<i>This text is italic.</i>
<b>This text is bold.</b>
<div>This is a division block.</div>
<p>This is a paragraph.</p>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>        

2.6 Lists: Ordered, Unordered, and Definition

  1. <ol type=”1">: Creates an ordered list with numbers (1, 2, 3, etc.).

  • <li>Coffee:: The first list item.
  • <ul>: Creates a nested unordered list.
  • <li>: List items for “Coffee” with Roman numerals (I, II).

2. <li>Tea: The second list item.

  • <ol type=” A”>: Creates a nested ordered list with letters (A, B, C, etc.
  • <li>: List items for “Tea” with letters (A, B).

 <h1>List of Items</h1>
    <ol type="1">
        <li>Coffee:
            <ul>
                <li>I. Black coffee</li>
                <li>II. Green coffee</li>
            </ul>
        </li>
        <li>Tea
            <ol type="A">
                <li>Black tea</li>
                <li>Green tea</li>
            </ol>
        </li>
    </ol>        

2.7 Tables; Frames; Forms: Form Elements, ID attributes, Class Attributes

  • Definition: Tables in HTML are used to display data in rows and columns, making information easier to organize and understand.
  • Concept: A table consists of <table>, rows defined by <tr>, and cells defined by <td> for data or <th> for headers.

2.7.1 Inline?Frames

Inline frames (iframes) are HTML elements used to embed content from another website directly into our current webpage. Here are some reasons why iframes are used:

  • Embed external content
  • Reduce page load time
  • Content isolation
  • Dynamic content updates

Here’s an HTML page example using an iframe:

<!DOCTYPE html>
<html>
<head>
<title>Iframe Example</title>
</head>
<body>
<p>This paragraph contains an iframe from TUIOST website.</p>
<iframe src="https://www.tuiost.edu.np" width="400" height="200"></iframe>
</body>
</html>        

2.7.2 Forms

  • Definition: Forms are used to collect user input and send it to a server for processing.
  • Concept: HTML forms are created with, <form>, which contains various elements like text fields, radio buttons, checkboxes, and submit buttons. Each form element interacts with a backend to handle user input.

<!DOCTYPE html>
<html>
<head>
  <title>HTML Tables, Frames, and Forms</title>
  <style>
    .styled-paragraph {
      color: blue;
      font-weight: bold;
    }
    #unique-paragraph {
      color: red;
    }
  </style>
</head>
<body>
  
  <!-- Table Example -->
  <h2>HTML Table</h2>
  <table border="1">
    <tr>
      <th>Name</th>
      <th>Age</th>
    </tr>
    <tr>
      <td>John</td>
      <td>25</td>
    </tr>
    <tr>
      <td>Jane</td>
      <td>30</td>
    </tr>
  </table>

  <!-- Frame Example (deprecated) -->
  <!-- <frameset cols="50%,50%">
    <frame src="frame1.html">
    <frame src="frame2.html">
  </frameset> -->

  <!-- Form Example -->
  <h2>HTML Form</h2>
  <form action="/submit" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name"><br><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email"><br><br>
    <input type="submit" value="Submit">
  </form>

  <!-- ID and Class Example -->
  <h2>ID and Class Attributes</h2>
  <p id="unique-paragraph">This is a unique paragraph with red text.</p>
  <p class="styled-paragraph">This is a paragraph with a blue, bold style.</p>
  <p class="styled-paragraph">This is another styled paragraph.</p>

</body>
</html>        

2.8 Meta Tag, Audio, Video, Canvas, Main, Section, Article, Header, Footer, Aside, Nav, Figure?Tags

2.8.1 Meta?Tag

  • Definition: The <meta> tag provides metadata about the HTML document, such as the charset, author, viewport, or description.
  • Concept: It is commonly used in the <head> section to optimize web pages for search engines (SEO) or define the character set for the document.

2.8.2 Audio?Tag

  • Definition: The <audio> tag is used to embed sound files in a webpage.
  • Concept: It allows users to control playback options such as play, pause, and volume directly within the browser.

2.8.3 Video?Tag

  • Definition: The <video> tag embeds videos into a webpage.
  • Concept: It supports attributes like controls, autoplay, and loop, giving users an interactive media experience.

2.8.4 Canvas?Tag

  • Definition: The <canvas> tag is used for drawing graphics on the web, using JavaScript.
  • Concept: It can create complex visual elements such as animations, charts, or games by manipulating pixels within the defined area.

2.8.5 Main?Tag

  • Definition: The <main> tag specifies the dominant content of the <body>.
  • Concept: It helps improve the page’s structure by clearly defining the main content, important for screen readers and SEO.

2.8.6 Section?Tag

  • Definition: The <section> tag defines a thematic grouping of content, typically with its heading.
  • Concept: It is used to break up the webpage into distinct sections, aiding in content organization and improving readability.

2.8.7 Article?Tag

  • Definition: The <article> tag represents a self-contained, independent piece of content, such as a blog post or news item.
  • Concept: It can be shared or reused on other sites or feeds without losing its meaning.

2.8.8 Header?Tag

  • Definition: The <header> tag specifies the introductory content or set of navigational links for a section or the entire webpage.
  • Concept: It’s typically used to hold logos, navigation menus, and introductory information.

2.8.9 Footer?Tag

  • Definition: The <footer> tag represents the footer of a document or section.
  • Concept: It usually contains information like copyright notices, contact details, or related links.

2.8.10 Aside?Tag

  • Definition: The <aside> tag defines content that is tangentially related to the content around it, like a sidebar.
  • Concept: It often contains supplementary information such as side notes, advertisements, or references.

2.8.11 Nav?Tag

  • Definition: The <nav> tag is used to define a block of navigation links.
  • Concept: It improves accessibility by making it clear that a specific set of links constitutes the main navigation menu.

2.8.12 Figure?Tag

  • Definition: The <figure> tag encapsulates media like images, illustrations, or diagrams with associated captions.
  • Concept: It groups visual content along with a <figcaption> for improved semantics and clearer content presentation.

  <!-- Header Section -->
  <header>
    <h1>Welcome to My Web Page</h1>
    <nav>
      <ul>
        <li><a href="#section1">Home</a></li>
        <li><a href="#section2">About</a></li>
        <li><a href="#section3">Contact</a></li>
      </ul>
    </nav>
  </header>

  <!-- Main Content -->
  <main>
    <!-- Section 1 -->
    <section id="section1">
      <h2>Introduction</h2>
      <p>This section introduces the main content of the webpage.</p>
    </section>

    <!-- Section 2 with an Article -->
    <section id="section2">
      <h2>About</h2>
      <article>
        <h3>What We Do</h3>
        <p>We specialize in creating web solutions using modern technologies.</p>
      </article>
    </section>

    <!-- Section 3 with Media Content -->
    <section id="section3">
      <h2>Media</h2>

      <!-- Figure with Image -->
      <figure>
        <img src="image.jpg" alt="A beautiful scenery" width="300">
        <figcaption>A stunning view of nature.</figcaption>
      </figure>

      <!-- Audio Element -->
      <h3>Listen to Our Theme Song</h3>
      <audio controls>
        <source src="song.mp3" type="audio/mpeg">
        Your browser does not support the audio element.
      </audio>

      <!-- Video Element -->
      <h3>Watch Our Promo Video</h3>
      <video controls width="400">
        <source src="promo.mp4" type="video/mp4">
        Your browser does not support the video tag.
      </video>

      <!-- Canvas Element -->
      <h3>Interactive Canvas Drawing</h3>
      <canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>
    </section>

    <!-- Aside Section -->
    <aside>
      <h3>Related Links</h3>
      <ul>
        <li><a href="#section1">Go to Home</a></li>
        <li><a href="#section2">Learn About Us</a></li>
      </ul>
    </aside>
  </main>

  <!-- Footer Section -->
  <footer>
    <p>&copy; 2024 My Website. All rights reserved.</p>
  </footer>

        

2.9 HTML Events: Window Events, Form Element Events, Keyboard Events, Mouse?Events

The KeyboardEvent Object handles events that occur when a user presses a key on the keyboard.

Common keyboard events:

  • keydown: Occurs when a key is pressed down.
  • keyup: Occurs when a key is released.
  • keypress: Occurs when a key is pressed and released (deprecated in some browsers).

<p id="message"></p>
<script>
document.addEventListener('keypress', function(event) {
document.getElementById("message").textContent = "Hello, world!";
});
</script>        

Explanation:

  • We use document.addEventListener(‘keypress’, function(event) {?… }) to listen for the ‘keypress’ event on the entire document.
  • Inside the event handler function, we set the text content of the paragraph element with the id “message” to “Hello, world!”.

2.9.1 Window?Events

  • Definition: Window events are triggered by the browser’s window object in response to user actions or system events.
  • Concept: These events allow developers to respond to changes in the state of the browser window (e.g., resizing, loading, or closing the window).

Examples:

  • load: Fires when the entire page (including all dependent resources like images) is fully loaded.
  • resize: Fires when the browser window is resized.
  • scroll: Triggered when the user scrolls the content in the window.
  • beforeunload: Fires before the user navigates away from the page.

2.9.2 Form Element?Events

  • Definition: Form element events are triggered by interactions with HTML form elements like <input>, <select>, and <textarea>.
  • Concept: These events are used to handle form-related interactions, such as submitting forms, validating inputs, or responding to user inputs.

Examples:

  • submit: Fires when a form is submitted.
  • change: Triggered when the value of an input element is changed.
  • focus: Fires when an element gains focus.
  • blur: Fires when an element loses focus.

2.9.3 Mouse?Events

  • Definition: Mouse events are triggered by user interactions involving the mouse, such as clicks or movement over an element.
  • Concept: These events allow developers to detect and respond to actions like clicking, hovering, or dragging items with the mouse.

Examples:

  • click: Fires when a mouse button is clicked on an element.
  • dblclick: Triggered when a mouse button is double-clicked.
  • mouseover: Fires when the mouse pointer hovers over an element.
  • mousedown: Fires when a mouse button is pressed on an element.
  • mouseup: Fires when a mouse button is released over an element.

2.9.4 Summary

  • Window Events: Handle browser window-level events (e.g., loading, resizing).
  • Form Element Events: Respond to user interaction with form fields (e.g., submitting, input changes).
  • Mouse Events: Track actions involving the mouse (e.g., clicking, hovering).

 <h1>Event Handling Example</h1>

    <!-- Window Events -->
    <h2>Window Events</h2>
    <p id="windowEvent">Resize the window or reload the page to see events in action.</p>

    <!-- Form Element Events -->
    <h2>Form Element Events</h2>
    <form id="sampleForm">
        <label for="name">Name:</label>
        <input type="text" id="name" required>
        <input type="submit" value="Submit">
    </form>
    <p id="formEventMessage"></p>

    <!-- Mouse Events -->
    <h2>Mouse Events</h2>
    <div id="hoverBox">Hover over me!</div>
    <p id="mouseEventMessage"></p>

    <script>
        // Window Events
        window.addEventListener('load', () => {
            document.getElementById('windowEvent').innerText = "Page is fully loaded.";
        });

        window.addEventListener('resize', () => {
            document.getElementById('windowEvent').innerText = "Window resized!";
        });

        // Form Element Events
        const form = document.getElementById('sampleForm');
        const formMessage = document.getElementById('formEventMessage');

        form.addEventListener('submit', (event) => {
            event.preventDefault(); // Prevent form submission
            const name = document.getElementById('name').value;
            formMessage.innerText = `Hello, ${name}! Your form has been submitted.`;
        });

        document.getElementById('name').addEventListener('focus', () => {
            formMessage.innerText = "Input field focused.";
        });

        document.getElementById('name').addEventListener('blur', () => {
            formMessage.innerText = "Input field lost focus.";
        });

        // Mouse Events
        const hoverBox = document.getElementById('hoverBox');
        const mouseMessage = document.getElementById('mouseEventMessage');

        hoverBox.addEventListener('mouseover', () => {
            mouseMessage.innerText = "Mouse is over the box!";
        });

        hoverBox.addEventListener('mouseout', () => {
            mouseMessage.innerText = "Mouse left the box.";
        });

        hoverBox.addEventListener('click', () => {
            mouseMessage.innerText = "Box clicked!";
        });
    </script>        

3. Cascading Style Sheets?(CSS)

3.1 Introduction to CSS; CSS?Syntax

CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML or XML. It enables web developers to apply styles to web pages, controlling layout, colors, fonts, and overall visual presentation.

3.2 CSS?Syntax

CSS syntax consists of selectors and declaration blocks. A selector targets HTML elements, while a declaration block contains one or more declarations (property-value pairs) that define the styles to be applied to the selected elements.

3.3 Inserting CSS

There are three primary methods to insert CSS into HTML documents:

  • Inline CSS: Styles are applied directly within an HTML element using the style attribute.
  • Internal CSS: Styles are defined within a <style> tag in the <head> section of an HTML document.
  • External CSS: Styles are contained in a separate CSS file linked to the HTML document using the <link> tag.

3.4 ID and Class Selectors

  • ID Selector: Targets a unique element on a page using the id attribute. IDs are unique within a page, meaning each element can only have one ID.
  • Class Selector: Targets elements that share the same class attribute. Multiple elements can share the same class, allowing for bulk styling.

3.5 Colors

CSS supports a variety of methods for defining colors, including named colors (e.g., “red”), hexadecimal values (e.g., “#FF0000”), and RGB/RGBA values (e.g., “rgb(255,0,0)” or “rgba(255,0,0,0.5)”). These allow developers to control the color of text, backgrounds, borders, and other elements.

3.6 Backgrounds

The background property in CSS allows developers to set background colors, images, and other properties for elements. Backgrounds can cover entire elements or specific parts of them and can be customized in terms of size, repeat behavior, and positioning.

3.7 Borders

CSS enables the addition of borders to elements using the border property, which can define the width, style (e.g., solid, dashed), and color. Borders can enhance the visual separation of elements on a web page.

3.8 Text

CSS provides various properties to style text, including font size, color, font family, line height, and text alignment. These properties help create readable and visually appealing text layouts.

3.9 Font

CSS allows extensive control over font styling, including selecting specific font families, adjusting font sizes, applying font weights (e.g., bold or light), and styling (e.g., italic). This is essential for enhancing the overall design and readability of text content.

3.10 List

CSS can be used to style ordered (numbered) and unordered (bulleted) lists, allowing developers to customize bullet styles, indentation, and list layout. This ensures lists are visually appealing and fit well within the overall design.

3.11 Table

CSS facilitates the styling of HTML tables, enabling customization of borders, padding, spacing, and background colors. Proper styling enhances the readability and presentation of tabular data on web pages.

<style>
        /* Internal CSS */
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }

        /* ID Selector */
        #header {
            background-color: #4CAF50;
            color: white;
            padding: 10px;
            text-align: center;
        }

        /* Class Selector */
        .highlight {
            background-color: yellow;
        }

        /* Styling for lists */
        ul {
            list-style-type: square; /* Change bullet style */
            padding-left: 20px;
        }

        /* Table styles */
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #4CAF50;
            color: white;
        }

        /* Customizing text */
        .large-text {
            font-size: 1.5em;
            color: #333;
        }
    </style>
</head>
<body>

    <div id="header">
        <h1>Welcome to CSS Concepts</h1>
    </div>

    <p class="large-text">This is an example of using CSS to style a webpage.</p>

    <p>This paragraph contains some <span class="highlight">highlighted text</span> using a class selector.</p>

    <h2>Sample List</h2>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>

    <h2>Sample Table</h2>
    <table>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>City</th>
        </tr>
        <tr>
            <td>John Doe</td>
            <td>30</td>
            <td>New York</td>
        </tr>
        <tr>
            <td>Jane Smith</td>
            <td>25</td>
            <td>Los Angeles</td>
        </tr>
    </table>        

CSS selectors are used to target specific HTML elements to which we want to apply styles. Among these, class and ID selectors are the most commonly used.

In Summary:

  • Use an ID selector when you want to style a single, unique element.
  • Use a class selector when you want to apply the same style to multiple elements.

3.4 CSS Box Model; Normal Flow Box Layout: Basic Box Layout, Display Property, Padding,?Margin

3.4.1 CSS Box?Model

The CSS Box Model is a fundamental concept that governs how elements are structured and positioned on a webpage. Every HTML element can be considered as a box, and the box model describes the properties of this box.

3.4.3 Components of the Box?Model:

  1. Content: This is the actual content of the element, like text, images, or other elements.
  2. Padding: The space between the content and the border.
  3. Border: The border surrounds the content and padding.
  4. Margin: The space outside the border, separating the element from other elements.

<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
border: 5px solid blue;
padding: 15px;
margin: 10px;
}
</style>
</head>
<body>
<div>
This is a div element.
</div>
</body>
</html>        

3.5 Positioning: Static, Fixed, Relative, Float,?Absolute

Positioning HTML elements in CSS allows us to control their placement on the page. CSS offers several positioning techniques:

3.5.1 Static Positioning

By default, elements are positioned statically. They flow in the order they appear in the HTML.

/* Default */
div {
position: static; /* This is the default value */
}        

3.5.2. Relative Positioning

Relative positioning moves an element relative to its original position.

div {
position: relative;
top: 10px; /* Moves the element 10px down from its original position */
left: 20px; /* Moves the element 20px right from its original position */
}        

3.5.3. Absolute Positioning

Absolute positioning removes an element from the document flow and positions it relative to its nearest positioned ancestor (non-static). If no such ancestor exists, it positions itself relative to the initial containing block (usually the viewport).

div {
position: absolute;
top: 50px; /* Moves the element 50px from the top of the nearest positioned ancestor */
left: 100px; /* Moves the element 100px from the left of the nearest positioned ancestor */
}        

3.5.4. Fixed Positioning

Fixed positioning positions an element relative to the viewport. It stays in the same place even when the page is scrolled.

div {
position: fixed;
bottom: 10px; /* Moves the element 10px from the bottom of the viewport */
right: 20px; /* Moves the element 20px from the right of the viewport */
}        

3.5.5 Sticky Positioning

Sticky positioning is a hybrid of relative and fixed positioning. The element toggles between relative and fixed based on the scroll position. It is positioned relative to its nearest scrolling ancestor until a specified scroll position is reached, at which point it becomes fixed.

div {
position: sticky;
top: 0; /* Sticks the element to the top of its container when scrolling */
}        

3.6 CSS3 Borders, Box Shadows, Text Effects and?Shadow

3.6.1 CSS3?Borders

CSS3 introduces additional border features like rounded corners and border images. The border-radius property allows you to create rounded edges for elements, enhancing design aesthetics. The border-image property lets you use images for borders, adding flexibility to styling.

3.6.2. Box?Shadows

The box-shadow property in CSS3 allows you to apply shadows to elements, adding depth and realism. You can control the shadow's offset, blur, spread, and color. Box shadows can be used to create 3D-like effects or simple visual enhancements.

3.6.3. Text Effects and?Shadow

CSS3 provides various text effects, including shadows and transformations. The text-shadow property lets you add shadows to text, creating an embossed or glowing effect. You can specify multiple values for horizontal and vertical offsets, blur radius, and shadow color to customize the appearance.

Examples of Properties:

  • border-radius: Defines rounded corners for an element.
  • box-shadow: Adds shadow to the element.
  • text-shadow: Adds shadow to text.

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }

        /* CSS3 Border */
        .border-example {
            border: 2px solid #4CAF50; /* Solid border */
            border-radius: 15px; /* Rounded corners */
            padding: 20px;
            margin: 20px 0;
            background-color: white;
        }

        /* Box Shadow */
        .box-shadow-example {
            background-color: white;
            border: 1px solid #ddd;
            padding: 20px;
            margin: 20px 0;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Shadow effect */
        }

        /* Text Shadow */
        .text-shadow-example {
            font-size: 24px;
            color: #333;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3); /* Shadow effect for text */
        }

        /* Combined Effects */
        .combined-example {
            border: 2px solid #4CAF50;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
            padding: 20px;
            background-color: white;
            font-size: 20px;
            color: #333;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
        }
    </style>

    <h2>CSS3 Borders Example</h2>
    <div class="border-example">
        This box has a solid border and rounded corners.
    </div>

    <h2>Box Shadow Example</h2>
    <div class="box-shadow-example">
        This box has a subtle shadow effect.
    </div>

    <h2>Text Shadow Example</h2>
    <p class="text-shadow-example">
        This text has a shadow effect applied to it.
    </p>

    <h2>Combined Borders, Shadows, and Text Effects</h2>
    <div class="combined-example">
        This box combines borders, shadows, and text effects.
    </div>        

3.7 Basics of Responsive Web Designs; Media?Queries

3.7.1 Using Media Queries for Responsive Web?Design

Media Queries are CSS rules that allow us to apply styles based on specific conditions, such as screen size, orientation, and resolution. They are the cornerstone of responsive web design, ensuring that the website adapts to different devices and screen sizes.

@media (condition) { /* CSS rules */ }

<!DOCTYPE html>
<html>
<head>
<title>Media Query Example</title>
<style>
body {
background-color: lightblue;
}
@media (max-width: 768px) {
body {
background-color: lightpink;
}
}
</style>
</head>
<body>
<p>This is a responsive page.</p>
</body>
</html>        

3.7.1.1 Common conditions:

  • (min-width: value): Applies styles when the viewport width is greater than or equal to the specified value.
  • (max-width: value): Applies styles when the viewport width is less than or equal to the specified value.
  • (orientation: landscape): Applies styles when the device is in landscape orientation.
  • (orientation: portrait): Applies styles when the device is in portrait orientation.

3.8 Introduction to Bootstrap

Bootstrap is a popular open-source front-end framework used for designing responsive and mobile-first websites. Developed by Twitter, it provides a collection of CSS and JavaScript components that facilitate the development of user-friendly web interfaces.

<link rel="stylesheet" >
</head>
<body>
<!-- Navigation Bar -->
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">My Bootstrap Site</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Services</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Contact</a>
                </li>
            </ul>
        </div>
    </nav>
    <!-- Main Content -->
    <div class="container mt-4">
        <h1 class="text-center">Welcome to My Bootstrap Page</h1>
        <div class="row">
            <div class="col-md-4">
                <div class="card">
                    <img src="https://via.placeholder.com/150" class="card-img-top" alt="Image 1">
                    <div class="card-body">
                        <h5 class="card-title">Card Title 1</h5>
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                        <a href="#" class="btn btn-primary">Go somewhere</a>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card">
                    <img src="https://via.placeholder.com/150" class="card-img-top" alt="Image 2">
                    <div class="card-body">
                        <h5 class="card-title">Card Title 2</h5>
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                        <a href="#" class="btn btn-primary">Go somewhere</a>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card">
                    <img src="https://via.placeholder.com/150" class="card-img-top" alt="Image 3">
                    <div class="card-body">
                        <h5 class="card-title">Card Title 3</h5>
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                        <a href="#" class="btn btn-primary">Go somewhere</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Include Bootstrap JS and dependencies -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>        


4. Client Side Scripting with JavaScript

4.1 Structure of JavaScript Program; Variables and Data?Types

Concept: JavaScript programs are structured with a combination of statements, expressions, and functions. Variables are declared using var, let, or const, and can hold different types of data, including:

  • Primitive Types: Numbers, Strings, Booleans, null, undefined, and Symbols.
  • Reference Types: Objects and Arrays.

4.2 Statements: Expression, Keyword,?Block

Concept:

  • Statement: A single line of code that acts (e.g., variable assignment).
  • Expression: A combination of values and operators that produces a new value (e.g., 2 + 3).
  • Keyword: Reserved words in JavaScript that have special meanings (e.g., if, else, function).
  • Block: A group of statements enclosed in curly braces {} that can be executed together (e.g., in control structures).

4.3 Operators; Flow Controls, Looping, Functions

Concept:

  • Operators: Symbols that perform operations on variables and values, including arithmetic (+, -, *, /), comparison (==, ===, <, >), and logical (&&, ||,?!).
  • Flow Controls: Structures like if, switch, and ternary operators that control the flow of execution based on conditions.
  • Looping: Constructs like for, while, and do...while that repeat a block of code multiple times.
  • Functions: Reusable blocks of code defined using the function keyword, which can take parameters and return values.

4.4 Popup Boxes: Alert, Confirm,?Prompt

Concept:

  • Alert: Displays a message to the user and requires them to click “OK” to proceed (alert("Hello, World!");).
  • Confirm: Shows a message and provides “OK” and “Cancel” buttons; returns true if "OK" is clicked, false otherwise (confirm("Are you sure?");).
  • Prompt: Displays a dialog box that prompts the user for input; returns the input value or null if canceled (prompt("Enter your name:");).

4.5 Objects and Properties; Constructors

Concept:

  • Objects: Collections of key-value pairs where keys are strings and values can be any data type, including functions.
  • Properties: Values associated with an object (e.g., person.name).
  • Constructors: Special functions used to create objects, usually defined with an uppercase first letter, using the new keyword (e.g., function Person(name) { this.name = name; }).

4.6 Arrays; Built-in Objects: Window, String, Number, Boolean, Date, Math, RegExp, Form,?DOM

Concept:

  • Arrays: Ordered collections of values that can hold multiple items, accessed using zero-based indexing (e.g., let fruits = ['apple', 'banana', 'cherry'];).
  • Built-in Objects: Predefined objects provided by JavaScript, including:
  • Window: Represents the browser window.
  • String: Provides methods for manipulating string values.
  • Number: Contains properties and methods for numeric values.
  • Boolean: Represents logical values true and false.
  • Date: Allows date and time manipulation.
  • Math: Provides mathematical constants and functions.
  • RegExp: Represents regular expressions for pattern matching.
  • Form: Represents HTML forms and their elements.
  • DOM (Document Object Model): Provides a structured representation of the document and methods to interact with it.

// 4.1 Structure of JavaScript Program; Variables and Data Types
let greeting = "Hello, World!"; // String
let age = 25; // Number
let isStudent = true; // Boolean

// 4.2 Statements: Expression, Keyword, Block
if (age >= 18) { // Block
    console.log("You are an adult."); // Statement
} else {
    console.log("You are a minor."); // Statement
}

// 4.3 Operators; Flow Controls, Looping, Functions
function calculateSum(a, b) { // Function
    return a + b; // Expression
}

console.log("Sum:", calculateSum(5, 10)); // Calling function with values

for (let i = 0; i < 5; i++) { // Looping
    console.log("Iteration:", i);
}

// 4.4 Popup Boxes: Alert, Confirm, Prompt
alert(greeting); // Alert box
let userConfirmation = confirm("Do you want to proceed?"); // Confirm box

if (userConfirmation) {
    let userName = prompt("Enter your name:"); // Prompt box
    console.log("Welcome, " + userName);
}

// 4.5 Objects and Properties; Constructors
function Person(name, age) { // Constructor
    this.name = name; // Property
    this.age = age; // Property
}

let person1 = new Person("Alice", 30); // Object instance
console.log("Person:", person1.name, "Age:", person1.age);

// 4.6 Arrays; Built-in Objects: Window, String, Number, Boolean, Date, Math, RegExp, Form, DOM
let fruits = ["apple", "banana", "cherry"]; // Array
console.log("Fruits:", fruits);

// Using built-in objects
console.log("Random Number:", Math.random()); // Math object
console.log("Current Date:", new Date()); // Date object

let regex = /[a-zA-Z]+/; // RegExp object
console.log("Regex Test:", regex.test("Hello")); // Testing regex        

4.7 User-Defined Objects

4.7.1. Object?Literals

The simplest way to create an object is using an object literal. This is done by defining the properties and their values within curly braces {}.

let person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.firstName); // Output: John
console.log(person.fullName()); // Output: John Doe        

4.7.2. Using the new Object()?Syntax

We can create an object using the Object constructor. This method is less commonly used but still valid.

let person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 30;
person.fullName = function() {
return this.firstName + " " + this.lastName;
};
console.log(person.firstName); // Output: John
console.log(person.fullName()); // Output: John Doe        

4.7.3. Constructor Functions

Constructor functions are a convention for creating multiple objects of the same type. The function name should start with an uppercase letter.

function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
let person1 = new Person("John", "Doe", 30);
let person2 = new Person("Jane", "Smith", 25);
console.log(person1.fullName()); // Output: John Doe
console.log(person2.fullName()); // Output: Jane Smith        

4.7.4. ES6?Classes

ES6 introduced classes, which provide a more structured and syntactic style over constructor functions.

class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
fullName() {
return this.firstName + " " + this.lastName;
}
}
let person1 = new Person("John", "Doe", 30);
let person2 = new Person("Jane", "Smith", 25);
console.log(person1.fullName()); // Output: John Doe
console.log(person2.fullName()); // Output: Jane Smith        

4.7.5. Using Object.create()

The Object. create() method creates a new object with the specified prototype object and properties.

let personPrototype = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
let person = Object.create(personPrototype);
person.firstName = "John";
person.lastName = "Doe";
person.age = 30;
console.log(person.fullName()); // Output: John Doe        

These methods provide a variety of ways to create objects in JavaScript, each with its use cases and benefits.

4.8 Event Handling and Form Validation

Event handling is a crucial part of web development that allows developers to create interactive web pages. It involves responding to user actions or events, such as mouse clicks, keyboard presses, and form submissions

4.8.2 Javascript and HTML Form Validation

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Signup Form</title>
        <style>
            body {
                font-family: Arial, sans-serif;
            }
            form {
                max-width: 300px;
                margin: auto;
                padding: 20px;
                border: 1px solid #ddd;
                border-radius: 8px;
            }
            .error {
                color: red;
                font-size: 0.875em;
            }
            .hidden {
                display: none;
            }
        </style>
    </head>
    <body>
        <h1>Signup Form</h1>
        <form id="signupForm">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" />
            <div id="nameError" class="error hidden">Name is required.</div>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" />
            <div id="emailError" class="error hidden">Invalid email address.</div>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" />
            <div id="passwordError" class="error hidden">Password must be at least 6 characters, start with a letter, and end with a digit.</div>
            <label for="age">Age:</label>
            <input type="number" id="age" name="age" />
            <div id="ageError" class="error hidden">Age must be between 8 and 60.</div>
            <button type="submit">Submit</button>
        </form>
        <script>
            document.getElementById("signupForm").addEventListener("submit", function (event) {
                let isValid = true;
                // Name Validationconst name = document.getElementById('name').value;
                if (name === "") {
                    document.getElementById("nameError").classList.remove("hidden");
                    isValid = false;
                } else {
                    document.getElementById("nameError").classList.add("hidden");
                }
                // Email Validation
                const email = document.getElementById("email").value;
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailPattern.test(email) || email === "") {
                    document.getElementById("emailError").classList.remove("hidden");
                    isValid = false;
                } else {
                    document.getElementById("emailError").classList.add("hidden");
                }
                // Password Validation
                const password = document.getElementById("password").value;
                const passwordPattern = /^[a-zA-Z].{4,}[0–9]$/;
                if (password.length < 6 || !passwordPattern.test(password)) {
                    document.getElementById("passwordError").classList.remove("hidden");
                    isValid = false;
                } else {
                    document.getElementById("passwordError").classList.add("hidden");
                }
                // Age Validation
                const age = document.getElementById("age").value;
                if (age < 8 || age > 60) {
                    document.getElementById("ageError").classList.remove("hidden");
                    isValid = false;
                } else {
                    document.getElementById("ageError").classList.add("hidden");
                }
          // Prevent form submission if invalid
                if (!isValid) {
                    event.preventDefault();
                }
            });
        </script>
    </body>
</html>
        

Explanation:

  • HTML Form: Contains fields for Name, Email, Password, and Age, with corresponding error messages.
  • JavaScript Validation:
  • Name: Checks if the field is not empty.
  • Email: Validates the email format using a regular expression.
  • Password: Ensures the password is at least 6 characters long, starts with a letter, and ends with a digit.
  • Age: Ensures the age is between 8 and 60.
  • Error Handling: Displays error messages if validation fails and prevents form submission.

This setup provides straightforward validation and feedback, ensuring users fill out the form correctly before submission.

4.9 Error Handling, Handling Cookies

  • Error Handling: Error handling involves managing errors gracefully to ensure the stability of web applications. It can be done using:
  • Handling Cookies: Cookies are small pieces of data stored on the client side to maintain user sessions or preferences. They can be handled in web applications by:

// error handling
try {
  // Simulate an error
  let result = someUndefinedFunction();
  console.log(result);
} catch (error) {
  console.error("An error occurred:", error.message);
  // Handle the error, like showing an alert to the user
  alert("Something went wrong. Please try again later.");
} finally {
  console.log("Error handling complete.");
}

// create a cookie

function setCookie(name, value, days) {
  let expires = "";
  if (days) {
    let date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + value + expires + "; path=/";
}

// Example: Set a cookie
setCookie("username", "JohnDoe", 7); // Cookie expires in 7 days

// read cookie
function getCookie(name) {
  let nameEQ = name + "=";
  let cookiesArray = document.cookie.split(';');
  for (let i = 0; i < cookiesArray.length; i++) {
    let cookie = cookiesArray[i].trim();
    if (cookie.indexOf(nameEQ) == 0) {
      return cookie.substring(nameEQ.length, cookie.length);
    }
  }
  return null;
}

// Example: Read a cookie
let username = getCookie("username");
if (username) {
  console.log("Welcome back, " + username);
} else {
  console.log("Username cookie not found.");
}
// delete cookie
function deleteCookie(name) {
  // To delete, set the expiration date to the past
  document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}

// Example: Delete a cookie
deleteCookie("username");
        

Both error handling and managing cookies ensure better usability and application reliability.

4.10. jQuery

4.10.1 jQuery Animate() Method for Custom Animations

The jQuery animate() method allows us to create custom animations by changing CSS properties over a specified duration.

$(selector).animate({properties}, [duration], [easing], [callback]);

  • selector: Specifies the element to animate.
  • properties: An object containing CSS properties and their target values.
  • duration: Optional. Specifies the duration of the animation (milliseconds or string like ‘slow’, ‘fast’).
  • easing: Optional. Specifies the speed of the animation at different points.
  • callback: Optional. A function to be executed after the animation completes.

<!DOCTYPE html>
<html>
<head>
<title>jQuery Animate Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
#myDiv {
width: 200px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div id="myDiv"></div>
<script>
$(document).ready(function() {
$("#myDiv").animate({
width: "400px",
height: "200px",
opacity: 0.5
}, 2000, function() {
alert("Animation complete!");
});
});
</script>
</body>
</html>        

Explanation:

  1. The animate() method is called on the element with the ID “myDiv”.
  2. The properties object specifies three CSS properties to animate: width, height, and opacity.
  3. The animation duration is set to 2000 milliseconds (2 seconds).
  4. A callback function is defined to execute after the animation completes.

This code will animate the div to double its size and reduce its opacity to 0.5 over 2 seconds.

4.10.2 jQuery Selectors and?Event?

<!DOCTYPE html>
<html>
<head>
<title>jQuery ID Selector</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button id="hideButton">Hide Paragraph</button>
<p id="myParagraph">This is a paragraph.</p>
<script>
$(document).ready(function() {
$("#hideButton").click(function() {
$("#myParagraph").hide();
});
});
</script>
</body>
</html>
// Hide the element
$("#myDiv").hide();
// Show the element
$("#myDiv").show();
// Toggle the element's visibility
$("#myDiv").toggle();        

4.10.3 jQuery?Chaining

Chaining in jQuery allows us to perform multiple actions on the same set of elements in a single statement. This enhances code readability and efficiency by avoiding redundant selections of elements.

Essentially, most jQuery methods return a jQuery object, which means we can immediately call another method on the same object without reselecting it.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div id="myDiv">This is a div</div>
<script>
$(document).ready(function() {
$("#myDiv").slideUp(500).slideDown(500);
});
</script>
</body>
</html>        

Explanation:

  1. Include jQuery: The <script> tag links the jQuery library.
  2. Select the element: $(“#myDiv”) selects the element with the ID “myDiv”.
  3. Chain methods:

  • slideUp(500) hides the element with a sliding up animation over 500 milliseconds.
  • slideDown(500) shows the element with a sliding down animation over 500 milliseconds.

How it?works:

  • The slideUp() method returns a jQuery object representing the element.
  • The slideDown() method is then called on the same object, performing the animation sequentially.

Benefits of chaining:

  • Improved code readability.
  • Enhanced performance by avoiding redundant element selections.
  • More concise code.

By understanding and utilizing chaining, we can write more efficient and elegant jQuery code.

4.12 JSON:?

JSON is a Lightweight Data-Interchange Format. JSON (JavaScript Object Notation) is a standard text-based format for representing structured data. It’s derived from JavaScript object syntax but is language-independent.

In JSON, values must be one of the following data types:

  • a string
  • a number
  • an object (JSON object)
  • an array
  • a boolean
  • null

{"name":"John"}- JSON STRINGS
{"age":30} - JSON Objects Values in JSON can be objects.
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
{
"employees":["John", "Anna", "Peter"]
}
{"sale":true}
{"middlename":null}        

4.12.1 Uses of?JSON

  • Data interchange: Commonly used to transfer data between web applications and servers.
  • Configuration files: Stores application settings and configurations.
  • Data storage: This can be used to store data in a human-readable format.

4.12.2 Parsing?JSON

Parsing JSON involves converting a JSON string into a data structure that can be used by a programming language.

let jsonString = '{"name":"John Doe", "age":30, "city":"New York"}';
// Parse the JSON string
let jsonData = JSON.parse(jsonString);
// Access data
console.log(jsonData.name); // Output: John Doe
console.log(jsonData.age); // Output: 30
console.log(jsonData.city); // Output: New York        

Explanation:

  1. A JSON string is defined.
  2. The JSON.parse() method is used to convert the string into a JavaScript object.
  3. The parsed data can be accessed using dot notation.
  4. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate. It supports six primary data types:

4.12.3 JSON Primitive Data?Types

Values in JSON can be arrays.

Values in JSON can be true/false

Values in JSON can be null.

Objects as values in JSON must follow the JSON syntax.

These are the basic building blocks of JSON data.

  • String: A sequence of characters enclosed in double quotes (e.g., “Hello, World!”, “true”, “123”).
  • Number: A numeric value, including integers and floating-point numbers (e.g., 42, 3.14, -10).
  • Boolean: A logical value, either true or false.
  • Null: Represents a null value.

4.12.4 Complex Data?Types

These data types allow for structured data representation.

  • Object: An unordered collection of key-value pairs. Keys must be strings, and values can be any JSON data type. Objects are enclosed in curly braces {}

5: AJAX and?XML?

5.1 Basics of AJAX Introduction to XML and its Application?

XML stands for Extensible Markup Language. It’s a text-based format for representing structured data. Unlike HTML, which defines how data looks, XML defines what data is.

5.1.1 Key Characteristics of?XML:

  • It’s self-descriptive.
  • It’s hierarchical.
  • It’s case-sensitive.

5.1.2 Example: XML File for Employee?Records

Let’s create a simple XML file containing employee records with both simple and complex data types.

<?xml version="1.0" encoding="UTF-8"?>
<employees>

<employee id="1">
<firstName>John</firstName>
<lastName>Doe</lastName>
<salary>50000</salary>

<address>
<street>123 Main St</street>
<city>Anytown</city>
<state>CA</state>
<zip>12345</zip>
</address>

<phone>(123) 456–7890</phone>
<email>[email protected]</email>
</employee>

</employees>        

5.1.3 Explanation:

  1. <?xml version=”1.0" encoding=”UTF-8"?>: This declaration specifies the XML version and character encoding.
  2. <employees>: This is the root element, containing all employee records.
  3. <employee>: This is a child element representing an individual employee.
  4. Simple types: firstName, lastName, salary, phone, and email are simple types as they hold single values.
  5. Complex type: address is a complex type as it contains nested elements (street, city, state, and zip).

5.2 Syntax Rules for Creating XML Document XML?Elements

XSD (XML Schema Definition) is a schema language for defining the structure of an XML document. It provides a formal grammar for describing the elements and data types that can appear in an XML document.

5.2.1 XSD of XML File (XSD Code Structure)

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>The Lord of the Rings</title>
<author>J.R.R. Tolkien</author>
<year>1954</year>
</book>
<book>
<title>Pride and Prejudice</title>
<author>Jane Austen</author>
<year>1813</year>
</book>
</books>
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="https://www.w3.org/2001/XMLSchema">
<xs:element name="books">
<xs:complexType>
<xs:sequence>
<xs:element name="book" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="year" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>        

5.2.2 Explaination:

The <xs:schema> element is the root element of an XSD document.

The <xs:element> defines the root element of the XML document, “books”.

The <xs:complexType> defines the structure of the “books” element.

The <xs:sequence> defines the order of child elements within “books”.

The <xs:element> defines the “book” element with minOccurs=”0" and maxOccurs=”unbounded” to allow zero or multiple occurrences.

The nested <xs:complexType> defines the structure of the “book” element.

The <xs:element> elements for “title”, “author”, and “year” define their data types using built-in types.

5.3 XML Attributes

Definition:

XML attributes provide additional information about elements in an XML document. They are defined within the opening tag of an element and consist of a name-value pair. Attributes help to clarify the characteristics of elements and can be used to store metadata.

Concepts:

  • Structure: Attributes are written in the format name="value".
  • Usage: Attributes can hold various types of data, including strings, numbers, or even boolean values, depending on the application’s requirements.
  • Uniqueness: Each attribute name within an element must be unique.
  • Example: Attributes can enhance the functionality of XML elements, such as specifying properties for an element.

<book title="The Great Gatsby" author="F. Scott Fitzgerald" year="1925">
    <description>A novel set in the Roaring Twenties.</description>
</book>        

5.4 XML?Tree

Definition: An XML tree is a hierarchical structure that represents the organization of elements within an XML document. It visually depicts the relationships between elements, where each element is a node, and the document itself is the root of the tree. The structure resembles a tree, with parent-child relationships between elements.

Concepts:

  • Root Element: The topmost element in an XML document, which contains all other elements. There can be only one root element per XML document.
  • Child Elements: Elements that are nested within another element, also known as the parent element. A parent can have multiple children.
  • Siblings: Elements that share the same parent are considered siblings.
  • Attributes: Attributes provide additional information about elements and can be part of any element in the XML tree.

Key Points:

  • Hierarchy: The XML tree structure emphasizes the hierarchy and relationships between elements, which is fundamental for data representation and parsing.
  • Traversal: XML trees can be traversed using various methods (e.g., depth-first, breadth-first) to access or manipulate the data.
  • Data Organization: The tree structure allows for organized and easily understandable data representation, making it easier to process by machines and humans alike.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XML Tree Representation</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
        }
        .node {
            margin-left: 20px;
            margin-bottom: 10px;
        }
        .root {
            font-weight: bold;
            color: blue;
        }
        .child {
            color: green;
        }
        .attribute {
            color: purple;
            font-style: italic;
        }
        .summary {
            font-style: italic;
            color: gray;
        }
    </style>
</head>
<body>
    <div class="node root">library</div>
    <div class="node child">
        book 
        <span class="attribute">title="1984"</span>
        <span class="attribute">author="George Orwell"</span>
        <span class="attribute">year="1949"</span>
        <div class="summary">A dystopian novel set in a totalitarian state.</div>
    </div>
    <div class="node child">
        book 
        <span class="attribute">title="To Kill a Mockingbird"</span>
        <span class="attribute">author="Harper Lee"</span>
        <span class="attribute">year="1960"</span>
        <div class="summary">A novel about racial injustice in the Deep South.</div>
    </div>
</body>
</html>


        

5.5 XML Namespace; XML Schema Languages: DTD,?XSD

A Document Type Definition (DTD) is a set of rules that define the structure and the legal elements and attributes of an XML document. DTDs are used to enforce the structure of XML documents, specifying the types of elements, their order, and their relationships.

DTDs can be internal or external, where internal DTDs are defined within the XML document and external DTDs are stored in separate files.

Here’s an example of a simple XML file representing information about books and its equivalent DTD:

5.5.2 XML File (books.xml):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE library SYSTEM "books.dtd">
<library>
<book>
<title>Introduction to XML</title>
<author>John Doe</author>
<publication_year>2020</publication_year>
<price>29.99</price>
</book>
<book>
<title>Data Science Basics</title>
<author>Jane Smith</author>
<publication_year>2021</publication_year>
<price>39.99</price>
</book>
</library>        

5.5.2.1 DTD File (books.dtd):

<!ELEMENT library (book+)>
<!ELEMENT book (title, author, publication_year, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publication_year (#PCDATA)>
<!ELEMENT price (#PCDATA)>        

In this example:

- `<!ELEMENT library (book+)>`: Defines that the `<library>` element must contain one
or more `<book>` elements.
- `<!ELEMENT book (title, author, publication_year, price)>`: Specifies that the `<book>`
element must contain the elements `<title>`, `<author>`, `<publication_year>`, and
`<price>` in that order.
- `<!ELEMENT title (#PCDATA)>`, `<!ELEMENT author (#PCDATA)>`, 
`<!ELEMENT publication_year (#PCDATA)>`, 
`<!ELEMENT price (#PCDATA)>`: Define that these elements contain parsed character data (#PCDATA).        

The DOCTYPE declaration in the XML file references the external DTD file (`books.dtd`), specifying the rules for the structure of the XML document. The DTD enforces the structure of the XML file, ensuring that it adheres to the specified rules and preventing the use of undefined elements or invalid structures.

5.6. XSD Simple Types, XSD Attributes, XSD Complex?Types

5.6. XSD Simple?Types

Concept: XSD (XML Schema Definition) Simple Types are used to define the basic data types for XML elements and attributes. They include built-in types like string, integer, boolean, and date, as well as user-defined types that can enforce constraints such as patterns or value ranges.

5.6.XSD Attributes

Concept: XSD Attributes define properties of XML elements. Attributes provide additional information about elements and can have simple types. They are defined within the context of an element and can be required or optional, allowing for flexible data modeling.

5.6.XSD Complex?Types

Concept: XSD Complex Types allow the definition of elements that can contain other elements and attributes. They enable the creation of structured data types by grouping elements and attributes, supporting nested structures, and providing a way to define hierarchical relationships.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="https://www.w3.org/2001/XMLSchema">

    <!-- Definition of Simple Types -->
    <xs:simpleType name="stringType">
        <xs:restriction base="xs:string"/>
    </xs:simpleType>
    
    <xs:simpleType name="integerType">
        <xs:restriction base="xs:integer"/>
    </xs:simpleType>
    
    <xs:simpleType name="booleanType">
        <xs:restriction base="xs:boolean"/>
    </xs:simpleType>
    
    <!-- Definition of Complex Type for Book -->
    <xs:complexType name="bookType">
        <xs:sequence>
            <xs:element name="title" type="stringType"/>
            <xs:element name="author" type="stringType"/>
            <xs:element name="price" type="integerType"/>
            <xs:element name="published" type="xs:date"/>
        </xs:sequence>
        <xs:attribute name="id" type="integerType" use="required"/>
        <xs:attribute name="available" type="booleanType" use="optional" default="true"/>
    </xs:complexType>

    <!-- Root Element -->
    <xs:element name="library">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="book" type="bookType" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>        

5.7 XML Style Sheets (XSLT);?XQuery

5.7.1 XML Style Sheets?(XSLT)

Concept: XSLT (Extensible Stylesheet Language Transformations) is a language used to transform XML documents into different formats (like HTML, plain text, or other XML structures). It defines rules for how to apply styles to XML data, making it possible to present XML content in a more readable format or convert it for different purposes.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" encoding="UTF-8"/>
    
    <xsl:template match="/library">
        <html>
            <head>
                <title>Library Catalog</title>
            </head>
            <body>
                <h1>Library Catalog</h1>
                <table border="1">
                    <tr>
                        <th>Title</th>
                        <th>Author</th>
                        <th>Price</th>
                        <th>Published Date</th>
                    </tr>
                    <xsl:for-each select="book">
                        <tr>
                            <td><xsl:value-of select="title"/></td>
                            <td><xsl:value-of select="author"/></td>
                            <td><xsl:value-of select="price"/></td>
                            <td><xsl:value-of select="published"/></td>
                        </tr>
                    </xsl:for-each>
                </table>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>        

5.7.2 XQuery

Concept: XQuery is a query language designed for querying and manipulating XML data. It allows developers to retrieve and manipulate XML content from databases or XML documents using expressions, providing powerful capabilities for data extraction, transformation, and filtering of XML data.

xquery version "1.0";

declare namespace library = "https://www.example.com/library";

for $book in doc("library.xml")//book
return
    <result>
        <title>{data($book/title)}</title>
        <author>{data($book/author)}</author>
        <price>{data($book/price)}</price>
        <published>{data($book/published)}</published>
    </result>        

6. Server Side Scripting using?PHP?

6.1 PHP Syntax, Variables, Data Types, Strings, Constants, Operators

6.1.1 Variables:

  • $name, $age, and $isStudent are variables that store a string, integer, and boolean, respectively.

6.1.2 Constants:

  • define("PI", 3.14); declares a constant named PI with a value of 3.14.

6.1.3 Data?Types:

  • $floatNumber demonstrates a float, and $array shows an array containing fruits.

6.1.4 String Manipulation:

  • $greeting concatenates a greeting message using the variable $name.
  • strlen($greeting) calculates the length of the greeting string.

6.1.5 Operators:

  • $sum adds 5 to the age, and $isAdult checks if the age is 18 or older.

6.1.6 Output:

echo displays the greeting and information about age and the value of PI.

<?php
// PHP Syntax and Variables
$name = "John Doe"; // String
$age = 30; // Integer
$isStudent = false; // Boolean

// Constants
define("PI", 3.14);

// Data Types
$floatNumber = 3.14; // Float
$array = array("apple", "banana", "cherry"); // Array

// String Manipulation
$greeting = "Hello, " . $name . "!"; // Concatenation
$length = strlen($greeting); // Length of string

// Operators
$sum = $age + 5; // Addition
$isAdult = ($age >= 18); // Comparison

// Output
echo $greeting . " You are " . $age . " years old. The value of PI is " . PI . ".";
?>        

6.1.7 Defining and Concatenating Strings in?PHP

In PHP, variables are defined using the dollar sign ($) followed by the variable name. Variable names are case-sensitive.

<?php
$firstName = "John";
$lastName = "Doe";
?>
// Concatenating Strings
// To combine two strings, we use the dot (.) operator.
<?php
$fullName = $firstName . " " . $lastName;
echo $fullName; // Output: John Doe
?>        

6.2 Control Structure, Functions, Array

6.2.1 Control Structure

Concept: Control structures in PHP are used to dictate the flow of execution in a script based on conditions. They include conditional statements (like if, else, switch), loops (such as for, while, foreach), and include control structures to manage how and when code blocks are executed.

<?php
// Conditional Statement: if, else
$temperature = 30;

if ($temperature > 25) {
    echo "It's a hot day.";
} elseif ($temperature == 25) {
    echo "It's a pleasant day.";
} else {
    echo "It's a cold day.";
}

// Switch Statement
$day = "Monday";

switch ($day) {
    case "Monday":
        echo "Start of the week!";
        break;
    case "Friday":
        echo "Almost weekend!";
        break;
    case "Saturday":
    case "Sunday":
        echo "It's the weekend!";
        break;
    default:
        echo "Midweek days!";
}

// Loop: for
echo "\nCounting from 1 to 5:\n";
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}

// Loop: while
echo "\n\nEven numbers from 1 to 10:\n";
$num = 1;
while ($num <= 10) {
    if ($num % 2 == 0) {
        echo $num . " ";
    }
    $num++;
}

// Loop: foreach
echo "\n\nFruits:\n";
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
    echo $fruit . " ";
}
?>        

6.2.2 Functions

In PHP, we define a function using the function keyword followed by the function name, parentheses, and curly braces. Here’s how we can define a function that takes two integers as arguments and returns their product:

<?php
// Define the function
function multiply($a, $b) {
return $a * $b;
}
// Example usage of the function
$result = multiply(4, 5);
echo "The product of 4 and 5 is: " . $result;
?>
Explanation:        

  • function multiply($a, $b): Defines a function named multiply with two parameters $a and $b.
  • return $a * $b;: Computes the product of the two parameters and returns the result.
  • $result = multiply(4, 5);: Calls the function with 4 and 5 as arguments and stores the result in $result.
  • echo “The product of 4 and 5 is: “?. $result;: Outputs the result.

This function will output The product of 4 and 5 is: 20.

6.2.3 Arrays in?PHP

This PHP script creates a multidimensional array named Product and initializes it with three instances. It then generates an HTML table to display the array values.

<?php
// Define and initialize the multidimensional array
$Product = array(
array("pcode" => "P001", "pname" => "Product 1", "price" => 29.99),
array("pcode" => "P002", "pname" => "Product 2", "price" => 49.99),
array("pcode" => "P003", "pname" => "Product 3", "price" => 19.99)
);
// Start the HTML document
echo "<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Product Table</title>
<style>
table {
width: 50%;
border-collapse: collapse;
margin: 25px 0;
font-size: 18px;
text-align: left;
}
th, td {
padding: 12px;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Product List</h1>
<table>
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th>Price</th>
</tr>";

// Loop through the array and generate table rows
foreach ($Product as $item) {
echo "<tr>
<td>{$item['pcode']}</td>
<td>{$item['pname']}</td>
<td>\${$item['price']}</td>
</tr>";
}

// Close the table and HTML document
echo " </table>
</body>
</html>";
?>
<?php
// we can define the array either using one of the following methods
// 1. array constructor()
$arr = array("dilli", 12.22, True);

// 2. square brackets
$fruits = ["apple", "banana", "citrus"];

// 3. associative array
$associative_array = array(
"name" => "dilli",
"age" => 25
);
// 4. associative array with using square brackets
$associative_arr_brackets = [
"name" => "dillihang",
"age" => 25
];
// createing multi dimensional array
// 1. using array keyword
$arr = array(
array("sports", "football"),
array("music", "salsa")
);
// 2. using square method
$multiarr = [
["GOT", "2014"],
["HELLO", "WORLD"]
]
?>        

Explanation:

  • PHP Array: The $Product array is a multidimensional associative array where each sub-array represents a product with its code, name, and price.
  • HTML Table: The PHP script generates an HTML table where each row corresponds to a product entry.
  • Table Styling: Basic CSS is used to style the table for better readability.

6.3 Creating Class and?Objects

6.3.1 Define a?Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:

<?php
class Fruit {
// code goes here…
}
?>
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>        

Note: In a class, variables are called properties, and functions are called methods!

6.3.2 Define?Objects

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class but will have different property values. Objects of a class are created using the new keyword.

In the example below, $apple and $banana are instances of the class Fruit:

<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
} }
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>        

6.4 PHP Forms: Accessing Form Elements, Form Validation

6.4.1 Accessing Form Elements in?PHP?

In PHP, accessing form elements is a common task when handling user input from HTML forms. This can be done using the $_GET, $_POST, or $_REQUEST superglobals, depending on the method used in the form. Below is a brief explanation of each method along with a code example.

1. Using?$_GET

The $_GET superglobal is used to collect data sent in the URL as query parameters. This method is suitable for forms where data is not sensitive (e.g., search forms).

2. Using?$_POST

The $_POST superglobal is used to collect data sent in the body of the HTTP request. This method is more secure than, $_GET making it suitable for sensitive information such as passwords.

3. Using $_REQUEST

The $_REQUEST superglobal can collect data from both $_GET and $_POST. It provides a unified way to access input, but it’s best practice to use $_GET or $_POST for clarity.

6.4.2 Form Validation using?PHP

Form validation is a crucial aspect of web development that ensures user inputs are correct and secure. PHP provides various methods for validating form data to improve user experience and enhance security. Here’s a guide on how to perform form validation using PHP.

Types of Validation

  1. Client-Side Validation: Validates input before it is sent to the server using HTML and JavaScript. This provides immediate feedback but is not a substitute for server-side validation.
  2. Server-Side Validation: Validates input after it is sent to the server using PHP. This is essential for security as users can bypass client-side validation.

<!-- form.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Validation Example</title>
</head>
<body>
    <h1>Sample Form with Validation</h1>
    <form action="process.php" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <span class="error" id="nameError"></span><br><br>

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

        <label for="age">Age:</label>
        <input type="number" id="age" name="age" min="1" max="120" required>
        <span class="error" id="ageError"></span><br><br>

        <input type="submit" value="Submit">
    </form>
</body>
</html>
<!-- process.php -->
<?php
$errors = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate Name
    if (empty($_POST['name'])) {
        $errors['name'] = "Name is required.";
    } else {
        $name = trim($_POST['name']);
        if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
            $errors['name'] = "Only letters and white space allowed.";
        }
    }

    // Validate Email
    if (empty($_POST['email'])) {
        $errors['email'] = "Email is required.";
    } else {
        $email = trim($_POST['email']);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = "Invalid email format.";
        }
    }

    // Validate Age
    if (empty($_POST['age'])) {
        $errors['age'] = "Age is required.";
    } else {
        $age = (int)$_POST['age'];
        if ($age < 1 || $age > 120) {
            $errors['age'] = "Age must be between 1 and 120.";
        }
    }

    // Check for errors
    if (empty($errors)) {
        // Process the data (e.g., save to database)
        echo "<h1>Form Submitted Successfully</h1>";
        echo "<p>Name: " . htmlspecialchars($name) . "</p>";
        echo "<p>Email: " . htmlspecialchars($email) . "</p>";
        echo "<p>Age: " . htmlspecialchars($age) . "</p>";
    } else {
        // Display errors
        foreach ($errors as $field => $error) {
            echo "<p>Error in $field: $error</p>";
        }
    }
} else {
    echo "Invalid request.";
}
?>        

6.5 Events, Cookies,?Sessions

6.5.1 Cookies

Definition: Cookies are small pieces of data stored on the client side by the web browser, allowing websites to remember information about the user across different sessions.

6.5.2 Concepts:

Purpose of Cookies:

  • Session Management: Keeping track of user sessions (e.g., login status).
  • Personalization: Storing user preferences and settings (e.g., theme selection).
  • Tracking: Monitoring user behavior for analytics and targeted advertising.

Cookie Structure:

  • Name: Identifier for the cookie.
  • Value: The data stored in the cookie.
  • Domain: Specifies which domain can access the cookie.
  • Path: Defines the URL path for which the cookie is valid.
  • Expiry Date: Determines when the cookie will be deleted. If not set, the cookie will expire at the end of the session (when the browser is closed).

Cookie Management in JavaScript:

  • Creating a Cookie: Assigning a value to document.cookie.
  • Reading a Cookie: Parsing document.cookie to retrieve values.
  • Deleting a Cookie: Setting the cookie’s expiry date to a past date.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Events and Cookies Example</title>
    <script src="script.js" defer></script>
</head>
<body>
    <h1>Events and Cookies</h1>
    <button id="setCookieBtn">Set Cookie</button>
    <button id="getCookieBtn">Get Cookie</button>
    <button id="deleteCookieBtn">Delete Cookie</button>
    <p id="message"></p>
</body>
</html>
// Event listeners for buttons
document.getElementById('setCookieBtn').addEventListener('click', () => {
    setCookie('username', 'JohnDoe', 7); // Set a cookie for 7 days
    document.getElementById('message').innerText = "Cookie 'username' set.";
});

document.getElementById('getCookieBtn').addEventListener('click', () => {
    const cookieValue = getCookie('username');
    document.getElementById('message').innerText = cookieValue ? `Cookie Value: ${cookieValue}` : "Cookie not found.";
});

document.getElementById('deleteCookieBtn').addEventListener('click', () => {
    deleteCookie('username'); // Delete the cookie
    document.getElementById('message').innerText = "Cookie 'username' deleted.";
});

// Function to set a cookie
function setCookie(name, value, days) {
    const expires = new Date(Date.now() + days * 864e5).toUTCString(); // Set expiration date
    document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/`;
}

// Function to get a cookie by name
function getCookie(name) {
    return document.cookie.split('; ').reduce((r, c) => {
        const [key, val] = c.split('=');
        return key === name ? decodeURIComponent(val) : r;
    }, '');
}

// Function to delete a cookie
function deleteCookie(name) {
    setCookie(name, '', -1); // Set the cookie with a past expiration date
}        

6.5.2 Handling Sessions in?PHP

Sessions in PHP are used to store information about a user’s session across multiple page requests. This is essential for maintaining user data like login status, shopping cart items, and other persistent information.

6.5.3 Starting a?Session

To start a session, use the session_start() function at the beginning of our PHP script:?

<?php
session_start();
?>        

6.5.4 Storing Data in a?Session

We can store data in the session using the $_SESSION array:

<?php
session_start();
$_SESSION['username'] = 'John Doe';
$_SESSION['cart'] = array('item1', 'item2');
?>        

6.5.5 Accessing Session?Data

To retrieve data from the session, simply access the corresponding element in the $_SESSION array:

<?php
session_start();
echo "Username: " . $_SESSION['username'];
?>        

6.5.6 Destroying a?Session

To destroy a session, use the session_destroy() function:

<?php
session_start();
session_destroy();
?>        

6.5.7 Important Considerations:

  1. Session Lifetime: By default, sessions are stored on the server and expire when the browser is closed. We can modify the session lifetime using the session_set_cookie_params() function.
  2. Session ID: A unique session ID is generated for each user. This ID is typically stored in a cookie.
  3. Session Security: Be mindful of session security. Avoid storing sensitive information in sessions and use HTTPS to protect data transmission.

6.6 Working with PHP and MySQL: Connecting to Database, Creating, Selecting, Deleting, Updating?Records

Below is the simple code on PHP CRUD. This code is just for the demonstration and is focused on lab work. It is not suitable for production.

6.6.1 Creating?Record

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cct";

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

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $email = $_POST['email'];

    $sql = "INSERT INTO student (firstname, lastname, email) VALUES ('$firstname', '$lastname', '$email')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
        header('Location: retrive.php');
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Student Record</title>
</head>
<body>
    <h2>Create New Student Record</h2>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <label for="firstName">First Name:</label>
        <input type="text" id="firstname" name="firstname" required>
        <br>
        <label for="lastName">Last Name:</label>
        <input type="text" id="lastname" name="lastname" required>
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br>
        <input type="submit" value="Create Record">
    </form>
</body>
</html>        

6.6.2 Search and Display?Result

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cct";

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

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

// Handle search query
$search = isset($_POST['search']) ? $_POST['search'] : "";

// SQL query to retrieve data based on search input
$sql = "SELECT id, firstname, lastname, email FROM student 
        WHERE firstname LIKE '%$search%' 
        OR lastname LIKE '%$search%' 
        OR email LIKE '%$search%'";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Search Student Records</title>
</head>
<body>
    <h2>Search Student Records</h2>
    <form method="post">
        <label for="search">Search:</label>
        <input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search); ?>">
        <input type="submit" value="Search">
    </form>
    <?php
    if ($result->num_rows > 0) {
        echo "<table border='1'>
                <tr>
                    <th>ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Email</th>
                </tr>";
        while ($row = $result->fetch_assoc()) {
            echo "<tr>
                    <td>" . $row["id"] . "</td>
                    <td>" . $row["firstname"] . "</td>
                    <td>" . $row["lastname"] . "</td>
                    <td>" . $row["email"] . "</td>
                </tr>";
        }
        echo "</table>";
    } else {
        echo "No results found";
    }
    $conn->close();
    ?>
</body>
</html>        

6.6.3 Updating?Record

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cct";

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

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

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = $_POST['id'];
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $email = $_POST['email'];

    $sql = "UPDATE student 
    SET firstname='$firstname', 
    lastname='$lastname',
    email='$email' WHERE id=$id";

    if ($conn->query($sql) === TRUE) {
        echo "Record updated successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Update Student Record</title>
</head>
<body>
    <h2>Update Student Record</h2>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <label for="id">Student ID:</label>
        <input type="number" id="id" name="id" required>
        <br>
        <label for="firstname">First Name:</label>
        <input type="text" id="firstname" name="firstname" required>
        <br>
        <label for="lastname">Last Name:</label>
        <input type="text" id="lastname" name="lastname" required>
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br>
        <input type="submit" value="Update Record">
    </form>
</body>
</html>        

6.6.4 Deleting?Record

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cct";

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

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

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = $_POST['id'];

    $sql = "DELETE FROM student WHERE id=$id";

    if ($conn->query($sql) === TRUE) {
        echo "Record deleted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Delete Student Record</title>
</head>
<body>
    <h2>Delete Student Record</h2>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <label for="id">Student ID:</label>
        <input type="number" id="id" name="id" required>
        <br>
        <input type="submit" value="Delete Record">
    </form>
</body>
</html>        

6.7 Introduction to CodeIgniter, Laravel, WordPress

6.7.1 CodeIgniter

A lightweight PHP framework. CodeIgniter is widely used by developers who prefer simplicity, performance, and a low learning curve for their web development projects.?

Key features:

  • Modular architecture for better organization.
  • Built-in libraries for common tasks like database interaction, form validation, and session management.
  • Excellent performance and scalability.

6.7.2 Laravel

A full-featured and popular framework. It offers a more expressive and elegant syntax compared to CodeIgniter.

Key features:

  • Eloquent ORM for seamless database interactions.
  • Blade templating engine for efficient and reusable views.
  • Artisan command-line interface for automating tasks.
  • Strong community and extensive ecosystem of packages.

6.7.3 WordPress

A popular content management system (CMS) built on PHP. Originally designed for blogging but has evolved into a versatile platform for creating websites of all kinds.

Key features:

  • User-friendly interface for managing content.
  • Extensive plugin and theme ecosystem for customization.
  • Strong SEO capabilities.
  • Large and active community.

7. Conclusion

As of 25 Sept 2024, the terms and examples plotted in the article can be outdated or not used anymore while you are reading this article because of the advancement in web technology. However, the aim is to outline the core concepts, and terms, and provide foundational knowledge with simplified examples. This article highlights how essential theory and concepts are required for understanding the techniques and developing modern web applications.?

Web technology is integral to the modern landscape of computer science, influencing various fields such as software development, data analysis, and user experience design. As the demand for web applications continues to grow, so does the necessity for web developers who possess a robust skill set.

8. References:

  • Tribhuvan University, Institute of Science and Technology, B.S.c.CSIT(Computer Science and Information Technology (CSC318) Web Technology) 2017 A.D Course Syllabus

  • w3schools
  • LLMs(Coding)

Read More Articles on Dilli Hang Rai | LinkedIn

More About me: dilli822.github.io

Feedback & Review: [email protected], [email protected]



要查看或添加评论,请登录

Dilli Hang Rai的更多文章

社区洞察

其他会员也浏览了