CSC 318 Web Technology: Navigating Key Terms and Concepts
50+ Must-Know Terms and Complete Web Technology Unpacked
Abstract:
This article provides an overview of over 50 fundamental web technology terms and concepts. It explores various topics and sub-topics related to web technology. This comprehensive detailed overview is a valuable reference for understanding key terms, ideas, and topics simply and concisely.?
1. Introduction to Web Technology
The World Wide Web has undergone a remarkable transformation since its inception, evolving from static HTML pages to dynamic, interactive platforms that power much of our daily digital interactions. This evolution has been driven by a continuous stream of innovative web technologies, each pushing the boundaries of what’s possible in online experiences.
1.1 Web Basics: Internet, Intranet, WWW, Static and Dynamic Web?Page
1.1.1 Internet
1.1.2 Intranet
1.1.3 World Wide Web?(WWW)
The World Wide Web, often simply called the Web, is a system of interconnected documents and other resources accessed via the Internet. It’s a vast collection of information, multimedia, and applications accessible through web browsers. The key to the Web is its use of hypertext links, which allow users to navigate seamlessly from one document to another.
Key components of the WWW:
1.1.4 Static Web?Page
1.1.5 Dynamic Web?Page
1.2 Web Client and Web?Server
1.2.1 Web?Client
A web client is a software application that communicates with a web server to access and display web resources. It’s essentially the tool we use to interact with the web.
Common examples of web clients:
How it works:
1.2.3 Web?Server
A web server is a computer program that serves web pages to users. It stores the website’s files and processes requests from web clients.
Key functions of a web server:
Popular web server software:
In essence:
1.4 HTTP: HTTP Request and?Response
1.4.1 HTTP?Protocol
HTTP (Hypertext Transfer Protocol) is the foundation of the World Wide Web. It’s a protocol for transferring data between a client (usually a web browser) and a server. It defines how messages are formatted and transmitted, and what actions web servers and browsers should take in response to various commands.
1.4.2 HTTP?Request
An HTTP request is a message sent from a client to a server to request a resource. It includes:
1.4.3 HTTP?Response
An HTTP response is a message sent from a server to a client in response to a request. It includes:
1.4.4 Example of a simple HTTP?request:
GET /index.html HTTP/1.1
Host: www.example.com
Example of a simple HTTP response:
HTTP/1.1 200 OK
Content-Type: text/html
<!DOCTYPE html>
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
Essentially, HTTP is the language used for communication between web browsers and servers, enabling the seamless exchange of information that powers the internet.
1.5 URL (Uniform Resource?Locator)
1.5.1 URL (Uniform Resource Locator). Client-Side Scripting
1.5.2 Server-Side Scripting
1.6 Web 1.0 and Web?2.0
1.6.1 Web?1.0?
Often referred to as the “Read-Only Web,” Web 1.0 was primarily about consuming information. Websites were static, with limited interaction and user-generated content. Key characteristics include:
1.6.2 Web 2.0 and Its?Services
Web 2.0 is a paradigm shift from passive consumption of content to active participation and collaboration. It introduced bidirectional services that revolutionized how we interact online.
Here are some key Web 2.0 services:
Social Networking
Content Sharing
Web Applications
User-Generated Content
Other Notable Services
Key characteristics of Web 2.0 services:
These services have transformed the way we communicate, consume information, and interact with each other online.
1.7 Client-server architecture
Client-server architecture is a model where clients (user devices) communicate with servers to access services or resources over a network.
1.7.1 Single-Tier Architecture
1.7.2 Two-Tier Architecture
1.7.3 Multi-Tier (N-Tier) Architecture
2. Hyper Text Markup Language?(HTML)
2.1 Introduction to HTML; Elements of HTML?Document
HTML is the standard language used to create and design web pages. It structures content on the web by using elements and tags.
2.2 HTML Elements and Attributes
2.3 Formatting
2.4 Formatting Text?Phrases
2.5 Image Element;?Anchors
<img src="image.jpg" alt="Description of Image">
<a >This is a link to example.com</a>
<tt>This is teletype (monospaced) text.</tt>
<strong>This is strong (bold) text.</strong>
<span>This is inline text with a span tag.</span>
<br>
<sub>Subscript text</sub>
<small>This text is small.</small>
<i>This text is italic.</i>
<b>This text is bold.</b>
<div>This is a division block.</div>
<p>This is a paragraph.</p>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
2.6 Lists: Ordered, Unordered, and Definition
2. <li>Tea: The second list item.
<h1>List of Items</h1>
<ol type="1">
<li>Coffee:
<ul>
<li>I. Black coffee</li>
<li>II. Green coffee</li>
</ul>
</li>
<li>Tea
<ol type="A">
<li>Black tea</li>
<li>Green tea</li>
</ol>
</li>
</ol>
2.7 Tables; Frames; Forms: Form Elements, ID attributes, Class Attributes
2.7.1 Inline?Frames
Inline frames (iframes) are HTML elements used to embed content from another website directly into our current webpage. Here are some reasons why iframes are used:
Here’s an HTML page example using an iframe:
<!DOCTYPE html>
<html>
<head>
<title>Iframe Example</title>
</head>
<body>
<p>This paragraph contains an iframe from TUIOST website.</p>
<iframe src="https://www.tuiost.edu.np" width="400" height="200"></iframe>
</body>
</html>
2.7.2 Forms
<!DOCTYPE html>
<html>
<head>
<title>HTML Tables, Frames, and Forms</title>
<style>
.styled-paragraph {
color: blue;
font-weight: bold;
}
#unique-paragraph {
color: red;
}
</style>
</head>
<body>
<!-- Table Example -->
<h2>HTML Table</h2>
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
</tr>
<tr>
<td>Jane</td>
<td>30</td>
</tr>
</table>
<!-- Frame Example (deprecated) -->
<!-- <frameset cols="50%,50%">
<frame src="frame1.html">
<frame src="frame2.html">
</frameset> -->
<!-- Form Example -->
<h2>HTML Form</h2>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
<!-- ID and Class Example -->
<h2>ID and Class Attributes</h2>
<p id="unique-paragraph">This is a unique paragraph with red text.</p>
<p class="styled-paragraph">This is a paragraph with a blue, bold style.</p>
<p class="styled-paragraph">This is another styled paragraph.</p>
</body>
</html>
2.8 Meta Tag, Audio, Video, Canvas, Main, Section, Article, Header, Footer, Aside, Nav, Figure?Tags
2.8.1 Meta?Tag
2.8.2 Audio?Tag
2.8.3 Video?Tag
2.8.4 Canvas?Tag
2.8.5 Main?Tag
2.8.6 Section?Tag
2.8.7 Article?Tag
2.8.8 Header?Tag
2.8.9 Footer?Tag
2.8.10 Aside?Tag
2.8.11 Nav?Tag
2.8.12 Figure?Tag
<!-- Header Section -->
<header>
<h1>Welcome to My Web Page</h1>
<nav>
<ul>
<li><a href="#section1">Home</a></li>
<li><a href="#section2">About</a></li>
<li><a href="#section3">Contact</a></li>
</ul>
</nav>
</header>
<!-- Main Content -->
<main>
<!-- Section 1 -->
<section id="section1">
<h2>Introduction</h2>
<p>This section introduces the main content of the webpage.</p>
</section>
<!-- Section 2 with an Article -->
<section id="section2">
<h2>About</h2>
<article>
<h3>What We Do</h3>
<p>We specialize in creating web solutions using modern technologies.</p>
</article>
</section>
<!-- Section 3 with Media Content -->
<section id="section3">
<h2>Media</h2>
<!-- Figure with Image -->
<figure>
<img src="image.jpg" alt="A beautiful scenery" width="300">
<figcaption>A stunning view of nature.</figcaption>
</figure>
<!-- Audio Element -->
<h3>Listen to Our Theme Song</h3>
<audio controls>
<source src="song.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<!-- Video Element -->
<h3>Watch Our Promo Video</h3>
<video controls width="400">
<source src="promo.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<!-- Canvas Element -->
<h3>Interactive Canvas Drawing</h3>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>
</section>
<!-- Aside Section -->
<aside>
<h3>Related Links</h3>
<ul>
<li><a href="#section1">Go to Home</a></li>
<li><a href="#section2">Learn About Us</a></li>
</ul>
</aside>
</main>
<!-- Footer Section -->
<footer>
<p>© 2024 My Website. All rights reserved.</p>
</footer>
2.9 HTML Events: Window Events, Form Element Events, Keyboard Events, Mouse?Events
The KeyboardEvent Object handles events that occur when a user presses a key on the keyboard.
Common keyboard events:
<p id="message"></p>
<script>
document.addEventListener('keypress', function(event) {
document.getElementById("message").textContent = "Hello, world!";
});
</script>
Explanation:
2.9.1 Window?Events
Examples:
2.9.2 Form Element?Events
Examples:
2.9.3 Mouse?Events
Examples:
2.9.4 Summary
<h1>Event Handling Example</h1>
<!-- Window Events -->
<h2>Window Events</h2>
<p id="windowEvent">Resize the window or reload the page to see events in action.</p>
<!-- Form Element Events -->
<h2>Form Element Events</h2>
<form id="sampleForm">
<label for="name">Name:</label>
<input type="text" id="name" required>
<input type="submit" value="Submit">
</form>
<p id="formEventMessage"></p>
<!-- Mouse Events -->
<h2>Mouse Events</h2>
<div id="hoverBox">Hover over me!</div>
<p id="mouseEventMessage"></p>
<script>
// Window Events
window.addEventListener('load', () => {
document.getElementById('windowEvent').innerText = "Page is fully loaded.";
});
window.addEventListener('resize', () => {
document.getElementById('windowEvent').innerText = "Window resized!";
});
// Form Element Events
const form = document.getElementById('sampleForm');
const formMessage = document.getElementById('formEventMessage');
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent form submission
const name = document.getElementById('name').value;
formMessage.innerText = `Hello, ${name}! Your form has been submitted.`;
});
document.getElementById('name').addEventListener('focus', () => {
formMessage.innerText = "Input field focused.";
});
document.getElementById('name').addEventListener('blur', () => {
formMessage.innerText = "Input field lost focus.";
});
// Mouse Events
const hoverBox = document.getElementById('hoverBox');
const mouseMessage = document.getElementById('mouseEventMessage');
hoverBox.addEventListener('mouseover', () => {
mouseMessage.innerText = "Mouse is over the box!";
});
hoverBox.addEventListener('mouseout', () => {
mouseMessage.innerText = "Mouse left the box.";
});
hoverBox.addEventListener('click', () => {
mouseMessage.innerText = "Box clicked!";
});
</script>
3. Cascading Style Sheets?(CSS)
3.1 Introduction to CSS; CSS?Syntax
CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML or XML. It enables web developers to apply styles to web pages, controlling layout, colors, fonts, and overall visual presentation.
3.2 CSS?Syntax
CSS syntax consists of selectors and declaration blocks. A selector targets HTML elements, while a declaration block contains one or more declarations (property-value pairs) that define the styles to be applied to the selected elements.
3.3 Inserting CSS
There are three primary methods to insert CSS into HTML documents:
3.4 ID and Class Selectors
3.5 Colors
CSS supports a variety of methods for defining colors, including named colors (e.g., “red”), hexadecimal values (e.g., “#FF0000”), and RGB/RGBA values (e.g., “rgb(255,0,0)” or “rgba(255,0,0,0.5)”). These allow developers to control the color of text, backgrounds, borders, and other elements.
3.6 Backgrounds
The background property in CSS allows developers to set background colors, images, and other properties for elements. Backgrounds can cover entire elements or specific parts of them and can be customized in terms of size, repeat behavior, and positioning.
3.7 Borders
CSS enables the addition of borders to elements using the border property, which can define the width, style (e.g., solid, dashed), and color. Borders can enhance the visual separation of elements on a web page.
3.8 Text
CSS provides various properties to style text, including font size, color, font family, line height, and text alignment. These properties help create readable and visually appealing text layouts.
3.9 Font
CSS allows extensive control over font styling, including selecting specific font families, adjusting font sizes, applying font weights (e.g., bold or light), and styling (e.g., italic). This is essential for enhancing the overall design and readability of text content.
3.10 List
CSS can be used to style ordered (numbered) and unordered (bulleted) lists, allowing developers to customize bullet styles, indentation, and list layout. This ensures lists are visually appealing and fit well within the overall design.
3.11 Table
CSS facilitates the styling of HTML tables, enabling customization of borders, padding, spacing, and background colors. Proper styling enhances the readability and presentation of tabular data on web pages.
<style>
/* Internal CSS */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
/* ID Selector */
#header {
background-color: #4CAF50;
color: white;
padding: 10px;
text-align: center;
}
/* Class Selector */
.highlight {
background-color: yellow;
}
/* Styling for lists */
ul {
list-style-type: square; /* Change bullet style */
padding-left: 20px;
}
/* Table styles */
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
/* Customizing text */
.large-text {
font-size: 1.5em;
color: #333;
}
</style>
</head>
<body>
<div id="header">
<h1>Welcome to CSS Concepts</h1>
</div>
<p class="large-text">This is an example of using CSS to style a webpage.</p>
<p>This paragraph contains some <span class="highlight">highlighted text</span> using a class selector.</p>
<h2>Sample List</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<h2>Sample Table</h2>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>25</td>
<td>Los Angeles</td>
</tr>
</table>
CSS selectors are used to target specific HTML elements to which we want to apply styles. Among these, class and ID selectors are the most commonly used.
In Summary:
3.4 CSS Box Model; Normal Flow Box Layout: Basic Box Layout, Display Property, Padding,?Margin
3.4.1 CSS Box?Model
The CSS Box Model is a fundamental concept that governs how elements are structured and positioned on a webpage. Every HTML element can be considered as a box, and the box model describes the properties of this box.
3.4.3 Components of the Box?Model:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
border: 5px solid blue;
padding: 15px;
margin: 10px;
}
</style>
</head>
<body>
<div>
This is a div element.
</div>
</body>
</html>
3.5 Positioning: Static, Fixed, Relative, Float,?Absolute
Positioning HTML elements in CSS allows us to control their placement on the page. CSS offers several positioning techniques:
3.5.1 Static Positioning
By default, elements are positioned statically. They flow in the order they appear in the HTML.
/* Default */
div {
position: static; /* This is the default value */
}
3.5.2. Relative Positioning
Relative positioning moves an element relative to its original position.
div {
position: relative;
top: 10px; /* Moves the element 10px down from its original position */
left: 20px; /* Moves the element 20px right from its original position */
}
3.5.3. Absolute Positioning
Absolute positioning removes an element from the document flow and positions it relative to its nearest positioned ancestor (non-static). If no such ancestor exists, it positions itself relative to the initial containing block (usually the viewport).
div {
position: absolute;
top: 50px; /* Moves the element 50px from the top of the nearest positioned ancestor */
left: 100px; /* Moves the element 100px from the left of the nearest positioned ancestor */
}
3.5.4. Fixed Positioning
Fixed positioning positions an element relative to the viewport. It stays in the same place even when the page is scrolled.
div {
position: fixed;
bottom: 10px; /* Moves the element 10px from the bottom of the viewport */
right: 20px; /* Moves the element 20px from the right of the viewport */
}
3.5.5 Sticky Positioning
Sticky positioning is a hybrid of relative and fixed positioning. The element toggles between relative and fixed based on the scroll position. It is positioned relative to its nearest scrolling ancestor until a specified scroll position is reached, at which point it becomes fixed.
div {
position: sticky;
top: 0; /* Sticks the element to the top of its container when scrolling */
}
3.6 CSS3 Borders, Box Shadows, Text Effects and?Shadow
3.6.1 CSS3?Borders
CSS3 introduces additional border features like rounded corners and border images. The border-radius property allows you to create rounded edges for elements, enhancing design aesthetics. The border-image property lets you use images for borders, adding flexibility to styling.
3.6.2. Box?Shadows
The box-shadow property in CSS3 allows you to apply shadows to elements, adding depth and realism. You can control the shadow's offset, blur, spread, and color. Box shadows can be used to create 3D-like effects or simple visual enhancements.
3.6.3. Text Effects and?Shadow
CSS3 provides various text effects, including shadows and transformations. The text-shadow property lets you add shadows to text, creating an embossed or glowing effect. You can specify multiple values for horizontal and vertical offsets, blur radius, and shadow color to customize the appearance.
Examples of Properties:
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
padding: 20px;
}
/* CSS3 Border */
.border-example {
border: 2px solid #4CAF50; /* Solid border */
border-radius: 15px; /* Rounded corners */
padding: 20px;
margin: 20px 0;
background-color: white;
}
/* Box Shadow */
.box-shadow-example {
background-color: white;
border: 1px solid #ddd;
padding: 20px;
margin: 20px 0;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Shadow effect */
}
/* Text Shadow */
.text-shadow-example {
font-size: 24px;
color: #333;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3); /* Shadow effect for text */
}
/* Combined Effects */
.combined-example {
border: 2px solid #4CAF50;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
padding: 20px;
background-color: white;
font-size: 20px;
color: #333;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
}
</style>
<h2>CSS3 Borders Example</h2>
<div class="border-example">
This box has a solid border and rounded corners.
</div>
<h2>Box Shadow Example</h2>
<div class="box-shadow-example">
This box has a subtle shadow effect.
</div>
<h2>Text Shadow Example</h2>
<p class="text-shadow-example">
This text has a shadow effect applied to it.
</p>
<h2>Combined Borders, Shadows, and Text Effects</h2>
<div class="combined-example">
This box combines borders, shadows, and text effects.
</div>
3.7 Basics of Responsive Web Designs; Media?Queries
3.7.1 Using Media Queries for Responsive Web?Design
Media Queries are CSS rules that allow us to apply styles based on specific conditions, such as screen size, orientation, and resolution. They are the cornerstone of responsive web design, ensuring that the website adapts to different devices and screen sizes.
@media (condition) { /* CSS rules */ }
<!DOCTYPE html>
<html>
<head>
<title>Media Query Example</title>
<style>
body {
background-color: lightblue;
}
@media (max-width: 768px) {
body {
background-color: lightpink;
}
}
</style>
</head>
<body>
<p>This is a responsive page.</p>
</body>
</html>
3.7.1.1 Common conditions:
3.8 Introduction to Bootstrap
Bootstrap is a popular open-source front-end framework used for designing responsive and mobile-first websites. Developed by Twitter, it provides a collection of CSS and JavaScript components that facilitate the development of user-friendly web interfaces.
<link rel="stylesheet" >
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">My Bootstrap Site</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
<!-- Main Content -->
<div class="container mt-4">
<h1 class="text-center">Welcome to My Bootstrap Page</h1>
<div class="row">
<div class="col-md-4">
<div class="card">
<img src="https://via.placeholder.com/150" class="card-img-top" alt="Image 1">
<div class="card-body">
<h5 class="card-title">Card Title 1</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<img src="https://via.placeholder.com/150" class="card-img-top" alt="Image 2">
<div class="card-body">
<h5 class="card-title">Card Title 2</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<img src="https://via.placeholder.com/150" class="card-img-top" alt="Image 3">
<div class="card-body">
<h5 class="card-title">Card Title 3</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
</div>
</div>
<!-- Include Bootstrap JS and dependencies -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
4. Client Side Scripting with JavaScript
4.1 Structure of JavaScript Program; Variables and Data?Types
Concept: JavaScript programs are structured with a combination of statements, expressions, and functions. Variables are declared using var, let, or const, and can hold different types of data, including:
4.2 Statements: Expression, Keyword,?Block
Concept:
4.3 Operators; Flow Controls, Looping, Functions
Concept:
4.4 Popup Boxes: Alert, Confirm,?Prompt
Concept:
4.5 Objects and Properties; Constructors
Concept:
4.6 Arrays; Built-in Objects: Window, String, Number, Boolean, Date, Math, RegExp, Form,?DOM
Concept:
// 4.1 Structure of JavaScript Program; Variables and Data Types
let greeting = "Hello, World!"; // String
let age = 25; // Number
let isStudent = true; // Boolean
// 4.2 Statements: Expression, Keyword, Block
if (age >= 18) { // Block
console.log("You are an adult."); // Statement
} else {
console.log("You are a minor."); // Statement
}
// 4.3 Operators; Flow Controls, Looping, Functions
function calculateSum(a, b) { // Function
return a + b; // Expression
}
console.log("Sum:", calculateSum(5, 10)); // Calling function with values
for (let i = 0; i < 5; i++) { // Looping
console.log("Iteration:", i);
}
// 4.4 Popup Boxes: Alert, Confirm, Prompt
alert(greeting); // Alert box
let userConfirmation = confirm("Do you want to proceed?"); // Confirm box
if (userConfirmation) {
let userName = prompt("Enter your name:"); // Prompt box
console.log("Welcome, " + userName);
}
// 4.5 Objects and Properties; Constructors
function Person(name, age) { // Constructor
this.name = name; // Property
this.age = age; // Property
}
let person1 = new Person("Alice", 30); // Object instance
console.log("Person:", person1.name, "Age:", person1.age);
// 4.6 Arrays; Built-in Objects: Window, String, Number, Boolean, Date, Math, RegExp, Form, DOM
let fruits = ["apple", "banana", "cherry"]; // Array
console.log("Fruits:", fruits);
// Using built-in objects
console.log("Random Number:", Math.random()); // Math object
console.log("Current Date:", new Date()); // Date object
let regex = /[a-zA-Z]+/; // RegExp object
console.log("Regex Test:", regex.test("Hello")); // Testing regex
4.7 User-Defined Objects
领英推荐
4.7.1. Object?Literals
The simplest way to create an object is using an object literal. This is done by defining the properties and their values within curly braces {}.
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.firstName); // Output: John
console.log(person.fullName()); // Output: John Doe
4.7.2. Using the new Object()?Syntax
We can create an object using the Object constructor. This method is less commonly used but still valid.
let person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 30;
person.fullName = function() {
return this.firstName + " " + this.lastName;
};
console.log(person.firstName); // Output: John
console.log(person.fullName()); // Output: John Doe
4.7.3. Constructor Functions
Constructor functions are a convention for creating multiple objects of the same type. The function name should start with an uppercase letter.
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
let person1 = new Person("John", "Doe", 30);
let person2 = new Person("Jane", "Smith", 25);
console.log(person1.fullName()); // Output: John Doe
console.log(person2.fullName()); // Output: Jane Smith
4.7.4. ES6?Classes
ES6 introduced classes, which provide a more structured and syntactic style over constructor functions.
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
fullName() {
return this.firstName + " " + this.lastName;
}
}
let person1 = new Person("John", "Doe", 30);
let person2 = new Person("Jane", "Smith", 25);
console.log(person1.fullName()); // Output: John Doe
console.log(person2.fullName()); // Output: Jane Smith
4.7.5. Using Object.create()
The Object. create() method creates a new object with the specified prototype object and properties.
let personPrototype = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
let person = Object.create(personPrototype);
person.firstName = "John";
person.lastName = "Doe";
person.age = 30;
console.log(person.fullName()); // Output: John Doe
These methods provide a variety of ways to create objects in JavaScript, each with its use cases and benefits.
4.8 Event Handling and Form Validation
Event handling is a crucial part of web development that allows developers to create interactive web pages. It involves responding to user actions or events, such as mouse clicks, keyboard presses, and form submissions
4.8.2 Javascript and HTML Form Validation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Signup Form</title>
<style>
body {
font-family: Arial, sans-serif;
}
form {
max-width: 300px;
margin: auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
}
.error {
color: red;
font-size: 0.875em;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>Signup Form</h1>
<form id="signupForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
<div id="nameError" class="error hidden">Name is required.</div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
<div id="emailError" class="error hidden">Invalid email address.</div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
<div id="passwordError" class="error hidden">Password must be at least 6 characters, start with a letter, and end with a digit.</div>
<label for="age">Age:</label>
<input type="number" id="age" name="age" />
<div id="ageError" class="error hidden">Age must be between 8 and 60.</div>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("signupForm").addEventListener("submit", function (event) {
let isValid = true;
// Name Validationconst name = document.getElementById('name').value;
if (name === "") {
document.getElementById("nameError").classList.remove("hidden");
isValid = false;
} else {
document.getElementById("nameError").classList.add("hidden");
}
// Email Validation
const email = document.getElementById("email").value;
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email) || email === "") {
document.getElementById("emailError").classList.remove("hidden");
isValid = false;
} else {
document.getElementById("emailError").classList.add("hidden");
}
// Password Validation
const password = document.getElementById("password").value;
const passwordPattern = /^[a-zA-Z].{4,}[0–9]$/;
if (password.length < 6 || !passwordPattern.test(password)) {
document.getElementById("passwordError").classList.remove("hidden");
isValid = false;
} else {
document.getElementById("passwordError").classList.add("hidden");
}
// Age Validation
const age = document.getElementById("age").value;
if (age < 8 || age > 60) {
document.getElementById("ageError").classList.remove("hidden");
isValid = false;
} else {
document.getElementById("ageError").classList.add("hidden");
}
// Prevent form submission if invalid
if (!isValid) {
event.preventDefault();
}
});
</script>
</body>
</html>
Explanation:
This setup provides straightforward validation and feedback, ensuring users fill out the form correctly before submission.
4.9 Error Handling, Handling Cookies
// error handling
try {
// Simulate an error
let result = someUndefinedFunction();
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
// Handle the error, like showing an alert to the user
alert("Something went wrong. Please try again later.");
} finally {
console.log("Error handling complete.");
}
// create a cookie
function setCookie(name, value, days) {
let expires = "";
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
// Example: Set a cookie
setCookie("username", "JohnDoe", 7); // Cookie expires in 7 days
// read cookie
function getCookie(name) {
let nameEQ = name + "=";
let cookiesArray = document.cookie.split(';');
for (let i = 0; i < cookiesArray.length; i++) {
let cookie = cookiesArray[i].trim();
if (cookie.indexOf(nameEQ) == 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
// Example: Read a cookie
let username = getCookie("username");
if (username) {
console.log("Welcome back, " + username);
} else {
console.log("Username cookie not found.");
}
// delete cookie
function deleteCookie(name) {
// To delete, set the expiration date to the past
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// Example: Delete a cookie
deleteCookie("username");
Both error handling and managing cookies ensure better usability and application reliability.
4.10. jQuery
4.10.1 jQuery Animate() Method for Custom Animations
The jQuery animate() method allows us to create custom animations by changing CSS properties over a specified duration.
$(selector).animate({properties}, [duration], [easing], [callback]);
<!DOCTYPE html>
<html>
<head>
<title>jQuery Animate Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
#myDiv {
width: 200px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div id="myDiv"></div>
<script>
$(document).ready(function() {
$("#myDiv").animate({
width: "400px",
height: "200px",
opacity: 0.5
}, 2000, function() {
alert("Animation complete!");
});
});
</script>
</body>
</html>
Explanation:
This code will animate the div to double its size and reduce its opacity to 0.5 over 2 seconds.
4.10.2 jQuery Selectors and?Event?
<!DOCTYPE html>
<html>
<head>
<title>jQuery ID Selector</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button id="hideButton">Hide Paragraph</button>
<p id="myParagraph">This is a paragraph.</p>
<script>
$(document).ready(function() {
$("#hideButton").click(function() {
$("#myParagraph").hide();
});
});
</script>
</body>
</html>
// Hide the element
$("#myDiv").hide();
// Show the element
$("#myDiv").show();
// Toggle the element's visibility
$("#myDiv").toggle();
4.10.3 jQuery?Chaining
Chaining in jQuery allows us to perform multiple actions on the same set of elements in a single statement. This enhances code readability and efficiency by avoiding redundant selections of elements.
Essentially, most jQuery methods return a jQuery object, which means we can immediately call another method on the same object without reselecting it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="myDiv">This is a div</div>
<script>
$(document).ready(function() {
$("#myDiv").slideUp(500).slideDown(500);
});
</script>
</body>
</html>
Explanation:
How it?works:
Benefits of chaining:
By understanding and utilizing chaining, we can write more efficient and elegant jQuery code.
4.12 JSON:?
JSON is a Lightweight Data-Interchange Format. JSON (JavaScript Object Notation) is a standard text-based format for representing structured data. It’s derived from JavaScript object syntax but is language-independent.
In JSON, values must be one of the following data types:
{"name":"John"}- JSON STRINGS
{"age":30} - JSON Objects Values in JSON can be objects.
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
{
"employees":["John", "Anna", "Peter"]
}
{"sale":true}
{"middlename":null}
4.12.1 Uses of?JSON
4.12.2 Parsing?JSON
Parsing JSON involves converting a JSON string into a data structure that can be used by a programming language.
let jsonString = '{"name":"John Doe", "age":30, "city":"New York"}';
// Parse the JSON string
let jsonData = JSON.parse(jsonString);
// Access data
console.log(jsonData.name); // Output: John Doe
console.log(jsonData.age); // Output: 30
console.log(jsonData.city); // Output: New York
Explanation:
4.12.3 JSON Primitive Data?Types
Values in JSON can be arrays.
Values in JSON can be true/false
Values in JSON can be null.
Objects as values in JSON must follow the JSON syntax.
These are the basic building blocks of JSON data.
4.12.4 Complex Data?Types
These data types allow for structured data representation.
5: AJAX and?XML?
5.1 Basics of AJAX Introduction to XML and its Application?
XML stands for Extensible Markup Language. It’s a text-based format for representing structured data. Unlike HTML, which defines how data looks, XML defines what data is.
5.1.1 Key Characteristics of?XML:
5.1.2 Example: XML File for Employee?Records
Let’s create a simple XML file containing employee records with both simple and complex data types.
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee id="1">
<firstName>John</firstName>
<lastName>Doe</lastName>
<salary>50000</salary>
<address>
<street>123 Main St</street>
<city>Anytown</city>
<state>CA</state>
<zip>12345</zip>
</address>
<phone>(123) 456–7890</phone>
<email>[email protected]</email>
</employee>
</employees>
5.1.3 Explanation:
5.2 Syntax Rules for Creating XML Document XML?Elements
XSD (XML Schema Definition) is a schema language for defining the structure of an XML document. It provides a formal grammar for describing the elements and data types that can appear in an XML document.
5.2.1 XSD of XML File (XSD Code Structure)
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>The Lord of the Rings</title>
<author>J.R.R. Tolkien</author>
<year>1954</year>
</book>
<book>
<title>Pride and Prejudice</title>
<author>Jane Austen</author>
<year>1813</year>
</book>
</books>
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="https://www.w3.org/2001/XMLSchema">
<xs:element name="books">
<xs:complexType>
<xs:sequence>
<xs:element name="book" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="year" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
5.2.2 Explaination:
The <xs:schema> element is the root element of an XSD document.
The <xs:element> defines the root element of the XML document, “books”.
The <xs:complexType> defines the structure of the “books” element.
The <xs:sequence> defines the order of child elements within “books”.
The <xs:element> defines the “book” element with minOccurs=”0" and maxOccurs=”unbounded” to allow zero or multiple occurrences.
The nested <xs:complexType> defines the structure of the “book” element.
The <xs:element> elements for “title”, “author”, and “year” define their data types using built-in types.
5.3 XML Attributes
Definition:
XML attributes provide additional information about elements in an XML document. They are defined within the opening tag of an element and consist of a name-value pair. Attributes help to clarify the characteristics of elements and can be used to store metadata.
Concepts:
<book title="The Great Gatsby" author="F. Scott Fitzgerald" year="1925">
<description>A novel set in the Roaring Twenties.</description>
</book>
5.4 XML?Tree
Definition: An XML tree is a hierarchical structure that represents the organization of elements within an XML document. It visually depicts the relationships between elements, where each element is a node, and the document itself is the root of the tree. The structure resembles a tree, with parent-child relationships between elements.
Concepts:
Key Points:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XML Tree Representation</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
.node {
margin-left: 20px;
margin-bottom: 10px;
}
.root {
font-weight: bold;
color: blue;
}
.child {
color: green;
}
.attribute {
color: purple;
font-style: italic;
}
.summary {
font-style: italic;
color: gray;
}
</style>
</head>
<body>
<div class="node root">library</div>
<div class="node child">
book
<span class="attribute">title="1984"</span>
<span class="attribute">author="George Orwell"</span>
<span class="attribute">year="1949"</span>
<div class="summary">A dystopian novel set in a totalitarian state.</div>
</div>
<div class="node child">
book
<span class="attribute">title="To Kill a Mockingbird"</span>
<span class="attribute">author="Harper Lee"</span>
<span class="attribute">year="1960"</span>
<div class="summary">A novel about racial injustice in the Deep South.</div>
</div>
</body>
</html>
5.5 XML Namespace; XML Schema Languages: DTD,?XSD
A Document Type Definition (DTD) is a set of rules that define the structure and the legal elements and attributes of an XML document. DTDs are used to enforce the structure of XML documents, specifying the types of elements, their order, and their relationships.
DTDs can be internal or external, where internal DTDs are defined within the XML document and external DTDs are stored in separate files.
Here’s an example of a simple XML file representing information about books and its equivalent DTD:
5.5.2 XML File (books.xml):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE library SYSTEM "books.dtd">
<library>
<book>
<title>Introduction to XML</title>
<author>John Doe</author>
<publication_year>2020</publication_year>
<price>29.99</price>
</book>
<book>
<title>Data Science Basics</title>
<author>Jane Smith</author>
<publication_year>2021</publication_year>
<price>39.99</price>
</book>
</library>
5.5.2.1 DTD File (books.dtd):
<!ELEMENT library (book+)>
<!ELEMENT book (title, author, publication_year, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publication_year (#PCDATA)>
<!ELEMENT price (#PCDATA)>
In this example:
- `<!ELEMENT library (book+)>`: Defines that the `<library>` element must contain one
or more `<book>` elements.
- `<!ELEMENT book (title, author, publication_year, price)>`: Specifies that the `<book>`
element must contain the elements `<title>`, `<author>`, `<publication_year>`, and
`<price>` in that order.
- `<!ELEMENT title (#PCDATA)>`, `<!ELEMENT author (#PCDATA)>`,
`<!ELEMENT publication_year (#PCDATA)>`,
`<!ELEMENT price (#PCDATA)>`: Define that these elements contain parsed character data (#PCDATA).
The DOCTYPE declaration in the XML file references the external DTD file (`books.dtd`), specifying the rules for the structure of the XML document. The DTD enforces the structure of the XML file, ensuring that it adheres to the specified rules and preventing the use of undefined elements or invalid structures.
5.6. XSD Simple Types, XSD Attributes, XSD Complex?Types
5.6. XSD Simple?Types
Concept: XSD (XML Schema Definition) Simple Types are used to define the basic data types for XML elements and attributes. They include built-in types like string, integer, boolean, and date, as well as user-defined types that can enforce constraints such as patterns or value ranges.
5.6.XSD Attributes
Concept: XSD Attributes define properties of XML elements. Attributes provide additional information about elements and can have simple types. They are defined within the context of an element and can be required or optional, allowing for flexible data modeling.
5.6.XSD Complex?Types
Concept: XSD Complex Types allow the definition of elements that can contain other elements and attributes. They enable the creation of structured data types by grouping elements and attributes, supporting nested structures, and providing a way to define hierarchical relationships.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="https://www.w3.org/2001/XMLSchema">
<!-- Definition of Simple Types -->
<xs:simpleType name="stringType">
<xs:restriction base="xs:string"/>
</xs:simpleType>
<xs:simpleType name="integerType">
<xs:restriction base="xs:integer"/>
</xs:simpleType>
<xs:simpleType name="booleanType">
<xs:restriction base="xs:boolean"/>
</xs:simpleType>
<!-- Definition of Complex Type for Book -->
<xs:complexType name="bookType">
<xs:sequence>
<xs:element name="title" type="stringType"/>
<xs:element name="author" type="stringType"/>
<xs:element name="price" type="integerType"/>
<xs:element name="published" type="xs:date"/>
</xs:sequence>
<xs:attribute name="id" type="integerType" use="required"/>
<xs:attribute name="available" type="booleanType" use="optional" default="true"/>
</xs:complexType>
<!-- Root Element -->
<xs:element name="library">
<xs:complexType>
<xs:sequence>
<xs:element name="book" type="bookType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
5.7 XML Style Sheets (XSLT);?XQuery
5.7.1 XML Style Sheets?(XSLT)
Concept: XSLT (Extensible Stylesheet Language Transformations) is a language used to transform XML documents into different formats (like HTML, plain text, or other XML structures). It defines rules for how to apply styles to XML data, making it possible to present XML content in a more readable format or convert it for different purposes.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8"/>
<xsl:template match="/library">
<html>
<head>
<title>Library Catalog</title>
</head>
<body>
<h1>Library Catalog</h1>
<table border="1">
<tr>
<th>Title</th>
<th>Author</th>
<th>Price</th>
<th>Published Date</th>
</tr>
<xsl:for-each select="book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="price"/></td>
<td><xsl:value-of select="published"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
5.7.2 XQuery
Concept: XQuery is a query language designed for querying and manipulating XML data. It allows developers to retrieve and manipulate XML content from databases or XML documents using expressions, providing powerful capabilities for data extraction, transformation, and filtering of XML data.
xquery version "1.0";
declare namespace library = "https://www.example.com/library";
for $book in doc("library.xml")//book
return
<result>
<title>{data($book/title)}</title>
<author>{data($book/author)}</author>
<price>{data($book/price)}</price>
<published>{data($book/published)}</published>
</result>
6. Server Side Scripting using?PHP?
6.1 PHP Syntax, Variables, Data Types, Strings, Constants, Operators
6.1.1 Variables:
6.1.2 Constants:
6.1.3 Data?Types:
6.1.4 String Manipulation:
6.1.5 Operators:
6.1.6 Output:
echo displays the greeting and information about age and the value of PI.
<?php
// PHP Syntax and Variables
$name = "John Doe"; // String
$age = 30; // Integer
$isStudent = false; // Boolean
// Constants
define("PI", 3.14);
// Data Types
$floatNumber = 3.14; // Float
$array = array("apple", "banana", "cherry"); // Array
// String Manipulation
$greeting = "Hello, " . $name . "!"; // Concatenation
$length = strlen($greeting); // Length of string
// Operators
$sum = $age + 5; // Addition
$isAdult = ($age >= 18); // Comparison
// Output
echo $greeting . " You are " . $age . " years old. The value of PI is " . PI . ".";
?>
6.1.7 Defining and Concatenating Strings in?PHP
In PHP, variables are defined using the dollar sign ($) followed by the variable name. Variable names are case-sensitive.
<?php
$firstName = "John";
$lastName = "Doe";
?>
// Concatenating Strings
// To combine two strings, we use the dot (.) operator.
<?php
$fullName = $firstName . " " . $lastName;
echo $fullName; // Output: John Doe
?>
6.2 Control Structure, Functions, Array
6.2.1 Control Structure
Concept: Control structures in PHP are used to dictate the flow of execution in a script based on conditions. They include conditional statements (like if, else, switch), loops (such as for, while, foreach), and include control structures to manage how and when code blocks are executed.
<?php
// Conditional Statement: if, else
$temperature = 30;
if ($temperature > 25) {
echo "It's a hot day.";
} elseif ($temperature == 25) {
echo "It's a pleasant day.";
} else {
echo "It's a cold day.";
}
// Switch Statement
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Almost weekend!";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "Midweek days!";
}
// Loop: for
echo "\nCounting from 1 to 5:\n";
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// Loop: while
echo "\n\nEven numbers from 1 to 10:\n";
$num = 1;
while ($num <= 10) {
if ($num % 2 == 0) {
echo $num . " ";
}
$num++;
}
// Loop: foreach
echo "\n\nFruits:\n";
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
?>
6.2.2 Functions
In PHP, we define a function using the function keyword followed by the function name, parentheses, and curly braces. Here’s how we can define a function that takes two integers as arguments and returns their product:
<?php
// Define the function
function multiply($a, $b) {
return $a * $b;
}
// Example usage of the function
$result = multiply(4, 5);
echo "The product of 4 and 5 is: " . $result;
?>
Explanation:
This function will output The product of 4 and 5 is: 20.
6.2.3 Arrays in?PHP
This PHP script creates a multidimensional array named Product and initializes it with three instances. It then generates an HTML table to display the array values.
<?php
// Define and initialize the multidimensional array
$Product = array(
array("pcode" => "P001", "pname" => "Product 1", "price" => 29.99),
array("pcode" => "P002", "pname" => "Product 2", "price" => 49.99),
array("pcode" => "P003", "pname" => "Product 3", "price" => 19.99)
);
// Start the HTML document
echo "<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Product Table</title>
<style>
table {
width: 50%;
border-collapse: collapse;
margin: 25px 0;
font-size: 18px;
text-align: left;
}
th, td {
padding: 12px;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Product List</h1>
<table>
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th>Price</th>
</tr>";
// Loop through the array and generate table rows
foreach ($Product as $item) {
echo "<tr>
<td>{$item['pcode']}</td>
<td>{$item['pname']}</td>
<td>\${$item['price']}</td>
</tr>";
}
// Close the table and HTML document
echo " </table>
</body>
</html>";
?>
<?php
// we can define the array either using one of the following methods
// 1. array constructor()
$arr = array("dilli", 12.22, True);
// 2. square brackets
$fruits = ["apple", "banana", "citrus"];
// 3. associative array
$associative_array = array(
"name" => "dilli",
"age" => 25
);
// 4. associative array with using square brackets
$associative_arr_brackets = [
"name" => "dillihang",
"age" => 25
];
// createing multi dimensional array
// 1. using array keyword
$arr = array(
array("sports", "football"),
array("music", "salsa")
);
// 2. using square method
$multiarr = [
["GOT", "2014"],
["HELLO", "WORLD"]
]
?>
Explanation:
6.3 Creating Class and?Objects
6.3.1 Define a?Class
A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:
<?php
class Fruit {
// code goes here…
}
?>
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Note: In a class, variables are called properties, and functions are called methods!
6.3.2 Define?Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class but will have different property values. Objects of a class are created using the new keyword.
In the example below, $apple and $banana are instances of the class Fruit:
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
} }
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
6.4 PHP Forms: Accessing Form Elements, Form Validation
6.4.1 Accessing Form Elements in?PHP?
In PHP, accessing form elements is a common task when handling user input from HTML forms. This can be done using the $_GET, $_POST, or $_REQUEST superglobals, depending on the method used in the form. Below is a brief explanation of each method along with a code example.
1. Using?$_GET
The $_GET superglobal is used to collect data sent in the URL as query parameters. This method is suitable for forms where data is not sensitive (e.g., search forms).
2. Using?$_POST
The $_POST superglobal is used to collect data sent in the body of the HTTP request. This method is more secure than, $_GET making it suitable for sensitive information such as passwords.
3. Using $_REQUEST
The $_REQUEST superglobal can collect data from both $_GET and $_POST. It provides a unified way to access input, but it’s best practice to use $_GET or $_POST for clarity.
6.4.2 Form Validation using?PHP
Form validation is a crucial aspect of web development that ensures user inputs are correct and secure. PHP provides various methods for validating form data to improve user experience and enhance security. Here’s a guide on how to perform form validation using PHP.
Types of Validation
<!-- form.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Example</title>
</head>
<body>
<h1>Sample Form with Validation</h1>
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<span class="error" id="nameError"></span><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<span class="error" id="emailError"></span><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="1" max="120" required>
<span class="error" id="ageError"></span><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<!-- process.php -->
<?php
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate Name
if (empty($_POST['name'])) {
$errors['name'] = "Name is required.";
} else {
$name = trim($_POST['name']);
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$errors['name'] = "Only letters and white space allowed.";
}
}
// Validate Email
if (empty($_POST['email'])) {
$errors['email'] = "Email is required.";
} else {
$email = trim($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = "Invalid email format.";
}
}
// Validate Age
if (empty($_POST['age'])) {
$errors['age'] = "Age is required.";
} else {
$age = (int)$_POST['age'];
if ($age < 1 || $age > 120) {
$errors['age'] = "Age must be between 1 and 120.";
}
}
// Check for errors
if (empty($errors)) {
// Process the data (e.g., save to database)
echo "<h1>Form Submitted Successfully</h1>";
echo "<p>Name: " . htmlspecialchars($name) . "</p>";
echo "<p>Email: " . htmlspecialchars($email) . "</p>";
echo "<p>Age: " . htmlspecialchars($age) . "</p>";
} else {
// Display errors
foreach ($errors as $field => $error) {
echo "<p>Error in $field: $error</p>";
}
}
} else {
echo "Invalid request.";
}
?>
6.5 Events, Cookies,?Sessions
6.5.1 Cookies
Definition: Cookies are small pieces of data stored on the client side by the web browser, allowing websites to remember information about the user across different sessions.
6.5.2 Concepts:
Purpose of Cookies:
Cookie Structure:
Cookie Management in JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Events and Cookies Example</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Events and Cookies</h1>
<button id="setCookieBtn">Set Cookie</button>
<button id="getCookieBtn">Get Cookie</button>
<button id="deleteCookieBtn">Delete Cookie</button>
<p id="message"></p>
</body>
</html>
// Event listeners for buttons
document.getElementById('setCookieBtn').addEventListener('click', () => {
setCookie('username', 'JohnDoe', 7); // Set a cookie for 7 days
document.getElementById('message').innerText = "Cookie 'username' set.";
});
document.getElementById('getCookieBtn').addEventListener('click', () => {
const cookieValue = getCookie('username');
document.getElementById('message').innerText = cookieValue ? `Cookie Value: ${cookieValue}` : "Cookie not found.";
});
document.getElementById('deleteCookieBtn').addEventListener('click', () => {
deleteCookie('username'); // Delete the cookie
document.getElementById('message').innerText = "Cookie 'username' deleted.";
});
// Function to set a cookie
function setCookie(name, value, days) {
const expires = new Date(Date.now() + days * 864e5).toUTCString(); // Set expiration date
document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/`;
}
// Function to get a cookie by name
function getCookie(name) {
return document.cookie.split('; ').reduce((r, c) => {
const [key, val] = c.split('=');
return key === name ? decodeURIComponent(val) : r;
}, '');
}
// Function to delete a cookie
function deleteCookie(name) {
setCookie(name, '', -1); // Set the cookie with a past expiration date
}
6.5.2 Handling Sessions in?PHP
Sessions in PHP are used to store information about a user’s session across multiple page requests. This is essential for maintaining user data like login status, shopping cart items, and other persistent information.
6.5.3 Starting a?Session
To start a session, use the session_start() function at the beginning of our PHP script:?
<?php
session_start();
?>
6.5.4 Storing Data in a?Session
We can store data in the session using the $_SESSION array:
<?php
session_start();
$_SESSION['username'] = 'John Doe';
$_SESSION['cart'] = array('item1', 'item2');
?>
6.5.5 Accessing Session?Data
To retrieve data from the session, simply access the corresponding element in the $_SESSION array:
<?php
session_start();
echo "Username: " . $_SESSION['username'];
?>
6.5.6 Destroying a?Session
To destroy a session, use the session_destroy() function:
<?php
session_start();
session_destroy();
?>
6.5.7 Important Considerations:
6.6 Working with PHP and MySQL: Connecting to Database, Creating, Selecting, Deleting, Updating?Records
Below is the simple code on PHP CRUD. This code is just for the demonstration and is focused on lab work. It is not suitable for production.
6.6.1 Creating?Record
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cct";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$sql = "INSERT INTO student (firstname, lastname, email) VALUES ('$firstname', '$lastname', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
header('Location: retrive.php');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Student Record</title>
</head>
<body>
<h2>Create New Student Record</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="firstName">First Name:</label>
<input type="text" id="firstname" name="firstname" required>
<br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastname" name="lastname" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<input type="submit" value="Create Record">
</form>
</body>
</html>
6.6.2 Search and Display?Result
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cct";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Handle search query
$search = isset($_POST['search']) ? $_POST['search'] : "";
// SQL query to retrieve data based on search input
$sql = "SELECT id, firstname, lastname, email FROM student
WHERE firstname LIKE '%$search%'
OR lastname LIKE '%$search%'
OR email LIKE '%$search%'";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search Student Records</title>
</head>
<body>
<h2>Search Student Records</h2>
<form method="post">
<label for="search">Search:</label>
<input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search); ?>">
<input type="submit" value="Search">
</form>
<?php
if ($result->num_rows > 0) {
echo "<table border='1'>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row["id"] . "</td>
<td>" . $row["firstname"] . "</td>
<td>" . $row["lastname"] . "</td>
<td>" . $row["email"] . "</td>
</tr>";
}
echo "</table>";
} else {
echo "No results found";
}
$conn->close();
?>
</body>
</html>
6.6.3 Updating?Record
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cct";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$sql = "UPDATE student
SET firstname='$firstname',
lastname='$lastname',
email='$email' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Student Record</title>
</head>
<body>
<h2>Update Student Record</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="id">Student ID:</label>
<input type="number" id="id" name="id" required>
<br>
<label for="firstname">First Name:</label>
<input type="text" id="firstname" name="firstname" required>
<br>
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" name="lastname" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<input type="submit" value="Update Record">
</form>
</body>
</html>
6.6.4 Deleting?Record
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cct";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$sql = "DELETE FROM student WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete Student Record</title>
</head>
<body>
<h2>Delete Student Record</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="id">Student ID:</label>
<input type="number" id="id" name="id" required>
<br>
<input type="submit" value="Delete Record">
</form>
</body>
</html>
6.7 Introduction to CodeIgniter, Laravel, WordPress
6.7.1 CodeIgniter
A lightweight PHP framework. CodeIgniter is widely used by developers who prefer simplicity, performance, and a low learning curve for their web development projects.?
Key features:
6.7.2 Laravel
A full-featured and popular framework. It offers a more expressive and elegant syntax compared to CodeIgniter.
Key features:
6.7.3 WordPress
A popular content management system (CMS) built on PHP. Originally designed for blogging but has evolved into a versatile platform for creating websites of all kinds.
Key features:
7. Conclusion
As of 25 Sept 2024, the terms and examples plotted in the article can be outdated or not used anymore while you are reading this article because of the advancement in web technology. However, the aim is to outline the core concepts, and terms, and provide foundational knowledge with simplified examples. This article highlights how essential theory and concepts are required for understanding the techniques and developing modern web applications.?
Web technology is integral to the modern landscape of computer science, influencing various fields such as software development, data analysis, and user experience design. As the demand for web applications continues to grow, so does the necessity for web developers who possess a robust skill set.
8. References:
Read More Articles on Dilli Hang Rai | LinkedIn
More About me: dilli822.github.io
Feedback & Review: [email protected], [email protected]