Web Programming notes
Web Programming notes
Full-stack development involves creating web applications covering both front-end and back-end aspects,
along with effective database management. In this holistic approach, developers handle the entire application
stack, from the user interface (UI) to server-side logic and database functionality. For example, consider a
sign-in page on a website. The front-end, or client-side, presents the UI where users input data, and this
information is sent to the back-end, or server-side, for validation through the database.
• Full-Stack Developer Skills
A full-stack developer possesses skills across all layers of an application, integrating different technologies
and frameworks to create end-to-end solutions.
• Front-End Development
Front-end development focuses on UI design using core technologies like HTML, CSS, and JavaScript.
Responsive design ensures that web applications adapt uidly to various devices, providing a consistent user
experience. Additionally, web accessibility in front-end development involves designing interfaces usable by
people with disabilities.
• Back-End Development
On the back-end, developers manage server-side logic, handle client requests ef ciently, and engage in API
development. The choice of server environments, such as Node.js with Express, requires a careful
con guration for stable and ef cient back-end operations. API development involves creating endpoints for
seamless data interaction between the server and client, enhancing overall functionality.
• Database Management
Database management is crucial for the effective storage and retrieval of data using systems like MySQL,
PostgreSQL, or MongoDB. Database design principles, including normalization and indexing, optimize data
organization and retrieval speed. Database management ensures data integrity through transactions
following ACID properties.
• Version Control and Collaboration
Version control systems like Git facilitate collaborative development by tracking changes to code, enabling
teamwork and systematic codebase management. Branching and merging are essential functionalities,
allowing developers to work independently on features before merging changes.
APIs in Full-Stack Development
APIs play a vital role in connecting front-end and back-end systems, enabling seamless data exchange.
Different types of APIs cater to diverse purposes, including RESTful APIs, Library APIs, Operating System
APIs, Database APIs, and OAuth APIs, among others.
API Bene ts
In the context of full-stack applications, front-end components leverage APIs to request and retrieve data
from the backend, enabling seamless user interactions and dynamic content updates. APIs also facilitate
communication in microservices architectures, where different parts of an application are developed and
deployed independently.
Moreover, APIs are instrumental in integrating full-stack applications with third-party services or APIs,
enhancing functionality by connecting with services like payment gateways, social media platforms, or
mapping services. They play a crucial role in versioning different parts of applications, ensuring smooth
updates and feature introductions without disrupting existing functionality. Additionally, APIs contribute to
secure communication, implement mechanisms such as API keys or OAuth tokens, and play roles in user
authentication and authorization.
API Types
Different types of APIs serve diverse purposes, including RESTful APIs, Library APIs, Operating System
APIs, Database APIs, and OAuth APIs, among others.
Deployment and Hosting
To make an app live, developers deploy it on a hosting platform. Choosing a platform involves
considerations like Heroku for a user-friendly experience, AWS for extensive cloud services, or Netlify for
simplicity and a focus on static sites. Scalability and performance requirements are crucial, and platforms
like AWS provide scalable solutions with resource adjustments based on demand. Load balancing and
fi
fi
fi
fl
fi
caching mechanisms optimize performance by distributing incoming traf c across multiple servers and
storing frequently accessed data, respectively. These measures contribute to a smoother user experience.
MERN Stack
A similar stack, MERN (MongoDB, Express.js, React, Node.js), replaces Angular with React, emphasizing
reactivity and seamless integration. MERN leverages React’s virtual DOM for ef cient UI development and
bene ts from a vibrant development community.
RESTful APIs
RESTful APIs, following a set of architectural principles, are designed to be simple, scalable, and exible.
They adhere to the stateless principle, where each client request contains all necessary information for the
server to understand and ful ll it without storing the client state between requests. These APIs utilize
standard HTTP methods—GET for retrieval, POST for creation, PUT for updating or creating, and DELETE
for removal.
• Key Abstractions
Key abstractions in RESTful APIs are resources, identi ed by Uniform Resource Identi ers (URIs),
representing entities like objects, data, or services. These APIs provide a uniform interface for interacting
with resources, ensuring consistency in access, manipulation, and navigation. Resources are represented in
formats such as JSON or XML, and clients interact with representations rather than the resources directly.
• API Endpoints
API endpoints are speci c URLs or URIs exposed by an API for client interaction. They correspond to
functions or operations, with the HTTP method indicating the action. A complete API endpoint combines the
base URL, endpoint path, and any additional parameters. For instance, GET https://api.example.com/users
retrieves a list of users.
• Fetch API
The Fetch API, a modern JavaScript API, simpli es HTTP requests. It initiates requests and handles
responses asynchronously. For example, the fetch function is used to request data, with subsequent .then()
blocks processing the response and handling errors.
// Validate and sanitize input (you can add more validation as needed)
$name = htmlspecialchars(trim($name));
$email = lter_var($email, FILTER_VALIDATE_EMAIL) ? $email : null;
$gender = in_array($gender, ["male", "female", "other"]) ? $gender : null;
$website = lter_var($website, FILTER_VALIDATE_URL) ? $website : null;
Characteristics of Microframeworks:
• Minimalistic Structure: Microframeworks provide only essential functionalities, ensuring a
lightweight and fast-paced development process without extensive built-in features.
• Flexible Component Selection: Developers can selectively integrate components based on project
needs, allowing for a tailored approach to development by leveraging preferred libraries or
extensions.
• Simpli ed Routing: These frameworks offer straightforward routing mechanisms, making it easy to
de ne endpoints and handle incoming HTTP requests ef ciently.
• Third-Party Libraries/Extensions: Microframeworks rely on third-party libraries or extensions for
features like authentication, allowing developers to choose the most suitable and secure methods for
their projects.
fi
fi
fl
fi
fi
fi
fi
fl
fi
fi
• Database Interaction: They enable database interactions using third-party libraries, providing
freedom to select databases and interaction methods tailored to project requirements.
• Input Validation: Microframeworks facilitate streamlined input validation through third-party
libraries or custom implementations, ensuring data integrity and security with user inputs.
• Template Engines: While often minimalist, microframeworks integrate with various template
engines, empowering developers to choose and use templates suited to their project’s UI rendering
needs.
Introduction to Lumen
Lumen, developed by Laravel, is a microframework tailored for the swift construction of high-performance
microservices and APIs. Its lightweight design ensures faster performance and optimized resource usage
compared to Laravel.
Key Features of Lumen
• Lightweight Design
• Designed to be lightweight and minimalistic.
• Provides essential functionalities in a stripped-down version of Laravel.
• Microservices and API Development
• Geared toward high-speed processing and minimal overhead.
• Speci cally tailored for the development of microservices and APIs.
Installation
Use Composer to install Lumen: composer create-project --prefer-dist laravel/lumen project-name.
Creates a new Lumen project with necessary dependencies.
Environment Con guration
• Store environment-speci c con gurations in the .env le.
• Con gure database and other settings using key–value pairs.
Route De nition
• De ne web routes in routes/web.php and API routes in routes/api.php.
• Segregate routes for better organization.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Controller Generation
• Generate controllers using Artisan’s make:controller command.
• Controllers organize logic and handle incoming requests for web or API routes.
Database Interaction with Eloquent
• Utilize Eloquent, Laravel’s ORM, for database tasks.
• Create models representing database tables, de ning relationships, and data retrieval methods.
Middleware Application
• Apply middleware to routes or groups of routes.
• Perform tasks like authentication, logging, or modifying requests.
Lumen’s Strengths
Lumen’s focus on speed, ef ciency, and scalability positions it as an ideal choice for projects requiring high-
performance microservices and API development. Its seamless integration with Laravel’s ecosystem,
coupled with its lightweight design, makes it a powerful tool for rapid and ef cient web development.
Example: $router->get('/protected', ['middleware' => 'auth', 'uses' => ‘Controller@method']);.
Echo
A PHP script demonstrates the declaration of variables with different data types and their echo outputs. The
echo construct is versatile, displaying variable values, plain text, concatenated strings, HTML integration,
expressions, and Boolean values. Echo contributes to dynamic content generation, making PHP a robust
language for web development.
Display Output: Echo Examples
Variable Concatenation:
Variable Interpolation:
Operator Precedence
In PHP, understanding operator precedence and associativity is crucial for crafting effective and error-free
expressions.
PHP Operators
A PHP script demonstrates basic arithmetic operations, conditional operator usage for decision-making,
comparison operators for numeric relationships, logical operators for decision trees, and compound
assignment operators for incremental modi cations.
1.Arithmetic Operations Script:
fi
fi
fi
2.Conditional Operator Script:
Syntax:
Example
For Switch-Case
fi
fi
Example
Example
Loops
Loops in PHP enable the execution of a block of code repeatedly as long as a certain condition is true. The
main types of loops are:
• for: Executes a block of code a speci ed number of times.
• while: Repeats a block of code as long as a speci ed condition is true.
• do-while: Similar to while, but the block of code is executed at least once, even if the condition is
initially false.
• foreach: Iterates over elements in an array or other iterable data structures.
For Loop
fi
fi
While Loop
Do-While Loop
Examples
These control structures provide essential tools for managing the ow of execution in PHP programs. They
allow developers to create exible and dynamic scripts by making decisions based on conditions, repeating
code execution with loops, and controlling the ow within loops using break and continue statements.
Functions
In PHP, functions are crucial for modularizing code. There are two main types: system functions (pre-built,
like date, time, and string functions) and custom functions (created by developers for speci c tasks). System
functions enhance code ef ciency, while custom functions improve reusability and readability.
System Functions in PHP: Date function, Date and Time function, String functions.
Date Function: Formats current date and time.
Date and Time Functions: Obtain the current date and timestamp.
fi
fl
fi
fl
fl
fi
String Functions:
Array
In PHP, arrays are fundamental data structures that store and organize elements, each identi ed by an index.
They are versatile, accommodating various data types, and come in two primary types: numeric arrays and
associative arrays.
Numeric Arrays:
Numeric arrays use numerical indices for element access, typically starting from 0. They can be initialized
using either the array() construct or square brackets []. Here is an example:
$array = array("Apple", "Banana", "Orange");
// OR
$array = ["Apple", "Banana", "Orange"];
The count() function determines the array length, and a for loop iterates through the elements, demonstrating
sequential access.
fi
fi
Associative arrays:
Associative arrays use string indices, providing a descriptive way to organize data. They are created using
the array() construct with key–value pairs.
Example
Output - Name: John Doe Age: 25 City: New York Email: john@example.com
Updated Age: 26 Gender: Male Iterating through the array: name: John Doe age: 26 city: New York email:
john@example.com gender: Male
The array $userDetails is populated with user attributes, and values are accessed using speci c keys.
Dynamic modi cations, such as updating the age and introducing a new key–value pair, illustrate the
adaptability of associative arrays.
Errors
Errors in programming can be categorized into different types, such as Syntax Errors, Logical Errors, and
Runtime Errors. Syntax Errors involve violations of programming language syntax rules, while Logical
Errors result from aws in the program’s logic, leading to unexpected outcomes. Runtime Errors occur
during program execution and may include scenarios like attempting to divide by zero or accessing an out-
of-bounds array index, posing challenges during execution.
Exception Handling
Exceptions are events that cause unexpected outcomes in a program, primarily triggered by runtime errors.
Exception handling is a technique used to manage errors effectively, allowing developers to gracefully
handle unexpected situations. PHP provides keywords for exception handling:
Encapsulating potentially error-prone code in the try block, handling speci c exceptions in the catch block,
and executing necessary cleanup in the nally block ensures robust error management. For example, when
fetching data from an external API, a try block can handle successful API calls, while a catch block manages
exceptions like network errors. The nally block ensures that essential cleanup operations are performed.
PHP provides several important exceptions, including:
Exception: The base class that provides common methods and properties for exceptions.
DivisionByZeroError: Used for divide by zero errors.
OutOfBoundsException: Captures index out-of-bound scenarios for arrays.
RunTimeException: A generic exception for various runtime errors.
Example - DivisionByZeroError Exception:
In this example, the code attempts to divide by zero, triggering a DivisionByZeroError exception. The catch
block handles the exception by printing a message, and the nally block is executed regardless of whether an
exception occurred. This demonstrates how exception handling in PHP ensures graceful management of
unexpected scenarios, enhancing program reliability.
fi
fl
fi
fi
fi
fi
fi
Basic Exception Handling
PHP Sessions
In PHP, sessions are a vital mechanism for maintaining stateful interactions between web servers and users,
enabling the persistence of user-speci c data across multiple pages or visits. Sessions facilitate a seamless
and personalized browsing experience by storing information such as user credentials, preferences, and
shopping cart contents. The process begins with a user-initiated login, triggering the server to create a
unique session identi er (sessionid) that links the browser to server-side session data.
The “$_SESSION” superglobal array is a powerful tool for developers, allowing the secure storage and
retrieval of session variables. To initiate a session, “session_start()” is invoked, marking the commencement
of user-speci c data management. The stored session data is maintained on the server, while a session
identi er cookie on the client side ensures the association between the browser and the session.
Storing data within sessions involves simple assignments, like “$_SESSION['user_id'] = 123,” ensuring the
continuity of user details throughout their session.
To conclude a session, “session_destroy()” is utilized, clearing all associated data. PHP sessions provide a
robust foundation for creating dynamic and stateful web applications, enhancing user experiences through
personalized and uninterrupted interactions.
Example
fi
fi
fi
fi
PHP Cookies
Cookies in PHP serve as essential tools for storing small data snippets on a client’s browser, enabling the
preservation of user details across web sessions. This cyclical exchange between the client and server
involves the browser initiating a request, receiving a cookie from the server, and subsequently forwarding it
in future requests. Using the setcookie() function in PHP, developers can customize parameters such as
name, value, expiration time, path, domain, and security options. This customization empowers web
applications to offer personalized experiences, utilizing cookies as ef cient data carriers. Setting a cookie
involves specifying its name, value, expiration time, and optional parameters.
Set and Retrieve Cookie:
Deleting a Cookie:
fi
Form handling in PHP
Form handling in PHP is integral to web development, involving creating HTML forms processed on the
server side using PHP scripts. Web forms enable user interaction by submitting data, with PHP handling this
data on the server, performing processing, and responding to users. Two common methods for sending form
data are the GET and POST methods. The GET method appends encoded user information to the page
request, visible in the URL, while the POST method transfers information via HTTP headers, suitable for
sensitive or binary data.
A practical example demonstrates form handling using HTML and PHP scripts. A basic web form captures
user input, with the PHP script processing the data. The “Input.html” le contains the form, and when
submitted, the data is sent to “Welcome.php” using either the GET or POST method. The PHP script
retrieves the values and generates a welcome message displayed on the web page. This exempli es the
fundamental role of PHP in handling user input for interactive web applications.
PHP Forms: GET Method
Input.html
Understanding the foundational SQL commands and PHP-MySQL integration is crucial for effective data
management and manipulation in web development.
Data Serialization Formats in Web Programming
Data serialization formats in web programming are crucial for organizing and exchanging computer data,
especially in the face of diverse hardware architectures and operating systems. The challenge arises when
data needs to be transferred between systems with inherent differences, such as Windows to Unix or between
Java and .NET applications with varying data types. The solution lies in platform-and-language-neutral data
serialization formats like JSON and XML, acting as a common language for universal comprehension and
interaction.
Serialization involves transforming structured data into a byte stream for ef cient storage, transmission, or
network transfer, while deserialization reverses this process to reconstruct the original data object. These
processes are fundamental in modern software development, facilitating tasks like data storage, network
communication, and ef cient data manipulation. Serialized data nds its home in les and databases. Files
on disks allow data retention even when applications are inactive, while databases support ef cient storage
and retrieval of serialized objects. Popular text-based serialization formats include XML, known for its
hierarchical structure, and JSON, valued for its simplicity in web development and APIs.
Choosing the Right Serialization Format
Choosing the right serialization format depends on factors like data complexity, human readability, speed,
and storage space constraints. Formats like XML and YAML suit complex data hierarchies, while JSON and
CSV are preferred for simplicity and speed. The decision ultimately hinges on the speci c requirements of
the application at hand.
Common Serialization Formats
XML (eXtensible Markup Language)
XML, or eXtensible Markup Language, is a versatile meta-language for storing and transferring data.
Utilizing tags similar to HTML, XML enables users to de ne their tags, attributes, and hierarchies, offering
exibility for the structured representation of data. It nds primary use in storing and exchanging structured
data between systems and applications, excelling in readability for humans and machines. XML
accommodates highly structured data common in databases and loosely structured content like letters or
articles, showcasing its adaptability.
The need for XML arises from the limitations of HTML, which has a xed set of tags and lacks restrictions
on tag arrangement. XML addresses these issues by allowing users to de ne their tags, attributes, and
hierarchies, providing a customized and structured language suitable for various data representations. It
imposes rules for clear and unambiguous data structure, making it ideal for organizing diverse types of
information without the constraints of prede ned HTML tags.
JSON (JavaScript Object Notation)
JSON (JavaScript Object Notation) is a widely used data format known for its simplicity, making it both
human-readable and machine-understandable. Its concise and straightforward structure facilitates easy
readability and manipulation, particularly in web development, data exchange, and communication between
systems. JSON’s compatibility, ef ciency, and support across various programming languages contribute to
its prevalence in modern web and application architectures.
YAML (YAML Ain’t Markup Language)
YAML, humorously standing for "YAML Ain't Markup Language," is a robust tool for data serialization and
con guration les. Serving as a superset of JSON, YAML extends capabilities while maintaining
compatibility. Its human-friendly syntax enhances readability, supporting a wider range of complex data
types for intricate data representations. YAML allows comments within data, aiding documentation and
maintainability, and its les can be manually modi ed while retaining structure and readability.
Use Cases for Each Format
Utility and use cases for XML, JSON, and YAML:
• XML: Well-suited for structured document storage, making it an ideal choice when dealing with
documents that require a strict hierarchical structure and prede ned tags to represent data elements.
• JSON: Primarily used in web APIs and for data interchange between servers and clients due to its
lightweight, readable, and straightforward format, facilitating seamless data transmission.
• YAML: Preferable for con guration les and human-readable data representations where
conciseness and readability are crucial. YAML’s succinct yet clear syntax makes it advantageous for
con guration settings and serializing complex but easily understandable data structures.
Each format excels in different scenarios, providing distinct advantages based on the speci c requirements
of the application or system at hand.
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Introduction to XML
XML, or Extensible Markup Language, is a versatile structured data format designed for both human
understanding and computer processing. Its strength is handling semi-structured data, making it suitable for
diverse applications. XML’s exibility allows users to create custom tags, accommodating various data types
such as web content, con guration settings, or structured documents. For instance, in a library system, XML
tags can represent book details like titles, authors, and publication dates, ensuring clear organization.
XML Document Structure
XML documents follow speci cations outlined in XML, identi ed by the .xml le extension. These
documents use tags and attributes to create a hierarchical tree-like structure, ensuring consistency and
clarity. The fundamental structure includes a single root element encompassing all others, facilitating
ef cient interpretation by both humans and machines. The core building block of an XML document is the
XML element, de ned by opening and closing tags. These elements encapsulate content, forming the basic
organizational format of XML. Attributes within XML elements provide additional details or metadata,
contributing to a more detailed representation of data.
Example XML Document
XML document that describes information about a baseball player
XML documents are portable and can be viewed and edited using text editors. Web browsers can display
XML in a formatted manner, but specialized software, called an XML parser, is needed to process XML
documents. The parser veri es adherence to rules such as a single root element, proper start and end tags,
and correct nesting, ensuring the integrity of XML documents.
XML for Complex Structures - XML Nesting
XML supports nesting, allowing the creation of complex structures. For example, a library system could
have a root element “library” containing nested “book” elements, each with details like title, author, and
publication year, showcasing XML’s ability to represent intricate data relationships.
Part-I
fi
fi
fi
fi
fl
fi
fi
fi
Part-II
XML Validation
XML validation is essential for ensuring the reliability and integrity of XML documents, serving several
crucial purposes. First and foremost, it ensures well-formedness by checking syntax rules and verifying
proper tags, nesting, attributes, and closing structures. This adherence to syntax rules is vital for the
document to be considered well-formed according to XML speci cations. Validation also ensures that XML
documents adhere to a prede ned structure or schema. Schemas de ne rules for elements, attributes, data
types, and their relationships. Validating against a schema ensures consistency and conformity to these
guidelines, promoting data integrity and accuracy. This is crucial for maintaining compatibility between
different systems, as standardized XML documents can be easily exchanged and interpreted without
compatibility issues.
Moreover, XML validation helps catch errors early in the development process. By detecting issues during
development, developers can debug and rectify problems before they impact production environments,
enhancing the overall reliability of XML-based systems. A well-formed XML document must adhere to
syntax rules, including having a single root element, matching opening and closing tags, case sensitivity,
proper nesting, and quoted attribute values. Validation plays a crucial role in ensuring that these
requirements are met. Various methods are employed for XML validation, including Document Type
De nition (DTD), XML Schema De nition (XSD), and Relax NG. These schema languages de ne the
structure and constraints of XML documents, enabling thorough validation.
XML Validation Tools
Several tools facilitate XML validation, offering different approaches to developers. Online validators like
XMLLint provide web-based validation services, command-line tools like xmllint offer validation through
terminals for automation, and Integrated Development Environments (IDEs) like XMLSpy or Oxygen XML
Editor integrate comprehensive XML validation tools, enhancing the overall XML development experience.
These tools contribute to accurate and standards-compliant XML creation and management by checking
syntax, validating against speci c schemas, and detecting errors.
Check whether the XML document is well-formed.
fi
fi
fi
fi
fi
fi
fi
The XML document is NOT WELL FORMED!
<city> element is not closed properly
<root> element is not closed
XML Schema (XSD)
XML Schema, also known as XML Schema De nition (XSD), serves dual purposes in handling XML data.
Firstly, it describes the structure and content of an XML document, outlining elements, attributes, and their
relationships. Secondly, it validates XML documents against prede ned rules, acting as a blueprint for
elements, attributes, data types, and constraints. The schema de nes elements, attributes, and data types,
allowing the speci cation of allowed values and constraints. This detailed description of XML documents
promotes data integrity, consistency, and conformity to prede ned guidelines. XML Schemas nd extensive
use in scenarios requiring data exchange between different systems, preventing inconsistencies and errors by
enforcing prede ned constraints.
XML Schema ensures the well-formedness of XML documents by describing their syntax, including proper
nesting, correct tag structures, and case sensitivity. When an XML document complies with an XML
Schema, it is termed “Valid,” meeting both syntax and structural constraints. Elements, the fundamental
building blocks of XML documents, are de ned in XML Schema using the xs:element tag.
<xs:element name = "x" type = "y"/>
This tag, part of the XML Schema namespace (xs), speci es the name and type of the element, forming the
blueprint for its structure.
XML Schema supports two main types of element de nitions: simple and complex. Simple types are
associated with primitive data types like integers or strings, while complex types act as containers for other
element de nitions, providing structured hierarchies within XML documents.
Prede ned Simple Types
xs:integer
xs:Boolean
xs:string
xs:date
Example: <xs:element name = "phone_number" type = "xs:int" />
A practical example of a complex type in XML Schema is illustrated, showcasing the de nition of a
“Contact” element with child elements like name, company, and phone. This structure ensures speci c order
and types for child elements within the “Contact” element.
Complex Type Example
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Global Types
Global types in XML Schema allow the creation of types that can be referenced throughout the entire
schema, ensuring consistency and reusability. For instance, a global type called “AddressType” can be
de ned, and various elements can reference this global type, promoting uniformity and simplifying
maintenance.
Global Type Example
The concept of global types is further demonstrated in an example where “AddressType” is de ned globally
and referenced by elements “Address1”and “Address2.” This approach enables consistent structuring across
different sections of the XML document and facilitates maintenance.
XML Tree Structure
An XML tree structure, inherent in XML documents, organizes data hierarchically through parent–child
relationships. It maintains order and relationships among elements, allowing nesting for a clear
representation. Elements, enclosed in tags, represent entities, while attributes offer additional details. This
structure is exempli ed in a bookstore scenario, where each book has attributes like category. The XML tree
is then utilized to create an XML Schema. The schema de nes elements, types, and constraints, ensuring a
fi
fi
fi
fi
standardized structure. In the provided XML Schema for a bookstore, it speci es the “bookstore” element
with a complex type, including elements like “title,” “author,” “year,” and “price” with de ned types and
constraints. This schema guides the creation of XML documents adhering to the de ned structure.
Create an XML document for the following tree structure.
Nested JSON
Nested JSON, or JSON nesting, involves incorporating one JSON object as a value within another JSON
object or including JSON arrays within other JSON arrays, creating a hierarchical or nested structure. This
approach is employed to represent complex and structured data relationships. Use cases for nested JSON
include structured data representation, where hierarchical relationships like organizational charts or tree
structures are involved. APIs often return nested JSON structures to provide comprehensive information
about a resource, including nested details about pro les, preferences, or related entities. Con guration les
for applications may use nested JSON to represent various settings with sections or categories containing
further details. In document databases like MongoDB, nested JSON-like structures allow for exible and
nested data models. In front-end development, nested JSON is frequently used to represent complex data
structures, especially when dealing with nested components or hierarchical data in user interfaces.
In this example:
• The JSON structure contains an object with a key “artists” whose value is an array of artists.
• An object represents each artist within the “artists” array.
• The “Deep Purple” artist object includes the keys “artistname,” “formed,” and “albums.”
• The “albums” key holds an array of album objects for that particular artist.
• Each album object contains details such as “albumname,” “year,” and “genre.”
This demonstrates a nested JSON structure where an array of artists contains multiple albums, showcasing
the relationship between artists and their albums.
fi
fi
fi
fi
fi
fl
fl
fi
JSON Parsing in JavaScript
In web development, converting JavaScript objects to JSON and vice versa is essential for various purposes.
JSON parsing plays a crucial role in scenarios such as data interchange, facilitating lightweight information
exchange between servers and web applications. It is integral for ef cient data transmission between clients
and serv, ensuring structured and quick transfers. APIs widely employ JSON for effective communication
between different systems due to its human-readable format. JSON also nds extensive use in storing and
persisting data in databases, offering exibility for complex data structures. Additionally, JSON parsing is
crucial for securely handling data from external sources, preventing potential security vulnerabilities.
To convert a JSON string to a JavaScript object, the JSON.parse() method is employed in JavaScript. This
process is vital when handling data from external sources like APIs or les, enabling effective interaction
and manipulation of the received data.
Example JSON Parsing—Parse JSON string to JavaScript object
let jsonString = '{"name": "Shreyas", "age": 40}';
let jsObject = JSON.parse(jsonString);
console.log(jsObject);
Conversely, the JSON.stringify() method is used to convert a JavaScript object to a JSON string, crucial for
scenarios such as data transmission or storage. This method ensures the representation of data in a
standardized JSON format, allowing seamless sharing across different systems or APIs.
Convert JavaScript object to JSON string
let jsPerson = { name: "Shreyas", age: 40 };
let jsonString = JSON.stringify(jsPerson);
console.log(jsonString);
This structured JSON representation ensures seamless order processing and effective integration with the
online bookstore system.
JSON in Web Programming
JSON plays a pivotal role in various web programming applications, notably in utilizing the Twitter API and
Google Maps integration. In the Twitter API, developers extract data in JSON format, including tweets, user
fi
fi
fi
fi
fi
fi
fi
pro les, search results, trends, and hashtags. This data enhances website interactivity, enabling features like
live tweet feeds and personalized user experiences. In the realm of Google Maps, JSON facilitates the visual
representation of geographical data through markers. These graphical icons, placed on the map, signify
speci c locations and offer animation effects, ensuring a seamless experience across both mobile and
desktop devices.
Moreover, JSON serves a crucial function in web applications by facilitating communication between the
user interface (UI) and backend server. It de nes the request and response format, with the UI sending
JSON-formatted requests for user interactions, and the backend responding in JSON with requested data or
action acknowledgments. API endpoints, asynchronous communication, and the exibility of JSON
contribute to the ef ciency of data exchange in modern web applications.
Introduction to YAML
YAML, a human-readable data serialization format, relies on indentation, key–value pairs, and sequences for
its syntax. It is commonly used in web programming for its readability and simplicity, particularly in
scenarios where human interaction is required, such as con guration les. YAML supports comments,
mapping (key–value pairs), and sequences (lists/arrays). Its sensitivity to spaces, case, and emphasis on
indentation for structure is noteworthy.
YAML Syntax Examples
Comment
# This is a comment
person:
name: John Doe # Inline comment
age: 30
Mapping (Key–Value Pairs)
YAML in Ansible
Ansible, a popular con guration management tool, employs YAML for expressing playbooks. YAML’s
versatility in orchestrating tasks and de ning con gurations makes it well-suited for Ansible’s use case.
Playbooks written in YAML provide a concise and readable way to describe automation tasks in Ansible.
Source: https://gist.github.com/gopal1996/de0b218253fcf8c9634bd8029d14eaf4
A request for a web page or app starts with an HTML request. The server returns the HTML response
headers and data. The browser then begins parsing the HTML, converting the received bytes to the DOM
tree. The browser initiates requests every time it nds links to external resources, be it stylesheets, scripts, or
embedded image references. Some requests are blocking, which means the parsing of the rest of the HTML
is halted until the imported asset is handled. The browser continues to parse the HTML, making requests and
building the DOM, until it gets to the end, at which point it constructs the CSS object model. With the DOM
and CSSOM completion, the browser builds the render tree, computing the styles for all the visible content.
After the render tree is complete, layout occurs, de ning the location and size of all the render tree elements.
Once complete, the page is rendered or “painted” on the screen.
We can improve page load speed by prioritizing which resources get loaded, controlling the order in which
they are loaded, and reducing the le sizes of those resources.
<script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags. You can place any number of
scripts in an HTML document. When including JavaScript code in an HTML document, one important
consideration is the placement of the script tags. Scripts can be placed in the <body>, the <head> section of
an HTML page, or both. The browser parses the HTML document from top to bottom. As it encounters the
scripts in the <head> section, the rest of the DOM element creations will be paused for the scripts to
download and execute. To solve the issue, it was recommended to place script tags at the bottom of the
HTML document, just before the closing </body> tag. It will ensure that all the DOM elements are
constructed and ready before we download and execute the scripts.
HTML provides the async and defer attributes to load the page faster and minimize the larger script loading
lag by downloading them in the background. The defer attribute tells the browser not to wait for the script.
Scripts with defer always execute when the DOM is ready. The async attribute means that a script is
completely independent and the browser does not block async scripts. Async scripts load in the background
and run when ready. The defer and async attributes are ignored if the <script> tag has no src.
fi
fi
fi
In practice, defer is used for scripts that need the whole DOM and/or their relative execution order is
important. async is used for independent scripts like ads. Their relative execution order does not matter.
Repaint and Re ow
Repaint occurs when changes are made to the appearance of the elements that change the visibility but do
not affect the layout.
• Visibility
• Background color
• Outline
Re ow means re-calculating the positions and geometries of elements in the document. Re ow happens
when changes are made to the elements that affect the layout of the partial or whole page.
• Resizing the window
• Changing the font
• Adding or removing a stylesheet
• Content changes, such as a user typing text in an input box
Example:
A DOM tree is made up of individual components called nodes. The main node, from which every other
node springs, is called the document node. The node under the document node is the root element node. The
DOM has several different types of nodes:
• Document node: At the top of the hierarchy is the document node, representing the entire document.
• Element nodes: HTML elements like <div>, <p>, <h1>, etc., are represented as element nodes in the
DOM.
• Attribute nodes: Attributes of elements are represented as attribute nodes.
• Text nodes: The actual text content within elements is represented as text nodes.
• Comment nodes: The HTML comments in a document.
Some key points about the tree:
• Every node, except the root node, has one parent.
• Each node may have any number of children.
• Nodes with the same parent are siblings.
fl
fl
fl
Parent, child, and sibling relationship in an HTML document
<html>
<head>
<title>The HTML Family</title>
</head>
<body>
<section> <! I am a parent of 3 p elements, child of body >
<p>First</p> <! 1st child and sibling of 2 p elements >
<p>Second</p> <! 2nd p child and sibling of 2 p elements >
<p>Third</p> <! 3rd p child and sibling of 2 p elements >
</section>
</body>
</html>
The HTML DOM also provides a couple of keywords for navigating nodes using their positions relative to
their siblings or parents.
• The parentNode property returns the parent node of an element or node.
• The childNodes property returns a collection (list) of an elements’s child nodes.
• The nextSibling property returns the next node on the same tree level.
• The previousSibling property returns the previous node on the same tree level.
• The rstChild property returns the rst child node of a node.
• The lastChild property returns the last child node of a node.
Example:
Complex structures can be created and manipulated within the DOM by using properties and methods for
working with HTML documents. Listed below are a few of them:
• Cookie: This property gets or sets the name/value pairs of cookies in the document
• Doctype: This property gets the Document Type Declaration associated with the document
• documentElement: This property gets the element that is the root of the document
• links: This property gets a collection of all and elements in the document that contain the href
attribute
• createElement(): Creates a new element node
• addEventListener(): Assigns an event handler to the document
• appendChild(): Inserts a new child node to the element (as a last child node)
• cloneNode(): Clones the element
• click(): Replicates a mouse click on the element
fi
‐
‐
‐
‐
‐
‐
‐
‐
‐
fi
‐
‐
‐
‐
‐
‐
‐
‐
Example:
Event Handling
Events are the things that happen within the browser (such as page loading) and things the user does (such as
clicking, pressing keys on the keyboard, and moving the mouse). The HTML DOM gives JavaScript the
ability to identify and respond to events in a web browser. When JavaScript does something in response to
these events, it is called event handling. The addEventListener method listens for events on any DOM node
and triggers actions based on those events.
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever
the speci ed event is delivered to the target.
Example:
Event delegation is a useful pattern that allows you to write cleaner code and create fewer event listeners
with similar logic. Capturing and bubbling allow us to implement one of the most powerful event handling
patterns called event delegation. This is useful for dynamically generated content. The idea is that if we have
a lot of elements handled in a similar way, then instead of assigning a handler to each of them, we put a
single handler on their common ancestor.
Manipulating Style Example:
Self-Study
• Study the topics covered in this document in detail from the links shared in the references.
• Practice codes using DOM
Event-driven programming is a method of programming in which the ow of the program is determined by
events that occur. An event is a noti cation that something speci c has occurred in the browser. Following
are a few events:
• abort: The loading of a le is aborted
• change: An element value has changed since losing and regaining focus
• click: A mouse has been clicked on an element
• dbclick: A mouse has been clicked twice on an element
• keydown: A key is pressed down
• keyup: A key is released after being pressed
• mousewheel: A wheel button of a mouse is rotated
• submit: A form is submitted
• blur: An element has gone out of focus
• scroll: The document or an element has been scrolled
• unload: The document or included le is being unloaded
Inline Event Handler
The rst system for handling events was introduced along with the rst versions of JavaScript. The inline
event handler attributes are formed by adding the pre x to an event. To use them, add the event attribute to
an HTML element. When the speci ed event occurs, the JavaScript within the value of the attribute will be
performed.
Example:
<a href="homepage.html" onclick="alert('Home page!');"> Home </a>
If you put this markup into an HTML document and click the link, you see an alert window with the words
“Home page!”.
HTML4 de ned a collection of events that browsers implement. JavaScript can deal with these events.
These events are associated with HTML tag attributes. Tag attributes are used to connect the events to
handler.
The addEventListener method listens for events on any DOM node and triggers actions based on those
events. When the function speci ed as an action for the event runs, it automatically receives a single
argument, the Event object.
Example:
When elements are nested, it is important to know which one will happen rst. The outer element is
clickable, but so is the inner element. When you click on the inner element, should the event attached to the
outer element happen rst, or should the event attached to the inner element happen rst?
The most common way for events to be handled in a situation like this is called bubbling up. Events on the
inside-most element happen rst and then bubble up to the outermost elements. To use the bubble-up
method, set the last argument of the addEventListener() method to false, which is also the default value. The
other way to handle this scenario is called the capture method. In capture mode, the outermost events
happen rst, and the innermost events happen last.
Example:
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
Use preventDefault method of the event object to prevent the default behavior associated with an event; for
example, preventing the default action of a form submission.
Event delegation in JavaScript is a pattern that ef ciently handles events. Events can be added to a parent
element instead of adding to every single element. It refers to the process of using event propagation
(bubbling) to handle events at a higher level in the DOM than the element on which the event originated.
Cookies are data, stored in small text les, on your computer. JavaScript can create, read, and delete cookies
with the document.cookie property. You can also add an expiry date. By default, the cookie is deleted when
the browser is closed.
Example:
document.cookie = "username=Tine Jones; expires=Thu, 18 Jan 2024 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie
belongs to the current page.
Example:
document.cookie = "username=Tina Jones; expires=Thu, 18 Jan 2024 12:00:00 UTC;
path=/";
First, we create a function that stores the name of the visitor in a cookie variable. The parameters of the
function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days
until the cookie should expire (exdays).
Example:
We can create a function that returns the value of a speci ed cookie. It takes the cookiename as parameter
(cname).
Example:
fi
fi
fi
Deleting a cookie is very simple. You do not have to specify a cookie value when you delete a cookie. Just
set the expires parameter to a past date:
Example:
Self-Study
• Study the topics covered in this document in detail from the links shared in the references.
• Practice codes using event handling and cookies
JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive.
JavaScript can be connected to the objects of its environment to provide programmatic control over them.
JavaScript is case-sensitive and uses the Unicode character set.
Variables
Variables are symbolic names for values used in an application. The names of variables, called identi ers,
conform to certain rules. A JavaScript identi er usually starts with a letter, underscore (_), or dollar sign ($).
Subsequent characters can also be digits (0–9). Because JavaScript is case-sensitive, letters include the
characters A through Z (uppercase) as well as a through z (lowercase).
Let x = 2;
In a statement like let x = 2, the let x part is called a declaration, and the = 2 part is called an initializer. A
variable may belong to one of the following scopes:
• Global scope: The default scope for all code running in script mode.
• Module scope: The scope for code running in module mode.
• Function scope: The scope created with a function.
In addition, variables declared with let or const can belong to an additional scope:
• Block scope: The scope created with a pair of curly braces (a block).
You can create a read-only, named constant with the const keyword. A constant cannot change value through
assignment or be re-declared while the script is running.
const a = 10;
Data Types
• Seven primitive datatypes are as follows:
• Boolean: A variable can have a value as true or false.
• Null: A special keyword used to denote a null value.
• Unde ned: Can be used when the value is not de ned.
• Number: It represents an integer or a oating-point number, for example, 2 or 3.59.
• BigInt: An integer with arbitrary precision, for example, 9007199254740992n.
• String: A sequence of characters that represent a text value, for example, "Hello".
• Symbol: A data type whose instances are unique and immutable.
Statements
The most basic statement is a block statement, which is used to group statements. The block is delimited by
a pair of curly braces:
{
statement1;
statement2;
// …
statementN;
}
A conditional statement is a set of commands that executes if a speci ed condition is true. JavaScript
supports two conditional statements: if...else and switch.
if statement will execute a statement if a logical condition is true, and the optional else clause can be used to
execute a statement if the condition is false.
if (condition) {
statement1;
} else {
statement2;
}
In case, we need to check for multiple conditions, we can use multi-level if. In this case, only the rst logical
condition, which evaluates to true, will be executed.
if (condition1) {
fi
fl
fi
fi
fi
fi
fi
statement1;
} else if (condition2) {
statement2;
} else if (conditionN) {
statementN;
} else {
statementLast;
}
A switch statement allows a program to evaluate an expression and attempt to match the expression's value
to a case label. If a match is found, the program executes the associated statement.
switch (expression) {
case label1:
statements1;
break;
case label2:
statements2;
break;
// …
default:
statementsDefault;
}
The optional break statement associated with each case clause to ensure that the program breaks out of
switch once the matched case is executed, and then continues execution from the statement following
switch. If break is missing, the program executes the matched case and the following cases.
Loops offer a quick and easy way to do something repeatedly.
A “for” loop repeats until a speci ed condition evaluates to false.
for (initialization; condition; afterthought)
statement
The “do...while” statement repeats until a speci ed condition evaluates to false.
do
statement
while (condition);
A “while” statement executes its statements as long as a speci ed condition evaluates to true.
while (condition)
statement
Self-Study
• Study the topics covered in this document in detail from the links shared in the references.
• Practice questions for loops and conditional statements.
Objects are variables too. But objects can hold multiple values. The values are written as name: value pairs.
You can create an object using an object initializer.
const obj = {
property1: value1, // property name may be an identi er
fi
fi
fi
fi
2: value2, // or a number
"property n": value3, // or a string
};
var person = { rstName:"Kala",
lastName:"Tiwari",
age:40,
eyeColor:"black"}
You can access a property of an object by its property name.
objectName.property // person.age
or
objectName["property"] // person["age"]
We can also use constructor functions. For this, rst de ne the object type by writing a constructor function,
then create an instance of the object with new.
function Person(name) {
this.name = name;
this.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
}
let person1 = new Person('Bob');
let person2 = new Person('Sarah');
In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same
properties. Only comparing the same object reference with itself yields true.
Example:
const name1 = { name: "Rita" };
const name2 = { name: "Rita" };
name1 == name2; // return false
name1 === name2; // return false
The temporary objects created when you access a property/methods of a string, number, or Boolean are
known as wrapper objects. JavaScript allows us to work with primitives (strings, numbers, etc.) as if they
were objects using these wrapper objects.
var name = 'Tina';
console.log(name.length);//prints 4
console.log(name.toUpperCase()); //prints TINA
typeof 'Tina' //string
Javascript detects that you are trying to access a property of a string primitive. It creates a wrapper object
String to wrap the original string primitive. It accesses the length and toUpperCase on the wrapper object
instead of the original primitive. It discards the wrapper object, frees the memory, and continues.
In JavaScript, an object can inherit properties of another object. The object from where the properties are
inherited is called the prototype. When we try to access a property of an object, the property is not only
searched in the object itself. It is also searched in the prototype of the object, in the prototype of the
prototype, and so on—until a property is found that matches the name or the end of the prototype chain is
reached.
Example:
Example:
let o = {}; // o inherits object methods from Object.prototype
o.x = 1; // and it now has an own property x.
let p = Object.create(o); // p inherits properties from o and Object.prototype
p.y = 2; // and has an own property y.
let q = Object.create(p); // q inherits properties from p, o, and...
q.z = 3; // ...Object.prototype and has an own property z.
let f = q.toString(); // toString is inherited from Object.prototype
fi
fi
fi
q.x + q.y // => 3; x and y are inherited from o and p
In JavaScript, classes are mainly an abstraction over the existing prototypical inheritance mechanism—all
patterns are convertible to prototype-based inheritance. Classes are usually created with class declarations.
Syntax:
class MyClass {
// class body...
}
Example:
class MyClass {
// Constructor
constructor() {
// Constructor body
}
// Instance eld
myField = "try";
// Instance method
myMethod() {
// myMethod body
}
// Static eld
static myStaticField = "test";
// Static method
static myStaticMethod() {
// myStaticMethod body
}
// Static block
static {
// Static initialization code
}
// Fields, methods, static elds, and static methods all have
// "private" forms
#myPrivateField = "test";
}
Arrays
An array is a special variable, which can hold more than one value. Using an array literal is the easiest way
to create a JavaScript Array.
const array_name = [item1, item2, ...];
Examples:
var empty = []; // An array with no elements
var primes = [2, 3, 5, 7, 11]; // An array with 5 numeric elements
var misc = [ 1.1, true, "a", ]; // 3 elements of various types + trailing comma
var a = new Array(10);
var a = new Array(5, 4, 3, 2, 1, "testing, testing");
Few of the Methods and properties for arrays:
• The length property returns the length (size) of an array.
• Method toString() converts an array to a string of (comma-separated) array values.
• at() method returns an indexed element from an array.
• join() method also joins all array elements into a string.
• pop() method removes the last element from an array.
• push() method adds a new element to an array (at the end).
• shift() method removes the rst array element and "shifts" all other elements to a lower index.
• unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements.
fi
fi
fi
fi
• concat() method creates a new array by merging (concatenating) existing arrays.
• copyWithin() method copies array elements to another position in an array.
• Splice() method adds new items to an array.
• slice() method slices out a piece of an array.
Functions
A JavaScript function is a block of code designed to perform a particular task. The code inside the function
will execute when "something" invokes (calls) the function and when we reach a return statement, the
function will stop executing.
Syntax:
function myFunction(p1, p2,….) { //function with parameters
//statements
}
Example:
function sum(a, b) { //function de nition
var c = a + b;
return c;
}
sum(1); //function call
Self-Study
• Study the topics covered in this document in detail from the links shared in the references.
• Practice code using objects, object inheritance, and arrays and functions.
CSS oats were initially designed for text wrapping around images, but their versatility soon made them a
crucial component in web layout design. By using the oat property, elements can be moved to one side of
their containing element, allowing subsequent elements to ow around them.
The oat property allows you to take an element in normal ow and place it as far to the left or right of the
containing element as possible.
This is particularly useful for creating multi-column layouts and arranging content in a visually appealing
manner.
The element with the oat property is removed from the normal ow and all the other elements will oat
and display beside it; therefore, if we want to stop the following element from oating or moving up, we
need to clear it and it is achieved with the clear property.
The clear property accepts the following values:
• left: Clear items oated to the left.
• right: Clear items oated to the right.
• both: Clear any oated items, left or right.
Consider the following code example for a simple two-column layout using oats and clear:
The HTML and CSS code below demonstrates a simple webpage layout using CSS oat and clear
techniques.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Floating Layout</title>
<link rel="stylesheet" href="style.css" >
fl
fl
fl
fl
fl
fl
fi
fl
fl
fl
fl
fl
fl
fl
fl
</head>
… </div>
<div class="column column2">
<h2>Column 2</h2>
<p>This is the content of the second column. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Mauris eget venenatis ligula. Ut lacinia at dolor vitae pulvinar. Aliquam pretium
dignissim eros. Integer faucibus, dui non aliquet bibendum, lectus orci lobortis odio, ornare
porttitor est tellus eget velit. Nulla eros elite malesuada id neque vel, viverra vehicula neque.
Nullam auctor turpis non leo iaculis nibus. Quisque blandit arcu venenatis libero tempor, ac
pulvinar ligula dapibus.
</p>
</div>
<div class="clear"></div>
<div id="box4" class="box">
<h3>Footer</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget venenatis ligula.
Ut lacinia at
dolor vitae pulvinar. .</p>
</div>
</div>
</body>
</html>
Style.CSS
.container {
width: 80%;
margin: 0 auto;
}
.column1 {
oat: left;
width: 20%;
box-sizing: border-box;
padding: 20px;
border: 1px solid black;
}
.column2 {
oat: left;
width: 80%;
box-sizing: border-box;
padding: 20px;
border: 1px solid black;
}
.box {
border: 1px solid black;
background-color: cadetblue;
text-align: justify;
padding: 10px;
margin-bottom: 10px;
}
fl
fl
fi
.clear {
clear: both;
}
Let's break down the code to understand how the layout is achieved:
1) Container: The .container class sets the width to 80% of the viewport and centers it with margin: 0
auto;.
2) Columns:Two columns, .column1 and .column2, are created using CSS oat.
3) .column1 is oated to the left with a width of 20%, while .column2 is oated to the left with a width
of 80%.
4) Both columns have box-sizing set to border-box to include padding and border in the de ned width.
Borders and padding are added for styling, creating a visual separation between the columns.
5) Clear x: The .clear class is used for clear x, ensuring that the container properly wraps around the
oated columns. This prevents layout issues that may arise due to oating elements.
The code results in a webpage layout with a header (box1), two columns (column1 and column2), and a
footer (box4). The use of CSS oat allows the columns to sit side by side, and the clear x ensures proper
wrapping the rest of the content(footer) within the container.
This layout is a basic example of how CSS oat and clear x can be employed to structure a webpage. While
these techniques are effective, modern layout approaches like Flexbox and CSS Grid are now widely used
for more complex and responsive designs.
fl
fi
fl
fl
fl
fi
fi
fl
fl
fl
fi
fi
Understanding Flexbox
Flexbox is designed to provide a consistent way to lay out and distribute space among items in a container,
even when the size of the items is unknown or dynamic. The main idea behind Flexbox is to give the
container the ability to alter its items' width, height, and order to best ll the available space and prevent
over ow or extra white space.
Flex Container and Flex Items
Flex Container: The parent element containing ex items. Applying display: ex; or display: inline- ex; to
an element turns it into a ex container.
Flex Items: The children elements within a ex container are referred to as ex items.
Main Axis and Cross Axis
Main Axis: The primary axis along which ex items are laid out. It is determined by the ex-direction
property.
Cross Axis: The perpendicular axis to the main axis, in uencing alignment through properties like align-
items and align-self.
main-start and main-end: The ex items are placed within the container starting from main-start and going to
the main-end.
cross-start and cross-end: Flex lines are lled with items and placed into the container starting on the cross-
start side of the ex container and going toward the cross-end side.
center: Items are aligned and centered along the main axis line.
fl
fl
fl
fl
fl
justify-content: center;
space-around: Items are evenly distributed in the line with equal space around them.
justify-content:space-around;
space-between: Items are evenly distributed in the line; The rst item starts immediately after the main start
and the last item is near the main end. The space is distributed between all the other items
justify-content:space-between;
space-evenly: Items are distributed such that the spacing between any two items is equal. Also the space to
the edges for the rst item and last item is equal.
justify-content:space-evenly;
align-items
This property is used to align items along the cross-axis. align-items applies to all items within the container.
The ex items are laid out along the cross-axis on the current line.
.container {
align-items: stretch | ex-start | ex-end | center ;
}
ex-start: Items are placed at the start of the cross-axis.
FLEX Properties
order
By default, ex items are laid out in the source order. However, the order property controls the order in
which they appear in the ex container.
ex-grow
This property de nes the ability of a ex item to grow if necessary. It accepts a unitless value that serves as a
proportion. It dictates what amount of the available space inside the ex container the item should take up. If
all items have ex-grow set to 1, the remaining space in the container will be distributed equally to all
children. If one of the children has a value greater than 1, that particular item would take up more space
depending on the ex-grow value. The ex-grow property de nes the rate at which the item size should
grow in relation to other elements.
ex-shrink: This de nes the ability for a ex item to shrink if necessary. This is the reverse of ex-grow.
ex-basis:This de nes the default size of an element before the remaining space is distributed. It can be a
length (e.g., 10%, 2rem, etc.) or a keyword.
FLEX Property
The ex property is a shorthand for ex-grow, ex-shrink, and ex-basis. It speci es how a ex item will
grow or shrink to t the available space:
.item {
ex: 2 1 50%;
/* ex-grow: 2; ex-shrink: 1; ex-basis: 50%; */
}
PracticalUse Cases
1. Responsive Design with Flexbox
Leveraging Flexbox properties to create responsive designs that adapt to different screen sizes.
.container {
ex-direction: column;
/* Stack items vertically on small screens */
}
@media screen and (min-width: 600px) {
.container {
ex-direction: row;
/* Arrange items in a row on larger screens */
}
}
2. Flexbox for Navigation Menus
fl
fl
fl
fl
fl
fl
fl
fl
fl
fl
fi
fl
fl
fi
fi
fi
fl
fi
fl
fl
fl
fl
fl
fl
fi
fl
fl
fi
fl
fl
Designing navigation menus with Flexbox for easy alignment and responsiveness.
.nav-container {
display: ex;
justify-content: space-around;
}
3. Flexbox for Card Layouts: Utilizing Flexbox to create card-based layouts.
Conclusion
CSS Flexbox is a powerful layout model that simpli es the process of creating exible and responsive
designs. Its intuitive and easy-to-understand properties make it an essential tool for web developers striving
to build modern and dynamic user interfaces. By mastering the concepts, developers can leverage Flexbox to
achieve complex layouts with less code and greater control over the visual presentation of their web pages.
Whether used independently or in conjunction with other layout models, Flexbox is a valuable addition to
the web developer's toolkit.
fl
fi
fl
Understanding CSS Grid
CSS grid layout, commonly known as CSS grid, is a two-dimensional layout system for the web that enables
the creation of complex grid-based layouts. It provides a powerful set of tools for de ning both the rows and
columns of an element, allowing for precise control over the placement and sizing of its children.
Grid Container and Grid Items:
Grid Container: The parent element that holds the grid items. Applying display: grid; or display: inline-grid;
to an element transforms it into a grid container.
Grid Items: The children elements within a grid container are referred to as grid items. These items are
placed within the de ned grid rows and columns.
Grid Lines and Grid Tracks:
Grid Lines: The horizontal and vertical lines that divide the grid into rows and columns are called grid lines.
They are referenced by their line numbers. In the below diagram, the line numbers are displayed in yellow
notes.
Grid Tracks: It is the space between two adjacent grid lines. Grid tracks can be rows or columns, forming the
structure of the grid. In the diagram below, the size of the tracks is displayed in yellow notes.
De ning a Grid:
The display property with a value of grid or is used to de ne an element as a grid container.
.container {
display: grid;
}
The above property de nes a single-column grid. You can de ne rows and columns on grid with the grid-
template-rows and grid-template-columns properties. These de ne grid tracks.
grid-template-rows and grid-template-columns
These properties de ne the number and size of the grid rows and columns. Sizes can be speci ed in pixels,
percentages, or using the fr unit (fractional unit).
Example: A grid with two columns (100px, 200px)
.container {
/* Two rows with speci c heights */
grid-template-rows: 100px 200px;
}
In addition to creating grids using lengths and percentages, we can use the fr unit to size grid rows and
columns exibly. This unit represents one fraction of the available space in the grid container.
Example: A grid with two columns with a 1:2 ratio
.container {
grid-template-columns: 1fr 2fr;
}
The explicit grid is the one created using grid-template-columns or grid-template-rows. The implicit grid is
created when content is placed. By default, tracks created in the implicit grid are auto-sized, which, in
fi
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
general, means that they are large enough to t their content. Grid tracks in an implicit track can be given a
size using the grid-auto-rows and grid-auto-columns properties.
Line-based placement:
Line-based placement in CSS grid refers to positioning grid items based on the line numbers of the grid
tracks (rows or columns). This approach allows for precise control over the placement of items within the
grid by specifying where they start and end in terms of grid lines.
grid-row and grid-column properties:
The grid-row and grid-column properties are used to position grid items based on the line numbers of the
grid tracks.
Example 1:
.item {
grid-row: 2 / 4;
grid-column: 1 / span 2;
}
The item starts at the second-row line and ends at the fourth-row line. It starts at the rst column line and
spans two columns.
Example 2:
In this example, a grid of four columns is de ned. The header starts from line 1 and extends up to line 4.
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-gap: 20px;
}
header {
grid-column: 1 / 4;
grid-row: 1;
background-color: lightblue;
color: red;
}
In the image below, you can see the line numbers and the placement of the header between lines 1 to 4.
Grid Areas:
In CSS grid layout, a grid area refers to the rectangular space enclosed by four grid lines within the grid
container. It is the region where grid items are placed, and it is de ned by specifying the names or indices of
the starting and ending lines for both rows and columns.
Named regions of the grid are created by combining multiple cells. Grid areas make it easy to de ne and
place items within the layout.
De ning Grid Template Areas
fi
fi
fi
fi
fi
fi
CSS grid template areas allow developers to name speci c regions within a grid and assign those names to
grid items. This approach is particularly bene cial when dealing with intricate layouts that involve multiple
grid items and the need for clear organization.
Grid template areas are de ned in the grid-template-areas property of the grid container. The property value
consists of strings enclosed in quotation marks, representing the named areas of the grid. Each string
corresponds to a row in the grid, and the areas within that row are de ned by space-separated names.
.container {
display: grid;
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
}
In this example:
The grid has three rows: header, sidebar-content, and footer.
Each row has four areas: header, sidebar, content, and footer.
Assigning Areas to Grid Items
Grid items are assigned to the named areas using the grid-area property. The value of grid-area corresponds
to the name of the area de ned in grid-template-areas. This ensures that each grid item is placed in its
designated area within the grid.
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.content {
grid-area: content;
}
.footer {
grid-area: footer;
}
In the below image, the grid area names are highlighted in the yellow notes. For example, the header spans
all three columns, the sidebar occupies only the rst column, as mentioned in the grid-template-areas
property.
Practical Implementation
1) Building responsive grids: Creating responsive grids that adapt to different screen sizes is a common
use case for CSS grid.
2) CSS grid is excellent for designing card-based layouts with consistent spacing and alignment.
3) CSS grid allows for the creation of multi-section page layouts with ease.
Best Practices
fi
fi
fi
fi
fi
fi
• Embrace exibility: Leverage the exibility of CSS grid to create versatile layouts that adapt to
various content and screen sizes.
• Combine grid with other layout techniques: CSS grid can be combined with other layout methods,
such as Flexbox or traditional positioning, for more intricate and feature-rich designs.
• Optimize for accessibility: Ensure that the grid layout is accessible by using semantic HTML and
providing alternative text for images.
Conclusion
CSS grid is a powerful layout system that brings a new level of exibility and control to web design. With
its intuitive syntax and comprehensive set of features, developers can easily create complex and responsive
layouts without relying on excessive markup or CSS hacks. Whether used for simple card layouts, multi-
section pages, or intricate responsive designs, a CSS grid is a valuable tool that empowers developers to
build modern and visually stunning websites.
fl
fl
fl
Media queries are CSS rules that allow developers to apply styles based on characteristics of the device,
such as its screen width, height, or resolution. They play a crucial role in the implementation of responsive
web design, providing a way to tailor the presentation of content to different devices and viewport sizes.
Syntax of Media Queries
The syntax of a media query is straightforward, typically consisting of a media type and one or more
expressions that check conditions such as width, height, or orientation.
It consists of:
• A media type tells the browser what kind of media this code is for (e.g., print, or screen). The
possible types of media you can specify are:
◦ all
◦ print
◦ screen
◦ speech
• A media expression, a rule, or a test that must be passed for the contained CSS to be applied.
• A set of CSS rules that will be applied if the test passes and the media type is correct.
Example:
@media screen and (max-width: 768px) {
/* Styles for screens with a maximum width of 768 pixels */
body {
font-size: 16px;
}
}
In this example:
• @media indicates the start of a media query.
• screen is the media type, specifying that the styles apply to devices with screens.
• (max-width: 768px) is the expression, applying styles only when the viewport width is 768 pixels or
less.
Use Cases of Media Queries
1. Responsive layouts: One of the primary use cases of media queries is creating responsive layouts. By
adjusting the layout, font sizes, and spacing based on the device's screen size, websites can provide an
optimal viewing experience for users.
@media screen and (max-width: 600px) {
/* Adjust styles for smaller screens */
.container {
padding: 10px;
}
.menu {
display: none;
}
}
2. Image optimization: Media queries can be used to load different images or image sizes based on the
user's device. This is particularly useful for improving page loading times and reducing bandwidth usage on
mobile devices.
@media screen and (max-width: 480px) {
/* Load smaller images for smaller screens */
.header {
background-image: url('small-header-image.jpg');
}
}
3. Print styles: Media queries allow developers to de ne styles speci cally for printed documents,
ensuring that the content is well-formatted when users decide to print a webpage.
@media print {
fi
fi
/* Styles for printed documents */
.navigation, .sidebar {
display: none;
}
}
4. Mobile- rst approach: A common practice in responsive web design is adopting a mobile- rst
approach. This involves designing and developing the mobile version of a website rst, then using media
queries to enhance the layout for larger screens. This approach ensures that the core content and
functionality are optimized for mobile devices.
/* Styles for mobile devices (default) */
body {
font-size: 14px;
}
/* Media query for larger screens */
@media screen and (min-width: 768px) {
body {
font-size: 16px;
}
}
Conclusion
Media queries are indispensable tools for web developers seeking to create adaptive and user-friendly
websites. As users access the web from an ever-expanding array of devices, the importance of responsive
design cannot be overstated. Media queries empower developers to tailor their designs to various screen
sizes and characteristics, providing a consistent and enjoyable experience for users across the digital
landscape. As technology continues to advance, the role of media queries will remain pivotal in shaping the
future of web design, ensuring that websites are not only visually appealing but also accessible to users
regardless of the device they choose.
fi
fi
fi
Cascading Style Sheets (CSS) is a rule-based language that empowers web designers to de ne styles for
speci c elements on a webpage.
CSS Rules: CSS rules consist of selectors and declarations, specifying how particular elements or groups of
elements should be styled on a webpage.
Components of a CSS Rule:
• Selector: Identi es the HTML element to be styled (e.g., paragraph).
• Declaration Block: Enclosed in curly braces {}, contains one or more property-value pairs.
CSS Declarations:
Declarations within a rule consist of property and value pairs, de ning speci c stylistic features.
Property: Human-readable identi er indicating the stylistic feature to be modi ed (e.g., color).
Value: Speci es how to style the property (e.g., blue). Depending on the property, values may include size
units, font names, or functions.
Property and value are separated by a colon (:).
CSS properties and values are case-insensitive.
CSS Declaration Blocks:
Declaration blocks are enclosed within curly braces and consist of one or more CSS declarations.
Multiple CSS rules are written sequentially in a stylesheet.
Examples:
p{
color: blue;
width: 200px;
border: 1px solid black;
}
h1 {
color: red;
text-align: center;
}
There are three different ways to apply styles to a webpage. They are external stylesheet, internal styles, and
inline styles.
1. External Stylesheet:
An external stylesheet involves writing CSS rules in a separate le with a .css extension. These rules are
linked to an HTML document using the <link> element in the <head> section.
Key points:
• <link> element speci es the stylesheet using the rel attribute.
• The location of the stylesheet is de ned by the href attribute, pointing to the CSS le.
• External stylesheets facilitate a clear separation of structure and styling, promoting reusability across
multiple pages.
2. Internal Stylesheet:
Internal stylesheets house CSS rules within an HTML document, enclosed in a <style> element within the
<head> section. These rules exclusively apply to the speci c HTML page.
Key points:
• Suitable for situations where modifying the original CSS le is restricted.
• Inef ciencies arise when maintaining websites with multiple pages due to each page having its
internal stylesheet.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
3. Inline Styles:
Inline styles are CSS declarations applied to a speci c HTML element within a style attribute. These styles
only affect the element they are applied to and cannot be referenced elsewhere in the document.
Example:
<h1 style="color:blue; border:1px solid black;">Hello World!</h1>
Key points:
• Least ef cient for maintenance, as changes may require multiple edits within a single page.
• Mixing presentational code with HTML content makes it harder to read and understand.
• Use cases include content management systems limiting HTML body edits.
Browser Rendering Process:
Understanding how browsers render HTML content and apply styles involves a multi-step process.
1. Loading HTML Content:
• Browser loads HTML content.
• Converts HTML into a Document Object Model (DOM) in the computer's memory.
2. Creating DOM:
• DOM has a hierarchical structure resembling a tree.
• Nodes represent elements, attributes, and text, de ning relationships in the DOM.
3. Applying CSS Rules:
• Browser parses associated CSS and creates a CSS Object Model (CSSOM).
• Combines DOM and CSSOM to form a render tree, determining the visual display.
4. Rendering on Screen:
• The render tree is used to render the visual display of the page on the screen.
Conclusion:
With a comprehensive understanding of the components of a CSS rule, the three CSS application methods,
and the browser rendering process, we are well-equipped to create stylish and well-structured HTML web
pages.
The CSS Cascade is a vital aspect of CSS that determines which CSS declarations take precedence over
others. It is essentially an algorithm that web browsers use to resolve competing CSS declarations.
Every CSS rule or declaration enters the CSS Cascade, which then decides whether it will become the nal
style or not.
The following are the order and steps that are followed to resolve con icts and select the nal style.
Importance: The rst factor that is looked at is the importance. There are four basic types of rules, and they
are listed below in the other of their importance.
1. transition: Rules that apply to an active transition take the utmost importance.
2. !important: When we add !important to the end of our declaration, it becomes an important rule.
3. animation: Rules that apply to an active animation.
4. normal: This level represents all the other rules.
Origin:
The second factor to be looked at in the cascade algorithm is the Origin.
fi
fi
fl
fi
fi
fi
fi
fi
There are three types of origin for CSS declarations: user-agent stylesheets, author stylesheets, and user
stylesheets. User-agent stylesheets are the default styles applied by browsers to any document. Author
stylesheets are the most common type of stylesheet created by web developers, who de ne the styles for the
document using one or more linked or imported stylesheets, <style> blocks, and inline styles de ned with
the style attribute. In addition, users can choose to override styles using a custom user stylesheet to tailor
their experience. These user styles can be con gured directly or added via browser extensions, depending on
the user agent.
The precedence of the various origins is, in descending order, is as follows.
• Transition declarations [css-transitions-1]
• Important user agent declarations
• Important user declarations
• Important author declarations
• Animation declarations [css-animations-1]
• Normal author declarations
• Normal user declarations
• Normal user agent declarations
Declarations from origins earlier in this list win over declarations from later origins.
Speci city:
The third factor that is looked at is Speci city. If two styles from the same origin precedence, con ict, then
Speci city is considered.
"Speci city" refers to a calculation that determines the most speci c CSS selector, by assigning weights or
scores to each selector type. Each selector is worth a certain number of points which adds up to give the nal
speci city score.
A universal selector (*) has no speci city and gets 0 points.
An element (type) or pseudo-element selector gets 1 point of speci city.
A class, pseudo-class, or attribute selector gets 10 points of speci city.
An ID selector gets 100 points of speci city.
CSS applied directly to the style attribute of the HTML element, gets a speci city score of 1,000 points.
Example:
div #myid
{
color:red;
}
div is an element selector, so gets 1 point
#myid is an id selector, so gets 100 points
So the speci city of this selector div #myid is 0101
The rule with the higher speci city is applied. When two rules have the same speci city, the next factor to
be looked is the source order.
Source order
The last factor to be looked at is the position of the CSS rule or the source order.
Source order only matters when the speci city weight of the rules is the same.
The CSS rules from all sources, such as external, internal, and imported, are all ordered as they appear in the
source code. The last declaration in document order wins.
The output of the cascade is a sorted list of declared values for each property on each element.
The Cascade algorithm resolved only style properties that con ict, but the other style properties are merged.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
fi
fi
fi
fi
fi
fl
fi
When designing web pages, the browser's rendering engine employs the CSS basic box model as a
fundamental framework. The browser's rendering engine visualizes each HTML element as a rectangular
box. This model represents each HTML element as a rectangular box, dictating its size, position, and various
properties such as color, background, and border. The box model standardizes layout design by governing
box size, position, and properties.
The CSS Box Model has four key components—content area, padding area, border area, and margin area—
which collectively de ne the structure of these rectangular boxes.
Quotations:
Blockquotes (<blockquote>): Use this element to mark up a block of content quoted from an external
source. When quoting a block of content from an external source, whether it is a paragraph, multiple
paragraphs, or a list, the <blockquote> element can be used. This element signals that the content is a
quotation, and for transparency, a URL pointing to the source should be included within the cite attribute.
However, note that browsers and screen readers often do not display the content of the cite attribute. If you
want users to access the source, consider providing it in the text via a link or another suitable method.
Example:
<blockquote cite="https://www.example.com/inspirational-quote">
"The only way to do great work is to love what you do."
<p>— Steve Jobs</p>
</blockquote>
Abbreviations:
The <abbr> element is commonly used to mark up abbreviations or acronyms. For clarity, include the full
expansion of the term in plain text on its rst use, alongside the <abbr> element.
If adding the full expansion alongside the abbreviation seems impractical, especially for shorter terms, you
can use the title attribute to provide the full expansion.
Example:
Contact Information:
Address (<address>): The <address> element is designed for marking up contact details. It can wrap around
simple contact information or more complex structures. It can enclose contact details like name, address,
phone number, and email within this element.
Example:
<address>
<p>John Doe</p>
<p>123 Main Street</p>
<p>Anytown, CA 12345</p>
<p>Phone: <a href="tel:555-123-4567">555-123-4567</a></p>
<p>Email: <a href="mailto:johndoe@example.com">johndoe@example.com</
a></p>
</address>
<pre>
<code>
function greet(name) {
console.log("Hello, " + name + "!");
}
</code>
</pre>
Introduction to Semantics
In HTML, semantic elements are specially designed to provide clear meaning and purpose to both the
developer and the browser, ensuring that the purpose and content of the HTML document are conveyed with
utmost clarity and precision.
Semantic versus Non-Semantic Elements
Semantic elements, such as “<h1>,” “<table>,” and “< gure>,” clearly de ne their content and contribute to
a better understanding of the document’s structure. In contrast, non-semantic elements like “<div>” and
“<span>” convey no inherent meaning about their content.
Semantic Elements in HTML5
The HTML5 version introduced several new semantic elements that offer meaningful ways to structure a
web page:
1. <article>: De nes an independent, self-contained content block suitable for items like forum posts,
blog posts, or newspaper articles.
fi
fi
fi
fi
fi
fi
2. <aside>: Speci es content that is tangentially related to the surrounding content, often used for
sidebars.
3. <details> and <summary>: De ne additional details that the user can choose to view or hide, with a
visible heading provided by <summary>.
4. < gcaption> and < gure>: Group images and their captions together for better structure and
presentation.
5. <footer>: Speci es a footer for a document or section, commonly containing information like the
author, copyright details, or contact information.
6. <header>: Speci es a header for a document or section, often used to contain introductory content.
7. <main>: Speci es the main content of a document, emphasizing the primary content.
8. <mark>: De nes marked or highlighted text within the document.
9. <nav>: De nes a set of navigation links intended for large blocks of navigation.
10. <section>: De nes a thematic grouping of content, typically with a heading, providing a structured
way to organize content.
Accessibility, in the context of technology and the Web, refers to the practice of making information and
services usable for everyone, regardless of their abilities, disabilities, or circumstances. It is about removing
barriers and creating inclusive experiences for all users. The Web Content Accessibility Guidelines (WCAG)
are a set of guidelines that aim to make digital content more accessible to people with disabilities.
These guidelines are divided into four key principles that serve as a roadmap for creating accessible content:
1. Perceivable: This principle focuses on making sure that users can perceive the content in some way.
For instance, the content should be presented in a way that can be seen, heard, or felt, depending on
the user’s abilities.
2. Operable: This principle focuses on giving users control over UI elements, such as buttons, links,
and forms. A user should be able to interact with these elements using various methods, such as a
mouse, keyboard, and voice command.
3. Understandable: This principle focuses on making sure that the content is easy to understand. It
should be presented in a clear and organized way, with simple and concise language that conveys the
intended message.
4. Robust: This principle focuses on developing content using well-established web standards that can
work across different browsers and devices, both now and in the future.
By following these standards, the content can be made accessible to a wider audience, including people with
disabilities.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
A signi cant amount of web content can become accessible if we use the appropriate HyperText Markup
Language elements for their intended purpose at all times.
fi
Protocols help the Internet to function properly. A protocol is simply a standard for enabling the following
between two entities on the network:
• Connection
• Communication
• Data transfer
HyperText Transfer Protocol (HTTP)
HTTP is the underlying protocol of the World Wide Web. Developed by Tim Berners-Lee and his team
between 1989 and 1991, HTTP has gone through many changes that have helped maintain its simplicity
while shaping its exibility. HTTP is a protocol for fetching resources such as HTML documents. It is the
foundation of any data exchange on the Web, and it is a client-server protocol, which means requests are
initiated by the recipient, usually the web browser.
HTTP messages are how data is exchanged between a server and a client. There are two types of messages:
requests sent by the client to trigger an action on the server, and responses, the answer from the server.
In client-server protocols like HTTP, sessions consist of three phases:
• The client establishes a TCP connection (or the appropriate connection if the transport layer is not
TCP).
• The client sends its request and waits for the answer.
• The server processes the request, sending back its answer, providing a status code and appropriate
data.
HyperText Transfer Protocol Secure (HTTPS)
HTTPS is an encrypted version of the HTTP protocol. It uses Transport Layer Security (TLS) to encrypt all
communication between a client and a server. This secure connection allows clients to safely exchange
sensitive data with a server, such as when performing banking activities or online shopping.
HTTPS transmits its data securely by using an encrypted connection. Basically, it uses a public key, which is
then decrypted on the recipient side. The public key is deployed on the server and included in what you
know as a Secure Sockets Layer (SSL) certi cate. The certi cates are cryptographically signed by a
certi cate authority.
Features of HTTP
• Connectionless protocol: The connection between a client and a server exists only for the current
request and response time.
• Stateless: HTTP is a stateless protocol as both the client and server know each other only during the
current request.
The general form of an HTTP request is as follows:
• Request line: It consists of at least three items—a method that tells the server what it should do with
the resource, a path that identi es the resource on the server, and an HTTP version number, showing
the HTTP speci cation to which the client has tried to comply.
• Header elds: They are written on a message to provide the recipient with information about the
sender, the message, and the way in which the sender wants to communicate with the recipient.
• Blank line: To separate the header and the body
• Message body: Actual or encoded message
fi
fi
fi
fl
fi
fi
fi
HTTP Methods:
• GET: The purpose of this method is to retrieve data from the server
• POST: This method sends data to the server for processing
• HEAD: It returns metadata about a resource on the server
• PUT: It is used to completely replace a resource identi ed with a given URL
• DELETE: It removes the resource from the server
• TRACE: It is used for troubleshooting and debugging
• OPTIONS: It returns a listing of which HTTP methods are supported and allowed by the server
HTTP headers let the client and the server pass additional information with an HTTP request or response. An
HTTP header consists of its case-insensitive name followed by a colon (:), then by its value.
Example:
GET /home.html HTTP/1.1
Host: developer.mozilla.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/
20100101 Firefox/50.0
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, de ate, br
Referer: https://developer.mozilla.org/testpage.html
Connection: keep-alive
Upgrade-Insecure-Requests: 1
The general form of an HTTP response is:
• Status line: The HTTP version number, showing the HTTP speci cation to which the server has tried
to make the message comply, status code, which is a three-digit number indicating the result of the
request, and reason phrase, which is human-readable text that summarizes the meaning of the status
code.
• Response header elds: It contains information that a client can use to nd out more about the
response and the server that sent it.
• Blank line: It separates the header from the body
• Response body: It contains either the resource requested by the client or some information about the
status of the action requested by the client.
fi
fl
fi
fi
fi
HTTP Response Codes
Listed below are a few of the response codes:
100 Continue: This interim response indicates that the client should continue the request or ignore the
response if the request is already nished.
200 OK: The request succeeded.
302 Found: This response code means that the URI of the requested resource has been changed temporarily.
304 Not Modi ed: This is used for caching purposes.
401 Unauthorized: Semantically, this response means “unauthenticated.”
408 Request Timeout: This response is sent on an idle connection by some servers, even without any
previous request by the client.
502 Bad Gateway: This error response means that the server, while working as a gateway to get a response
needed to handle the request, got an invalid response.
HTTP response headers provide additional information about the server’s response to an HTTP request
Example:
200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Date: Mon, 18 Jul 2016 16:06:00 GMT
Etag: "c561c68d0ba92bbeb8b0f612a9199f722e3a621a"
Keep-Alive: timeout=5, max=997
Last-Modi ed: Mon, 18 Jul 2016 02:36:04 GMT
Server: Apache
Set-Cookie: mykey=myvalue; expires=Mon, 17-Jul-2017 16:06:00 GMT; Max-
Age=31449600; Path=/; secure
Transfer-Encoding: chunked
Vary: Cookie, Accept-Encoding
File Transfer Protocol (FTP)
FTP is an insecure protocol for transferring les from one host to another over the Internet. It is used for the
transfer of les from one host to another over a TCP-based network, such as the Internet. For many years, it
was the standard way of transferring les, but as it is inherently insecure, it is no longer supported by many
hosting accounts.
SSL
SSL is used for securing an internet connection by encrypting data sent between a website and a browser. It
prevents hackers from seeing or stealing any information transferred, including personal or nancial data.
Transport Layer Security (TLS)
fi
fi
fi
fi
fi
fi
fi
TLS is an updated, more secure version of SSL. It is the most widely used protocol for implementing
cryptography on the Web. TLS uses a combination of cryptographic processes to provide secure
communication over a network. TLS uses public-key cryptography to provide authentication and secret-key
cryptography with hash functions to provide privacy and data integrity.
Web Applications
Web applications are delivered on the World Wide Web to users with an active network connection.
WEB 1.0 is the WWW. It is a system of interlinked, hypertext pages or documents accessed via
INTERNET. It is the read-only web.
WEB 2.0 is the social web. It makes use of new and latest technologies to make the user experience more
interactive, useful, and interconnecting. It is associated with blogs, wikis, podcasts, etc.
WEB 3.0: It is a Semantic Web. It supports 3D portals, multi-user virtual environments, integrated games,
and all media ows in and out of virtual web worlds. Web 3.0 organizes all the information
Tools Used in Web Programming:
Web programs and scripts are divided into two categories:
• Client side: HTML and XML are client-side languages
• Server side: PHP and Ruby are server-side languages
JavaScript is often a client-side language but can be used for both
HTML
HTML is the standard markup language for web pages. It describes the structure of a web page. It consists of
a series of elements and these elements tell the browser how to display the content. Each element is de ned
by a start tag, some content, and an end tag. A web browser reads the HTML documents and displays them
correctly.
Example:
XML
XML stands for eXtensible Markup Language. Unlike other programming languages, XML cannot perform
computing operations by itself. XML’s primary function is to create formats for data that are used to encode
information for documentation, database records, transactions, and many other types of data. It was designed
to be self-descriptive, human- and machine-readable. XML users create their own markup language set of
tags and attributes.
Example:
JavaScript
JavaScript, often abbreviated as JS, is a programming language and core technology of the World Wide Web,
alongside HTML and CSS. JavaScript engines were originally used only in web browsers but are now core
components of some servers and a variety of applications. The most popular runtime system for this usage is
fl
fi
Node.js. JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting
object-oriented, imperative, and declarative styles.
Primary uses:
• Validate form data
• Build Ajax-enabled HTML documents
• Create dynamic HTML documents
PHP
PHP is a general-purpose scripting language geared toward web development. PHP is a server scripting
language and a powerful tool for making dynamic and interactive web pages. PHP code is embedded in
HTML documents. The code is interpreted on the server before the HTML document is delivered to the
requesting client.
Example:
Form - HTML. ——>
Table - HTML
Flexstyle - solution
/* Global */
* {
margin: 0;
padding: 0;
font-family: Arial, Helvetica;
}
/* Header
Adds background color , padding and boxshadow to header
*/
header {
background-color: goldenrod;
padding: 20px 50px;
box-shadow: 0 1px 8px #ddd;
}
/*Style the heading element */
h1{
color:darkblue;
margin-left: 10px;
}
/*Navigation Element
Nav is the Flex container, The List items inside the nav element are the flex items*/
nav{
display: flex;
justify-content:flex-end;
align-items: center;
padding: 20px 50px;
}