0% found this document useful (0 votes)
22 views60 pages

Cheat Sheet

The document provides an overview of HTML, CSS, JavaScript, MVC architecture, and server-side development with PHP. It covers fundamental concepts, syntax, and best practices for each technology, emphasizing the separation of concerns in MVC architecture. The content is structured into chapters, detailing the roles and functionalities of each component in web development.

Uploaded by

jowelaw685
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views60 pages

Cheat Sheet

The document provides an overview of HTML, CSS, JavaScript, MVC architecture, and server-side development with PHP. It covers fundamental concepts, syntax, and best practices for each technology, emphasizing the separation of concerns in MVC architecture. The content is structured into chapters, detailing the roles and functionalities of each component in web development.

Uploaded by

jowelaw685
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

HTML (Chapter 3)

1. What is HTML?

●​ HTML (HyperText Markup Language) is a markup language used to structure web content.
●​ It uses markup to distinguish content from instructions.

2. HTML Syntax:

●​ HTML documents are composed of elements within angle brackets (< >).
●​ Elements can have attributes to define additional information.
●​ Empty elements (e.g., <br>) do not require closing tags.
●​ Nesting: Elements must be properly nested for correct rendering.

3. Semantic Markup:

●​ Focuses on the structure rather than appearance.


●​ Benefits:
○​ Better maintainability.
○​ Enhanced accessibility.
○​ Improved SEO (Search Engine Optimization).

4. Structure of HTML Documents:

●​ Starts with <!DOCTYPE html> to define the document type.

Common structure:​
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph.</p>
</body>
</html>

●​ Head contains metadata, styles, and scripts.


●​ Body contains visible content.

5. Quick Tour of HTML Elements:

●​ Headings: <h1> to <h6> define headings.


●​ Paragraphs & Divs: <p> for paragraphs, <div> for grouping.
●​ Links: <a href="url">Link Text</a>.
●​ Lists:
○​ Unordered: <ul>
○​ Ordered: <ol>
○​ Description: <dl>
●​ Images: <img src="image.jpg" alt="description">
●​ Character Entities:
○​ &lt; for <
○​ &gt; for >
○​ &copy; for ©

1
6. HTML5 Semantic Elements:

●​ <header>, <nav>, <main>, <section>, <article>, <aside>, <footer>.


●​ Enhance document structure and accessibility.

CSS (Chapter 4)
1. What is CSS?

●​ CSS (Cascading Style Sheets) describes how HTML elements are displayed.
●​ Can control fonts, colors, spacing, layouts, etc.

2. CSS Syntax:

selector {
property: value;
}

●​ Selectors target HTML elements.


●​ Declarations consist of properties and values.

3. Location of Styles:

●​ Inline: Within the HTML element (style="color: red;").


●​ Internal: Within <style> tags in the <head>.
●​ External: Separate .css file linked via <link>.

4. Selectors:

●​ Element Selector: Targets by tag (p {}).


●​ Class Selector: Targets by class (.className {}).
●​ ID Selector: Targets by ID (#idName {}).
●​ Attribute Selector: [type="text"] {}.
●​ Pseudo-classes: a:hover, :first-child.
●​ Pseudo-elements: ::before, ::after.

5. The Cascade & Specificity:

●​ Specificity Order: Inline > ID > Class > Element.


●​ Inheritance: Some properties inherit (e.g., color, font), while others don't (e.g., margins).

6. The Box Model:

●​ Consists of:
○​ Content
○​ Padding
○​ Border
○​ Margin

7. CSS Text Styling:

●​ Fonts: font-family, font-size, font-weight, font-style.


●​ Text Properties: text-align, text-decoration, line-height, letter-spacing.

2
Advanced CSS: Layout (Chapter 7)
1. Normal Flow:

●​ Default layout where block elements stack vertically and inline elements flow horizontally.

2. Positioning Elements:

●​ Static: Default.
●​ Relative: Offset from its normal position.
●​ Absolute: Positioned relative to nearest positioned ancestor.
●​ Fixed: Positioned relative to the viewport.

3. Floating Elements:

●​ Use float: left/right to position elements.


●​ Use clear: both to prevent elements from wrapping around floated items.

4. Constructing Multicolumn Layouts:

●​ Using floats, flexbox, or grid.

5. Responsive Design:

Media Queries:​
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}

●​ Flexible Grids: Using percentages.


●​ Viewport Meta Tag:​
<meta name="viewport" content="width=device-width, initial-scale=1.0">

6. Filters, Transitions, and Animations:

●​ Filters: filter: grayscale(100%);

Transitions:​
div {
transition: all 0.5s ease;
}
Animations:​
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
div {
animation: example 2s infinite;
}

7. CSS Frameworks & Preprocessors:

●​ Frameworks: Bootstrap, Foundation.


●​ Preprocessors: SASS, LESS.

3
JavaScript Extra Notes – Comprehensive Guide

1. Introduction to JavaScript

●​ Client-side scripting language executed by browsers.


●​ Processes on the client-side, improving user experience.
●​ Object-based language, enabling interaction with page elements.
●​ Works with HTML (structure) and CSS (style) to enhance behavior.
●​ Popular, lightweight, and case-sensitive.

2. JavaScript Coding
Embedded Script:​
<body>
<script>
// JavaScript code here
</script>
</body>
External Script:​
<body>
<script src="myScript.js"></script>
</body>

3. JavaScript Output
document.write(): Directly writes content to the HTML document.​
<script>
document.write("Hello World JavaScript!");
</script>​
Output:​
Hello World JavaScript!
innerHTML: Modifies the content of an HTML element.​
<p id="demo">Original Text</p>
<button onclick="changeText()">Change Text</button>

<script>
function changeText() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>​
Output after clicking the button:​
Hello World

4. JavaScript Alerts and Confirms

Alert Box:​
alert("This is an alert!");​
Displays a pop-up alert with a message.

Confirm Box:​
if (confirm("Press OK or Cancel")) {
alert("You pressed OK");
} else {
alert("You pressed Cancel");
}​
Pops up a confirmation box and acts based on user input.

5. Basic Data Types


4
●​ Number: Integers and floating-point numbers (e.g., 4, 16, 3.14).
●​ String: Sequence of characters (e.g., 'John', 'A').
●​ Boolean: true or false.
●​ Array: A list of values (e.g., [1, 2, 3]).
●​ Object: A collection of key-value pairs (e.g., { name: "John", age: 30 }).

6. Variables and Operators


Variable Declaration:​
var name = "John";
let age = 25;
const country = "Canada";
Operators:

○​ Arithmetic: +, -, *, /, %
○​ Relational: <, <=, >, >=, ==, !=
○​ Logical: &&, ||, !

7. Statements and Conditionals

●​ Statements: Instructions executed by the browser.

Conditional Statements:​
let income = 100000;
let rate = income < 100000 ? 0.15 : 0.35;
let payment = income - (income * rate);
console.log("Pay:", payment);​
Output:​
Pay: 65000

8. Loops
For Loop:​
for (let i = 0; i < 5; i++) {
console.log("count:", i);
}​
Output:​
count: 0
count: 1
count: 2
count: 3
count: 4

While Loop:​
let i = 0;
while (i < 5) {
console.log("Counter is", i);
i++;
}​
Output:​
Counter is 0
Counter is 1
Counter is 2
Counter is 3
Counter is 4

9. Arrays

5
Creating Arrays:​
var colors = ["red", "blue", "green"];
console.log(colors);​
Output:​
["red", "blue", "green"]

●​ Accessing Elements:​
console.log(colors[0]); // red

10. Functions
Function Declaration:​
function findTax(income, rate) {
return income * rate;
}

let tax = findTax(40000, 0.30);


console.log(tax);

Output:​
12000

Function Example (with Local Variables):​


function greet() {
let name = "John";
console.log("Hello,", name);
}
greet();
console.log(typeof name); // undefined (outside scope)

11. Events & Event Listeners


Event Example:​
<button onclick="displayDate()">The time is?</button>
<p id="demo"></p>

<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>​
Output: Displays the current date and time under the button when clicked.
Event Listener Approach:​
let myButton = document.getElementById("myBtn");
myButton.addEventListener("click", function() {
alert("Button clicked!");
});

12. Document Object Model (DOM)

●​ Introduction: The DOM represents the entire structure of an HTML document.

Accessing Elements:​
let title = document.getElementById("title");
title.innerHTML = "Updated Title";​
Modifies the element with the ID title.

6
Model-View-Controller (MVC) Pattern – Detailed Explanatory Notes

1. Introduction to MVC Architecture

●​ Origins:
○​ The Model-View-Controller (MVC) architecture dates back to the 1970s.
○​ It was introduced in the Xerox Smalltalk language.
○​ It predates object-oriented programming but aligns well with its principles.
●​ Purpose:
○​ The core objective of MVC is to separate concerns:
■​ Model: The data and business logic.
■​ View: The representation of the data (UI).
■​ Controller: The user input handler.
○​ This separation enhances modularity, reusability, and scalability.

2. Understanding the Problem MVC Solves

●​ Model Stability vs. View Volatility:


1.​ The Model (entity object) represents the core data and logic. It is stable and changes
infrequently.
2.​ The View (boundary object) is volatile. User interfaces evolve—combo boxes today,
textboxes tomorrow, or even a complete shift from desktop to web interfaces.
●​ Issues with Tight Coupling:
1.​ If the Model is tightly coupled to the View, every UI change would require modifications
in the core logic.
2.​ This makes the system rigid, reduces reusability, and increases maintenance overhead.
●​ Multi-View Synchronization:
1.​ Applications may support multiple views (e.g., desktop UI, mobile UI, web UI)
simultaneously.
2.​ A change in data from one view should immediately reflect across all other views.
●​ Key Challenges Addressed by MVC:
1.​ Presenting the same data in various formats across different windows.
2.​ Ensuring real-time synchronization between multiple views.
3.​ Allowing easy changes in the UI without affecting core functionality.
4.​ Supporting diverse interface styles co-existing with the same business logic.

3. MVC Architecture – The Solution

●​ Core Concept:
○​ MVC decouples the Model (data and logic) from the View (UI).
○​ In MVC, the View depends on the Model, but the Model is independent of the View.
○​ This one-way dependency ensures that the core logic remains untouched during UI
changes.
●​ Propagation Mechanism:
○​ A dependency mechanism ensures that when the Model changes, all registered Views
are notified and updated accordingly.

4. Components of MVC

4.1 Model

●​ Role:
○​ Acts as the central component containing core functionality and data.
○​ Responsible for business logic, data processing, and maintaining the application's state.

7
○​ It is aware of its dependent views and controllers but doesn’t handle their specific
details.
●​ Responsibilities:
○​ Manage data and rules.
○​ Notify views when data changes.
○​ Serve as the single source of truth for the application’s state.
●​ Example:
○​ In a shopping cart application, the Model would manage the list of items, their prices,
quantities, and total amount.

4.2 View

●​ Role:
○​ Responsible for the presentation layer.
○​ Displays data retrieved from the Model to the user.
●​ Responsibilities:
○​ Render data in the appropriate format (e.g., lists, tables, charts).
○​ Update the UI when the Model changes.
○​ Remain independent of business logic.
●​ Example:
○​ A graphical table showing products in the shopping cart or a list view on a mobile app.

4.3 Controller

●​ Role:
○​ Serves as the intermediary between the user and the system.
○​ Handles user input, interprets it, and communicates with the Model.
●​ Responsibilities:
○​ Process user commands (clicks, typing, gestures).
○​ Update the Model based on user actions.
○​ Decide which View to display based on the interaction.
●​ Example:
○​ When a user clicks “Add to Cart,” the Controller captures this event, updates the Model
by adding the item, and triggers a View update.

4.4 Propagation/Dependency Mechanism

●​ Purpose:
○​ Ensures real-time synchronization between the Model and all associated Views.
○​ When the Model data changes, it notifies all views to refresh and display the updated
data.
●​ Mechanisms Used:
○​ Observer Pattern: Views register themselves as observers to the model.
○​ Event Listeners/Handlers: Controllers listen for user events and update the model
accordingly.

5. Benefits of MVC Architecture

●​ Separation of Concerns: Each component focuses on a specific task.


●​ Reusability:
○​ Models can be reused across different applications or interfaces.
○​ Views can be redesigned without altering the core logic.
●​ Scalability:
○​ Supports multiple views and controllers interacting with the same model.
●​ Maintainability:
○​ Changes in one component (e.g., UI redesign) don’t ripple through the entire system.
●​ Testability:
○​ The Model can be tested independently of the View and Controller.

8
6. Real-World Examples of MVC

●​ Web Applications:
○​ Django (Python):
■​ Model: Database models.
■​ View: HTML templates.
■​ Controller: Views.py functions handling user requests.
○​ Ruby on Rails:
■​ Embraces MVC strictly with models, views, and controllers separated.
●​ Frontend Frameworks:
○​ AngularJS, React (with Flux/Redux), and Vue.js implement variations of MVC or
similar architectures.
●​ Desktop Applications:
○​ GUI-based applications like Java Swing or .NET often use MVC or its derivatives.

7. Conclusion

●​ The Model-View-Controller architecture remains one of the most effective design patterns for
building modular, scalable, and maintainable applications.
●​ By decoupling core logic from the user interface and input handling, it simplifies complex
applications and enhances the developer’s ability to maintain and scale systems efficiently.

Introduction to Server-Side Development with PHP – Beginner Notes

Chapter 11: Introduction to Server-Side Development

1. What is Server-Side Development?

●​ Client-Side vs. Server-Side Scripts:


○​ Client-Side Scripts: Executed by the user's browser (e.g., JavaScript).
○​ Server-Side Scripts: Executed on the server before sending content to the browser
(e.g., PHP).
●​ Why Use Server-Side Scripting?
○​ Generates dynamic content.
○​ Handles data storage and retrieval (e.g., databases).
○​ Provides enhanced security (since code runs on the server).
○​ Examples of Server-Side Languages:
■​ PHP, Python, Ruby on Rails, Node.js, ASP.NET, JSP, Perl.

2. Quick Tour of PHP

●​ What is PHP?
○​ PHP stands for Hypertext Preprocessor.
○​ A widely-used open-source server-side scripting language.
○​ Embedded within HTML to create dynamic web pages.

Basic PHP Syntax:​


<?php
echo "Hello, World!";
?>

○​ <?php ... ?> tags enclose PHP code.


○​ echo outputs content to the browser.

9
PHP Comments:
Single-line comment:​
// This is a single-line comment
# This is also a single-line comment
Multi-line comment:​
/*
This is a
multi-line comment
*/

Variables, Data Types, and Constants:

●​ Variables:
○​ Start with a $ sign.
○​ Dynamically typed (no need to specify data type).

$count = 42;
$name = "John";

●​ Data Types:
○​ Boolean: true or false
○​ Integer: Whole numbers (e.g., 4, 16)
○​ Float: Decimal numbers (e.g., 3.14)
○​ String: Text (e.g., "Hello")
○​ Array: A collection of values
○​ Object: Instance of a class
●​ Constants:
○​ Defined using define() and written in uppercase.

define("DATABASE_LOCAL", "localhost");
echo DATABASE_LOCAL; // Outputs: localhost

Writing to Output:

●​ echo:​
echo "Hello World";
●​ Concatenation:

Combine strings using the period (.) operator.

$username = "Ricardo";
echo "Hello, " . $username; // Outputs: Hello, Ricardo

●​ printf:
○​ Used for formatted output.
●​ printf("%s is %d years old.", "John", 25); // Outputs: John is 25 years old.

3. Program Control

Conditional Statements:
if...else:​
$hourOfDay = 10;
if ($hourOfDay > 6 && $hourOfDay < 12) {
$greeting = "Good Morning";
} elseif ($hourOfDay == 12) {
$greeting = "Good Noon Time";
} else {
$greeting = "Good Afternoon or Evening";
10
}
echo $greeting;

switch...case:​
$artType = "PT";
switch ($artType) {
case "PT":
$output = "Painting";
break;
case "SC":
$output = "Sculpture";
break;
default:
$output = "Other";
}
echo $output; // Outputs: Painting

Loops:
while loop:​
$count = 0;
while ($count < 5) {
echo $count;
$count++;
}
do...while loop:​
$count = 0;
do {
echo $count;
$count++;
} while ($count < 5);
for loop:​
for ($count = 0; $count < 10; $count += 2) {
echo $count;
}

Alternate Syntax for Control Structures:


Often used in templates mixing PHP and HTML.​
<?php if ($userStatus == "loggedin") : ?>
<a href="account.php">Account</a>
<a href="logout.php">Logout</a>
<?php else : ?>
<a href="login.php">Login</a>
<a href="register.php">Register</a>
<?php endif; ?>

Including Files:
include and require to reuse code.​
include 'header.php';
require 'config.php';

4. Functions

Basic Function Syntax:


Defining and Calling a Function:​
function getNiceTime() {
return date("H:i:s");
}
echo getNiceTime(); // Outputs: current system time

11
Return Type Declarations:
Specify the return type explicitly.​
function mustReturnString(): string {
return "hello";
}

Parameters:
Passing Parameters:​
function greet($name) {
return "Hello, " . $name;
}
echo greet("Alice"); // Outputs: Hello, Alice
Default Parameter Values:​
function greet($name = "Guest") {
return "Hello, " . $name;
}
echo greet(); // Outputs: Hello, Guest

●​ Passing by Reference:
○​ Allows modifying the original variable.

function addOne(&$number) {
$number++;
}

$count = 5;
addOne($count);
echo $count; // Outputs: 6

Variable Scope:
Global vs. Local Variables:​
$globalVar = "I am global";

function testScope() {
global $globalVar;
echo $globalVar;
}
testScope(); // Outputs: I am global

5. Summary

●​ PHP is a powerful server-side scripting language used for creating dynamic web applications.
●​ It integrates seamlessly with HTML and offers robust features like variables, control structures,
functions, and more.
●​ Key Concepts Covered:
○​ Server-side scripting and its benefits.
○​ PHP basics: syntax, variables, data types, and constants.
○​ Program control: conditionals and loops.
○​ Functions and their parameters.
○​ Variable scope and best practices.

With this foundational knowledge, you can start building dynamic and interactive PHP-based web
applications!

12
PHP Arrays and Superglobals – Beginner Notes

Chapter 12: PHP Arrays and Superglobals

1. Arrays in PHP

Defining Arrays:

●​ Arrays in PHP are used to store multiple values in a single variable.

Syntax:​
$days = array("Mon", "Tue", "Wed", "Thu", "Fri");
// Alternate syntax
$days = ["Mon", "Tue", "Wed", "Thu", "Fri"];

Associative Arrays:

●​ Arrays with named keys.​


$person = array("name" => "John", "age" => 30);

Multidimensional Arrays:
Arrays containing one or more arrays.​
$cart = array(
array("id" => 37, "title" => "Burial at Ornans", "quantity" => 1),
array("id" => 345, "title" => "The Death of Marat", "quantity" => 1),
array("id" => 63, "title" => "Starry Night", "quantity" => 1)
);

Iterating Through Arrays:


While Loop:​
$i = 0;
while ($i < count($days)) {
echo $days[$i] . "<br>";
$i++;
}
Do-While Loop:​
$i = 0;
do {
echo $days[$i] . "<br>";
$i++;
} while ($i < count($days));
For Loop:​
for ($i = 0; $i < count($days); $i++) {
echo $days[$i] . "<br>";
}
Foreach Loop:​
// Iterating through values
foreach ($days as $value) {
echo $value . "<br>";
}

// Iterating through keys and values


foreach ($days as $key => $value) {
echo "Day[$key] = $value<br>";
}

Adding and Deleting Elements:

13
Add an Element:​
$days[] = "Sat"; // Adds to the end
$days[5] = "Sun"; // Adds at specific index

●​ Delete an Element:​
unset($days[2]); // Removes the element at index 2

Array Sorting:

●​ Sort an Array:​
sort($days);

More Array Operations:


Useful array functions:​
array_keys($array); // Get all keys
array_values($array); // Get all values
array_rand($array); // Get random key
array_reverse($array); // Reverse array
shuffle($array); // Shuffle array
in_array("value", $array); // Check if value exists

2. Superglobal Arrays

●​ Superglobals are built-in arrays that are always accessible.

Common Superglobals:

●​ $_GET - Data sent via URL parameters.


●​ $_POST - Data sent via HTTP POST.
●​ $_REQUEST - Combines $_GET, $_POST, and $_COOKIE.
●​ $_SERVER - Information about the server and request.
●​ $_FILES - Data about uploaded files.
●​ $_SESSION - Session variables.
●​ $_COOKIE - Cookies sent by the browser.
●​ $GLOBALS - All global variables.

Example:
echo $_SERVER['HTTP_USER_AGENT']; // Displays user's browser info

3. Working with $_GET and $_POST


Accessing Form Data:​
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'] ?? 'Guest';
echo "Hello, $username";
}
Using isset() to Check Data:​
if (isset($_POST['username'])) {
echo $_POST['username'];
}
Accessing Form Array Data:​
<form method="get">
<input type="checkbox" name="day[]" value="Monday">Monday
<input type="checkbox" name="day[]" value="Tuesday">Tuesday
<input type="submit">

14
</form>​
echo "You selected: ";
foreach ($_GET['day'] as $day) {
echo $day . "<br>";
}

●​ Sanitizing Input:​
$name = htmlspecialchars($_POST['name']);

4. Working with $_SERVER

●​ Common $_SERVER Keys:


○​ $_SERVER['HTTP_USER_AGENT'] – Browser info.
○​ $_SERVER['REQUEST_METHOD'] – Request method (GET, POST).
○​ $_SERVER['HTTP_REFERER'] – URL of the referring page.

Example:​
$browser = $_SERVER['HTTP_USER_AGENT'];
echo "You are using: $browser";

5. Working with $_FILES


HTML Form for File Upload:​
<form enctype="multipart/form-data" method="post">
<input type="file" name="file1">
<input type="submit">
</form>
Handling File Upload in PHP:​
if ($_FILES['file1']['error'] == UPLOAD_ERR_OK) {
$destination = "./uploads/" . $_FILES['file1']['name'];
move_uploaded_file($_FILES['file1']['tmp_name'], $destination);
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
Validating File Type and Size:​
$validTypes = array("image/jpeg", "image/png");
if (in_array($_FILES['file1']['type'], $validTypes)) {
echo "Valid file type.";
} else {
echo "Invalid file type.";
}

6. Reading and Writing Files in PHP

Stream Access:
Reading a File:​
$file = fopen("example.txt", "r");
while (!feof($file)) {
echo fgets($file) . "<br>";
}
fclose($file);
Writing to a File:​
$file = fopen("example.txt", "w");

15
fwrite($file, "Hello World");
fclose($file);

In-Memory Access:
Read Entire File:​
$content = file_get_contents("example.txt");
echo $content;

●​ Write Entire File:​


file_put_contents("example.txt", "New content");

7. Summary

●​ PHP arrays can be indexed, associative, or multidimensional.


●​ Superglobal variables like $_GET, $_POST, and $_FILES allow easy data handling.
●​ Always sanitize and validate user input.
●​ PHP offers powerful tools to read/write files and manage file uploads.

With these fundamentals, you can now build dynamic and data-driven PHP applications!

Working with Databases - Detailed Explanatory Notes

1. Databases and Web Development

Importance of Databases

●​ Databases help separate dynamic content from static structure.


●​ Essential for maintaining data consistency and integrity in web applications.

How Websites Use Databases

●​ Store user data, product information, transactions, etc.


●​ Dynamic websites fetch data from databases to display customized content.

Database Design Principles

●​ Tables: Structured collection of related data.


●​ Foreign Keys: Link tables to maintain relationships.

Diagramming Tables Example

●​ Users Table
○​ UserID (Primary Key)
○​ Name
○​ Email
●​ Orders Table
○​ OrderID (Primary Key)
○​ UserID (Foreign Key)
○​ OrderDate

16
2. SQL (Structured Query Language)

Basic SQL Statements

●​ SELECT: Retrieve data.​


SELECT * FROM Users;​
Expected Output: All records from the Users table.
●​ WHERE Clause: Filter data.​
SELECT * FROM Users WHERE Name = 'John';​
Expected Output: All users named John.

JOIN: Combine data from multiple tables.​


SELECT Users.Name, Orders.OrderDate FROM Users

●​ JOIN Orders ON Users.UserID = Orders.UserID;​


Expected Output: List of users with their order dates.

Data Manipulation Statements

●​ INSERT​
INSERT INTO Users (Name, Email) VALUES ('Alice', '[email protected]');
●​ UPDATE​
UPDATE Users SET Email = '[email protected]' WHERE Name = 'Alice';
●​ DELETE​
DELETE FROM Users WHERE Name = 'Alice';

Transactions

Group multiple queries into a single unit.​


START TRANSACTION;

INSERT INTO Orders (UserID, OrderDate) VALUES (1, NOW());

●​ COMMIT;​
Expected Output: New order inserted only if all queries succeed.

3. NoSQL Databases

Types of NoSQL Databases

●​ Key-Value Stores: Simple key-value pairs.


○​ Example: { "user123": "John Doe" }
●​ Document Stores: Store structured documents (e.g., JSON).

Example:​
{

"UserID": "user123",

"Name": "John Doe",

"Orders": ["order1", "order2"]

●​ Column Stores: Store data in columns rather than rows.

17
4. Database APIs

PHP MySQL Extensions

●​ MySQL Extension: Older, deprecated.


●​ MySQLi Extension: Improved, supports both procedural and OOP.
●​ PDO (PHP Data Objects): Database-independent abstraction layer.

Connecting to MySQL

MySQLi Procedural​
$connection = mysqli_connect("localhost", "user", "pass", "database");

if (!$connection) {

die("Connection failed: " . mysqli_connect_error());

PDO Object-Oriented​
try {

$pdo = new PDO("mysql:host=localhost;dbname=database", "user", "pass");

} catch (PDOException $e) {

die($e->getMessage());

5. Managing a MySQL Database

Command-Line Interface

●​ Connecting to MySQL​
mysql -h localhost -u user -p
●​ Import SQL File​
mysql -u user -p database < file.sql

GUI Tools

●​ phpMyAdmin: Web-based interface.


●​ MySQL Workbench: Desktop application for MySQL management.

6. Accessing MySQL in PHP

Basic Steps

1.​ Connect to the database.


2.​ Handle connection errors.
3.​ Execute SQL queries.
4.​ Process results.
5.​ Close the connection.

Example

$pdo = new PDO("mysql:host=localhost;dbname=bookcrm", "user", "pass");


18
$sql = "SELECT * FROM Categories ORDER BY CategoryName";

$result = $pdo->query($sql);

while ($row = $result->fetch()) {

echo $row['ID'] . " - " . $row['CategoryName'] . "<br/>";

$pdo = null;

Expected Output: List of categories sorted by name.

Using Prepared Statements

Positional Placeholders​
$sql = "INSERT INTO Users (Name, Email) VALUES (?, ?)";

$stmt = $pdo->prepare($sql);

●​ $stmt->execute(['John', '[email protected]']);

Named Placeholders​
$sql = "INSERT INTO Users (Name, Email) VALUES (:name, :email)";

$stmt = $pdo->prepare($sql);

●​ $stmt->execute([':name' => 'John', ':email' => '[email protected]']);

7. Sample Database Techniques

Search and Results Page

●​ Input a search term and fetch matching records.

Editing a Record

●​ Retrieve, modify, and save changes to a record.

Storing Files in Database

●​ BLOB (Binary Large Object) to store images or files.

8. Case Study Schemas

Example Databases

●​ Travel Photo Sharing Database


●​ Art Database
●​ Book CRM Database

9. Key Terms

19
●​ DDL (Data Definition Language): Create/modify tables.
●​ DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE.
●​ Transactions: Ensure data consistency.
●​ Primary Key: Unique identifier.
●​ Foreign Key: Link between tables.
●​ BLOB: Store binary data.
●​ PDO: PHP Data Objects.
●​ NoSQL: Non-relational databases.

What is Cross-Browser Compatibility?

●​ Cross-Browser Compatibility refers to how a website appears and functions consistently across
different web browsers (like Chrome, Firefox, Safari) and their versions.​

●​ Issues occur when a website looks or behaves differently on different browsers due to:​

○​ Browser differences and versions.​

○​ Operating systems (Windows, MacOS, Linux).​

○​ Hardware (laptops, phones, tablets).​

○​ Screen sizes and resolutions.​

○​ Variations in HTML, CSS, JavaScript support.​

Common Cross-Browser Compatibility Issues

1.​ HTML/CSS Code Validation Errors: Inconsistent code that may not render correctly in all
browsers.​

2.​ Outdated Browser Detection: Users running old browser versions may face display or
functionality issues.​

3.​ Missing CSS Resets: Browsers apply default styles differently; without a reset, styles may vary.​

4.​ Layout Compatibility Issues: Responsive designs may not adapt well on all devices.​

5.​ DOCTYPE Errors: Missing DOCTYPE can cause inconsistent rendering.​

6.​ Vendor-Specific Functions: Browser-specific code that doesn’t work elsewhere.​

7.​ Lack of Real Device Testing: Relying only on simulators can miss real-world issues.

How to Fix Cross-Browser Compatibility Issues

1.​ Use Cross-Browser Friendly Libraries:​

20
○​ Frameworks like AngularJS, Bootstrap, jQuery, and Animate.css are designed for
compatibility across browsers.​

2.​ Use Separate Stylesheets for Different Browsers:​

○​ Create conditional stylesheets tailored for specific browsers to handle unique quirks.​

3.​ Perform Cross-Browser Testing:​

○​ Use tools like LambdaTest or BrowserStack to test how your site behaves on multiple
browsers and devices.​

4.​ Validate Code:​

○​ Use tools from W3C to validate HTML/CSS to avoid syntax errors.​

5.​ Apply CSS Resets:​

○​ Reset browser-specific styles to ensure consistency using tools like Normalize.css.​

6.​ Ensure Layout Compatibility:​

○​ Use flexbox or grid systems in CSS, and avoid hardcoding sizes.​

○​ Implement responsive designs using media queries.

Best Practices to Avoid Compatibility Issues

●​ Start development on widely used browsers like Firefox or Chrome.​

●​ Use standardized HTML, CSS, and JavaScript.​

●​ Link CSS files at the top of your HTML and JavaScript files at the bottom for better page
loading.​

●​ Use Conditional Statements to target specific browsers.​

●​ Regularly test on real devices instead of just emulators.

Using Conditional Statements


Internet Explorer (IE) Only: Apply specific styles to older IE versions.​

<!--[if lt IE 9]>
<link rel="stylesheet" href="ie.css">
<![endif]-->

Firefox Only: Use @-moz-document to apply Firefox-specific styles.​



@-moz-document url-prefix() {
h1 { color: red; }
}
WebKit Browsers (Chrome, Safari):​

@media screen and (-webkit-min-device-pixel-ratio:0) {
body { color: green; }
}

21
Useful Tools & Resources

●​ W3C Validator: Validate HTML/CSS code. W3C Validator


●​ LambdaTest: Cross-browser testing tool. LambdaTest
●​ BrowserStack: Real device and browser testing. BrowserStack

📖 Introduction to Object-Oriented Programming (OOP) in PHP


Object-Oriented Programming (OOP) is a programming paradigm based on "objects". In PHP, OOP
helps to organize code efficiently, making it reusable and easier to maintain.

Key OOP Concepts:

●​ Object: An instance of a class, representing a real-world entity.


●​ Class: A blueprint for creating objects, defining properties and behaviors.

🏗️ Defining Classes and Creating Objects in PHP


Defining a Class: Use the class keyword to define a class.​

class Artist {
public $firstName;
public $lastName;
public $birthDate;
public $birthCity;
public $deathDate;
}

Creating (Instantiating) an Object: Use the new keyword.​


$picasso = new Artist();
$dali = new Artist();
Assigning Properties: Access and modify properties using ->.​
$picasso->firstName = "Pablo";
$picasso->lastName = "Picasso";
$picasso->birthCity = "Malaga";

🚀 Constructors
A constructor is a special method that initializes objects when they are created.t

class Artist {
public $firstName;
public $lastName;
public $birthCity;
public $birthDate;
public $deathDate;

function __construct($firstName, $lastName, $city, $birth, $death = null) {


$this->firstName = $firstName;
$this->lastName = $lastName;
$this->birthCity = $city;
$this->birthDate = $birth;
22
$this->deathDate = $death;
}
}

Using Constructor:​
$picasso = new Artist("Pablo", "Picasso", "Malaga", "Oct 25, 1881", "Apr 8, 1973");

⚙️ Methods in PHP Classes


Methods define what actions an object can perform.

class Artist {
public $firstName;
public $lastName;

public function outputAsTable() {


echo "<table><tr><td>$this->firstName</td><td>$this->lastName</td></tr></table>";
}
}

$picasso = new Artist("Pablo", "Picasso");


$picasso->outputAsTable();

🔒 Visibility: Public, Private, Protected


●​ Public: Accessible from anywhere.
●​ Private: Accessible only within the class.
●​ Protected: Accessible within the class and subclasses.

class Artist {
private $birthDate;

public function setBirthDate($date) {


$this->birthDate = $date;
}

public function getBirthDate() {


return $this->birthDate;
}
}

📏 Static Members and Constants


Static Properties/Methods: Shared among all instances of the class. Use static keyword.​

class Artist {
public static $artistCount = 0;
public function __construct() {
self::$artistCount++;
}
}

23
echo Artist::$artistCount;
Class Constants: Fixed values that don’t change.​
class Artist {
const EARLIEST_DATE = 'January 1, 1200';
}
echo Artist::EARLIEST_DATE;

🛡️ Encapsulation
Encapsulation is about hiding internal details of objects and only exposing necessary information.

Use getters and setters to access private properties.​



class Artist {

private $name;

public function setName($name) {


$this->name = $name;
}

public function getName() {


return $this->name;
}
}

🏛️ Inheritance
Inheritance allows one class to inherit properties and methods from another.

class Art {
public $title;
}
class Painting extends Art {
public $medium;
}

$guernica = new Painting();


$guernica->title = "Guernica";
$guernica->medium = "Oil on canvas";

🧩 Polymorphism
Polymorphism allows objects to take many forms. A subclass can override methods of its parent class.

class Art {
public function display() {
echo "Displaying Art";
}
}

class Painting extends Art {


public function display() {
echo "Displaying Painting";
24
}
}

$artwork = new Painting();


$artwork->display(); // Outputs: Displaying Painting

🔗 Interfaces
An interface defines a contract that classes must follow but doesn’t provide the actual implementation.

interface Viewable {
public function getSize();
public function getPNG();
}

class Painting implements Viewable {


public function getSize() {
return "20x30";
}

public function getPNG() {


return "image.png";
}
}

🧮 Unified Modeling Language (UML)


●​ UML diagrams visually represent classes, their relationships, and interactions.
●​ They are used in Object-Oriented Design to map out class structures before coding.

📋 Key Terms
●​ Class: Blueprint for objects.
●​ Object: Instance of a class.
●​ Constructor: Special method to initialize objects.
●​ Encapsulation: Hiding internal details of a class.
●​ Inheritance: Reusing code from another class.
●​ Polymorphism: Same method behaving differently based on the object.
●​ Interface: A contract for classes to implement.
●​ Static Member: A property/method shared across all instances.
●​ Getter/Setter: Methods to access or modify private properties.​

1. Drag & Drop API

🔑 What is Drag & Drop?


●​ Drag: Selecting and moving an object.​

●​ Drop: Placing the object in a new location.

In HTML, any element can be draggable and droppable.

25
🛠️ Code Example – Basic Drag & Drop
<!DOCTYPE html>
<html>
<head>
<style>
#div1 {
width: 350px;
height: 70px;
padding: 10px;
border: 1px solid #aaaaaa;
}
</style>
</head>
<body>

<p>Drag the image into the rectangle:</p>

<!-- Drop Area -->


<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div><br>

<!-- Draggable Image -->


<img id="drag1" src="https://via.placeholder.com/150" draggable="true" ondragstart="drag(event)"
width="150" height="69">

<script>
function allowDrop(ev) {
ev.preventDefault(); // Allow dropping
}

function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id); // Set data to be dragged
}

function drop(ev) {
ev.preventDefault(); // Prevent default browser handling
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data)); // Append dragged item
}
</script>

</body>
</html>

🎯 Expected Output:
●​ A rectangle and an image will be displayed.
●​ You can drag the image and drop it into the rectangle.

⚡ 2. Event Handlers for Drag & Drop


Event Description

26
gstart when dragging starts (drag(event) is called).

gover when dragging over the drop area (must use preventDefault).

p when the draggable element is dropped in the drop area.

g ontinuously while dragging the element.

gend when the drag operation ends (on release).

genter when a draggable enters a drop zone.

gleave when a draggable leaves a drop zone.

gexit when the dragging operation exits the element boundaries.

🔄 3. Drag & Drop Event Flow


Here's how events are triggered in a typical drag-and-drop operation:

1.​ dragstart ➔ User starts dragging.


2.​ drag ➔ While the element is being dragged.
3.​ dragover ➔ The dragged item moves over the drop zone.
4.​ dragenter ➔ The draggable enters the drop zone.
5.​ drop ➔ User drops the element.
6.​ dragend ➔ The drag operation ends.

🛡️ 4. Advanced Drag & Drop – Multiple Elements


This example allows multiple items to be dragged and dropped into a common drop zone.

<!DOCTYPE html>
<html>
<head>
<style>
.dropzone {
width: 350px;
height: 150px;
padding: 10px;
border: 2px dashed #aaaaaa;
}

.draggable {
width: 100px;
height: 50px;
margin: 10px;
background-color: lightblue;
cursor: move;
}
</style>
</head>
<body>
27
<h3>Drag the boxes into the drop zone:</h3>

<div class="draggable" id="drag1" draggable="true" ondragstart="drag(event)">Box 1</div>


<div class="draggable" id="drag2" draggable="true" ondragstart="drag(event)">Box 2</div>

<div class="dropzone" ondrop="drop(event)" ondragover="allowDrop(event)">


Drop Here
</div>

<script>
function allowDrop(ev) {
ev.preventDefault();
}

function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>

</body>
</html>

🎯 Expected Output:
●​ Two draggable boxes (Box 1 and Box 2) and a drop zone.
●​ Drag either box into the drop zone.

🌐 5. Address Same Origin Policy


The Same-Origin Policy (SOP) restricts how documents/scripts from one origin can interact with
resources from another origin, providing a security layer.

🔑 Origin Components:
1.​ Protocol/Scheme: http, https
2.​ Domain/Hostname: www.ryerson.ca
3.​ Port: :80, :443 (default for HTTP/HTTPS)

Same Origin means all three components match.

🛡️ Why Same-Origin Matters?


●​ Prevents malicious websites from accessing your session or data on another site.​

●​ Example: Protects your bank login session from being accessed by other tabs/websites.

28
🚀 Cross-Origin Resource Sharing (CORS)
●​ CORS allows specific cross-origin interactions.​

●​ A server can use headers like Access-Control-Allow-Origin to permit external domains.​

💡 Example:​
A frontend on https://example.com calling an API on https://api.example.com would need
CORS enabled.

1. Web Applications Design


1.1 Layered Architectures

●​ 2-Layered Architecture:
○​ Presentation Layer: User Interface (UI) with technologies like HTML, CSS, JavaScript.
○​ Database Layer: Data storage using databases like MySQL, MongoDB.
●​ 3-Layered Architecture:
○​ Presentation Layer: UI displayed to users.
○​ Application Layer: Business logic with frameworks (e.g., Tomcat, WebLogic).
○​ Database Layer: Data storage and retrieval.
●​ Example Flow:
○​ User submits a form (Presentation Layer).
○​ Server processes data (Application Layer).
○​ Data is stored/retrieved (Database Layer).
●​ 4-Layered Architecture:
○​ Adds an Enterprise Layer to separate application logic and data access logic for better
scalability and security.

1.2 Design Patterns

1.2.1 Model-View-Controller (MVC)

●​ Model: Represents data and business logic.


●​ View: UI that presents data to users.
●​ Controller: Handles user input, updates Model and View.

Advantages:

●​ Modular code for better maintainability.


●​ Easier to test and debug.

Disadvantages:

●​ Can become complex.


●​ High learning curve.

Example Flow:

1.​ User clicks a button (View).


2.​ Controller processes the action.
3.​ Model updates data.
4.​ View reflects updated data.

29
1.2.2 Model-View-ViewModel (MVVM)

●​ Model: Raw data.


●​ View: UI elements.
●​ ViewModel: Intermediary that binds Model data to View.

Advantages:

●​ Improved maintainability and testability.


●​ Automatic data binding between View and ViewModel.

Disadvantages:

●​ Complex data bindings.


●​ Less suitable for small applications.

Example Flow:

1.​ User enters data in UI (View).


2.​ ViewModel automatically updates with data.
3.​ Model reflects changes.

2. Geolocation API

The Geolocation API allows web applications to access the user's geographical location.

2.1 Key Methods:

●​ navigator.geolocation.getCurrentPosition(successCallback, errorCallback)
○​ Gets the user’s current position.
●​ navigator.geolocation.watchPosition(successCallback, errorCallback)
○​ Continuously monitors position changes.
●​ navigator.geolocation.clearWatch(watchID)
○​ Stops watching the position.

2.2 Example Code:


<!DOCTYPE html>
<html>
<body>

<h2>Geolocation Example</h2>
<p id="demo">Click the button to get your location:</p>

<button onclick="getLocation()">Get Location</button>

<script>
var x = document.getElementById("demo");

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +

30
"<br>Longitude: " + position.coords.longitude;
}

function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable.";
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred.";
break;
}
}
</script>

</body>
</html>

Expected Output:

●​ User clicks "Get Location".


●​ Browser asks for permission.
●​ On approval, displays:
○​ Latitude: [value]
○​ Longitude: [value]

2.3 Geolocation Position Object:

●​ Coordinates:
○​ latitude – Decimal degrees.
○​ longitude – Decimal degrees.
○​ altitude – Height above sea level.
○​ accuracy – Accuracy of latitude and longitude.
○​ altitudeAccuracy – Accuracy of altitude.
○​ heading – Direction of travel.
○​ speed – Current speed.

2.4 Display Location on Google Maps:


function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=" + latlon +
"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";
document.getElementById("mapholder").innerHTML = "<img src='" + img_url + "'>";
}

Expected Output:

●​ A static map image showing the user’s location.

3. Conclusion

●​ Layered Architectures help structure web applications for scalability and maintainability.
31
●​ MVC and MVVM patterns provide organized methods for handling data and UI interactions.
●​ Geolocation API allows real-time location tracking in web applications with features like error
handling and map integration.

Overview of JavaScript Frameworks:

JavaScript frameworks help organize and streamline web application development by providing structured
ways of managing code. Popular frameworks include:

●​ Ember: Enforces a structured approach using the MVC (Model-View-Controller) pattern.


●​ Angular: Similar MVC-like structure, maintained partially by Google, and useful in building
Single-Page Applications (SPAs).
●​ React: Developed by Facebook, focuses only on the View component, unlike Ember and Angular.​

Common JavaScript stacks include:

●​ LAMP: Linux, Apache, MySQL, PHP.


●​ MEAN: MongoDB, Express, Angular, Node.js.

Node.js:

Node.js is a JavaScript runtime environment allowing developers to run JavaScript server-side. It's
event-driven, single-threaded, and uses asynchronous, non-blocking I/O, suitable for real-time,
push-based applications.

Comparison:

●​ Traditional frameworks (like Apache/PHP) use a blocking, multi-threaded architecture.


Threads wait for I/O operations to complete, consuming resources.​

●​ Node.js uses a single-thread, event-driven architecture, where a single thread handles many
requests using event loops. This leads to higher efficiency in handling multiple simultaneous
connections.​

Sample Node.js HTTP server code:

var http = require('http');

var server = http.createServer(function (request, response) {


response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello this is our first node.js application\n");
response.end();
});

server.listen(7000, "localhost");
console.log("Server running at http://127.0.0.1:7000/");

32
Here's a line-by-line explanation of the Node.js code:

✅ Line 1:
var http = require('http');

●​ This line imports Node.js's built-in http module, which allows you to
create HTTP servers and handle requests/responses.

✅ Line 2:
var server = http.createServer(function (request, response) {

●​ This line creates a new HTTP server using http.createServer().​

●​ It takes a callback function with two parameters:​

○​ request: contains information about the incoming HTTP request.


○​ response: used to send data back to the client (browser).

✅ Line 3:
response.writeHead(200, {"Content-Type": "text/plain"});

●​ Sets the HTTP status code to 200 (OK) and response headers.
●​ "Content-Type": "text/plain" means the server will return plain text
(not HTML or JSON).

✅ Line 4:
response.write("Hello this is our first node.js application\n");

●​ This writes the actual response content (text) to be sent to the client.​

✅ Line 5:
response.end();

●​ Ends the response and tells the server it's done sending data.
●​ No more data can be written after calling end().

✅ Line 6:
});

●​ Closes the callback function passed to http.createServer().

✅ Line 7:
server.listen(7000, "localhost");

●​ Tells the server to start listening for requests on:​

○​ Port 7000 of the


○​ localhost (i.e., your own machine).

33
✅ Line 8:
console.log("Server running at http://127.0.0.1:7000/");

●​ Logs a message to the terminal so you know the server is running and
which address to open in your browser.

🧠 Summary: This script sets up a basic Node.js server that:


●​ Listens on port 7000,
●​ Responds to any HTTP request with plain text saying:​

“Hello this is our first node.js application”

Use cases demonstrated:

●​ Basic HTTP server


●​ Serving static files
●​ Real-time chat applications (using WebSockets)

MongoDB:
MongoDB is a document-oriented NoSQL database system. Unlike relational databases, MongoDB
stores data in flexible, JSON-like documents.

MongoDB Key Terms:

●​ Collection: Similar to tables in SQL.


●​ Document: Similar to rows in SQL; stored as JSON/BSON.
●​ Field: Similar to columns in SQL tables.
●​ Nested Documents: Documents embedded within other documents.

Example - Comparison with Relational Databases:

SQL Example:​
SELECT * FROM students WHERE age > 20;
MongoDB Equivalent:​
db.students.find({ age: { $gt: 20 } });
Running MongoDB Shell Example:
mongo

Accessing MongoDB in Node.js:

●​ Use the official MongoDB driver: mongodb.github.io/node-mongodb-native


●​ Use an ORM like Mongoose for easier database-object interactions.

Angular (AngularJS):

Angular is a popular, open-source JavaScript framework for developing Single Page Applications (SPAs).
It's part of the MEAN stack but can function independently.

Features:

34
●​ MVC (Model-View-Controller) architecture.
●​ Maintained by Google.
●​ Suitable for creating interactive and dynamic SPAs.

AngularJS vs Angular 2+:

●​ AngularJS uses JavaScript.


●​ Angular 2+ can use JavaScript, TypeScript, or Dart (TypeScript preferred).

Simple AngularJS Example:

<html ng-app>
<body>
<div ng-controller="myController">
{{message}}
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
<script>
function myController($scope) {
$scope.message = "Hello, Angular!";
}
</script>
</body>
</html>

Here's a line-by-line explanation of your AngularJS code:

✅ Line 1:
<html ng-app>

●​ ng-app is a directive that tells AngularJS: “This is the root of an


AngularJS application.”
●​ It initializes the app and links the AngularJS framework to this HTML
document.
●​ Angular automatically bootstraps (starts) the app from here.

✅ Line 2:
<body>

●​ Starts the HTML body section where the content of the page will go.

✅ Line 3:
<div ng-controller="myController">

●​ Declares a controller named myController for this <div>.


●​ This means any AngularJS expressions or data inside this <div> will be
managed by myController.

✅ Line 4:
35
{{message}}

●​ This is an AngularJS expression (also called "interpolation").


●​ Angular evaluates {{message}} and replaces it with the value of
$scope.message from the controller.
●​ In this case, it will display:​
"Hello, Angular!"

✅ Line 5:
</div>

●​ Closes the <div> that uses the controller.

✅ Line 6:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>

●​ Imports the AngularJS library (version 1.7.9) from Google's CDN.


●​ This is essential to use AngularJS features like ng-app, ng-controller,
and {{}}.

✅ Line 7–10:
<script>
function myController($scope) {
$scope.message = "Hello, Angular!";
}
</script>

●​ This defines the controller logic.


●​ myController is a JavaScript function that AngularJS treats as a
controller.
●​ It uses $scope, an AngularJS object that connects the controller and the
view.

Inside the controller:​


$scope.message = "Hello, Angular!";

●​ sets a variable named message, which is then used in the view with
{{message}}.

✅ Line 11:
</body>

●​ Closes the body of the HTML page.

✅ Line 12:
</html>

●​ Closes the HTML document.

🧠 In Summary: This is a minimal AngularJS app that:


36
●​ Loads AngularJS,
●​ Declares an app using ng-app,
●​ Uses a controller (myController) to set a message,
●​ Displays the message using {{message}}.

When run in a browser, you'll see:

Hello, Angular!

Important Concepts and Terminologies:

●​ Build Tools: Software used to automate compiling and building applications (e.g., Webpack,
Gulp).
●​ Commodity Servers: Standardized hardware that can be easily replaced or upgraded.
●​ DIRT (Data-Intensive Real-Time): Applications requiring real-time data processing.
●​ Full-Duplex: Communication protocol where both ends send/receive simultaneously.
●​ Failover Clustering: Ensuring continuous availability by switching to a standby server upon
failure.
●​ Sharding: Splitting database collections into smaller, more manageable pieces.
●​ Push-Based Web Apps: Server initiates communication to clients.
●​ Single-Page Applications (SPAs): Web applications that dynamically rewrite the current page
without loading entire new pages.
●​ WebSockets: Protocol allowing two-way interactive communication between client and server.

Summary (Quick Review):

●​ JavaScript frameworks help organize development and simplify complex tasks.


●​ Node.js: Single-thread, non-blocking I/O, ideal for real-time apps.
●​ MongoDB: Document-based NoSQL database system, flexible schema.
●​ Angular: Front-end framework ideal for SPAs, MVC structure, maintained by Google.

📌 1. Introduction to AngularJS
●​ What: A client-side JavaScript framework for building dynamic web apps.​

●​ Key Features:​

○​ Single Page Application (SPA)


○​ Extended HTML via directives
○​ Data-binding, MVC architecture
○​ Cross-browser compatibility
●​ History: Developed by Google in 2010; Latest version 1.7.x (LTS till July 2021)

📦 2. Installation & Getting Started


A. Install Node.js:
> node -v # e.g., v22.14.0
> npm -v # e.g., 8.5.0

B. Install Angular CLI:

37
> npm install -g @angular/cli
> ng version

C. Manual AngularJS Setup:

●​ Download from: https://angularjs.org/


●​ Use angular.js or angular.min.js
●​ Create HTML:

<html>
<head><script src="angular.js"></script></head>
<body>
<div ng-app>{{3*2*10}}</div>
</body>
</html>

🔹 Output: 60 (Only if ng-app and AngularJS script included)


📘 3. Core AngularJS Concepts
🔧 Directives (Start with ng-)
●​ ng-app: root of the AngularJS app
●​ ng-controller: attaches controller logic
●​ ng-model: binds input data
●​ ng-bind: replaces innerHTML
●​ ng-init: initializes values

💡 Expressions
<p>{{ 10 + 5 }}</p>

●​ Like JavaScript expressions but in double curly braces.​

🧠 4. Controllers, Scopes, Modules


●​ Module: Container for app parts
●​ Controller: JS function managing the model
●​ Scope: Bridges controller and view (data-binding)

Example 1:
<div ng-app="app1" ng-controller="cnt1">
Name: <input ng-model="name">
ID: <input ng-model="id">
<p>{{name + " : " + id}}</p>
</div>

<script>
var c1 = angular.module('app1', []);
c1.controller('cnt1', function($scope) {
$scope.name = "Arian";
$scope.id = 123456;
38
});
</script>

✍️ 5. ng-init and ng-bind


Example 2:
<div ng-app="app2" ng-init="Income=1000; Rate=0.13">
<p>Total Tax: {{Income * Rate}}</p>
</div>
Can also be:
<span ng-bind="Income * Rate"></span>

🧾 6. Templates
●​ Combine data model and view
●​ Auto-update based on model changes
●​ Includes: ng-directives, {{expressions}}, filters, forms

🔌 7. Dependency Injection (DI)


●​ Injects services/components like $scope, $http, $location​
Promotes modularity & reusability
●​ Helps in testability

🛠 8. Services
●​ AngularJS provides 30+ built-in service
●​ Used to perform specific tasks app-wide

Example 5:
<div ng-app="myApp" ng-controller="myCtrl">
<h3>{{myUrl}}</h3>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
</script>

🚀 9. Bootstrapping Process
1.​ Injector created (for DI)
2.​ Root scope created​
DOM compilation (Angular directives processed)
3.​ Event listeners for model changes

🧱 10. MVC Pattern


●​ Model: Holds data
●​ View: HTML with data

39
●​ Controller: Connects them

Example 4:
<div ng-controller="fullName">
{{Student.FName}}
</div>
<script>
function fullName($scope) {
$scope.Student = { FName: "John", LName: "Smith" };
}
</script>

🌐 11. Single Page Application (SPA)


●​ Load HTML/CSS/JS once
●​ Data updates dynamically (no reloads)
●​ Looks and feels like native apps

🔀 12. Routing & Multiple Views


●​ Uses ngRoute module
●​ $routeProvider defines routes and templates

Example 6:
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", { templateUrl: "main.htm" })
.when("/london", { templateUrl: "london.htm" })
.when("/paris", { templateUrl: "paris.htm" });
});
app.controller("londonCtrl", function($scope) {
$scope.msg = "I love London";
});

✅ 13. Advantages of AngularJS


●​ Easy JS-based syntax
●​ Two-way data binding
●​ Fast development
●​ MVC support
●​ Clean, reusable code
●​ SPA-friendly

⚠️ 14. Disadvantages
●​ Requires JavaScript to run
●​ Needs understanding of MVC for complex apps

40
🔹 INTRODUCTION TO SPA (Single Page Applications)
✅ What is SPA?
●​ A SPA is different from a traditional multi-page application (MPA).
●​ In SPA, pages (views) load inline within the same HTML page instead of navigating to new
HTML documents.
●​ Navigation is handled via JavaScript routing mechanisms like ngRoute.

🔹 Major SPA Features


1. Client-Side Rendering

●​ HTML rendering is moved from server → client.


●​ Faster interactions after initial load.

2. Performance

●​ Less client-side load time and fewer server queries.


●​ Uses AJAX for smooth, partial updates.​

3. Offline Support

●​ Can work offline; syncs back once connection is restored.

4. Responsiveness

●​ Only part of the page updates, not the whole page.

5. Modern Usability

●​ Preferred for modern web & mobile apps.


●​ SPA tools include: AngularJS, Angular, NodeJS.

🔹 AngularJS Routing Deep Dive


●​ Use ngRoute module to define views.
●​ $routeProvider configures routes (like switch-case).
●​ Use ng-view to place view content dynamically.​

🔹 ✅ COMPLETE EXAMPLE WALKTHROUGH — test-spa.html


Step 1 – Define Module
var app = angular.module('myApp', []);

Step 2 – Define Controller


app.controller('HomeController', function($scope) {
$scope.message = 'Hello from HomeController';
});

Step 3 – Bind Module + Controller in HTML

41
<html ng-app="myApp">
<body ng-controller="HomeController">
<h1>{{message}}</h1>
</body>
</html>

✅ Output: Hello from HomeController


Step 4 – Include Routing Scripts
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>

And:

var app = angular.module('myApp', ['ngRoute']);

Step 5 – Use ng-view


<body>
<div ng-view></div>
</body>

Step 6 – Route Configuration


app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.html',
controller: 'HomeController'
})
.when('/aboutus', {
templateUrl: 'pages/aboutus.html',
controller: 'AboutusController'
})
.when('/reviews', {
templateUrl: 'pages/reviews.html',
controller: 'ReviewsController'
})
.otherwise({redirectTo: '/'});
});

Step 7 – Create Controllers


app.controller('AboutusController', function($scope) {
$scope.message = 'Hello from AboutusController';
});

app.controller('ReviewsController', function($scope) {
$scope.message = 'Hello from ReviewsController';
});

Step 8 – Each HTML Page (home.html, etc.)


<!-- home.html -->
<h1>Home</h1>
42
<h3>{{message}}</h3>

Step 9 – Add Navigation Links


<a href="#/">Home</a>
<a href="#/aboutus">Aboutus</a>
<a href="#/reviews">Reviews</a>

Step 10 – Embed Templates Using ng-template

(Avoids AJAX requests for views)

<script type="text/ng-template" id="pages/home.html">


<h1>Home</h1><h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/aboutus.html">
<h1>Aboutus</h1><h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/reviews.html">
<h1>Reviews</h1><h3>{{message}}</h3>
</script>

📝 Summary for MCQs


●​ SPA = Single page app, dynamic content loads via JS.
●​ AJAX = Allows updates without full page reload.
●​ ngRoute = AngularJS routing module.
●​ ng-view = Placeholder for current view.
●​ $routeProvider = Routing config, like switch-case.
●​ Controller = Handles view logic.
●​ Service = Reusable logic, singleton.
●​ Module = App container.
●​ Offline support = SPA can queue actions offline and sync later.
●​ AngularJS = Best for fast SPA development.

✅ Angular Overview
●​ Angular is a framework for building single-page applications (SPA) using TypeScript.
●​ Built on a component-based architecture.
●​ Released in 2016 (Angular 2), with updates up to Angular 9 (Feb 2020).​

✅ Advantages of Angular
●​ Component-based → reusable and testable.
●​ Fast due to advanced data binding and lazy loading.
●​ Cross-platform support (web + mobile).
●​ TypeScript = type safety + cleaner code.
●​ CLI support for fast development.

Disadvantages

●​ Steep learning curve.

43
●​ Must learn TypeScript.
●​ Migration from AngularJS is non-trivial.
●​ Complex component management.

✅ Angular Architecture
1. Modules

●​ Decorated with @NgModule


●​ Define:
○​ declarations: components
○​ imports: libraries/modules
○​ providers: services
○​ bootstrap: root component
○​ exports: shared components

2. Components

●​ Decorated with @Component


●​ Includes:
○​ selector: HTML tag
○​ templateUrl: path to HTML
○​ styleUrls: CSS path
●​ Lifecycle hooks: ngOnInit(), ngOnDestroy()

3. Templates

●​ HTML view of a component.


●​ Uses special Angular syntax.

✅ Directives
Structural

●​ *ngIf, *ngFor, *ngSwitch – alter DOM structure​

Attribute

●​ [ngClass] – update element’s attribute dynamically

✅ Services and Dependency Injection (DI)


●​ Services hold business logic
●​ Injected using DI for reuse.
●​ Example:

constructor(private userService: UserService) {}

✅ Getting Started
1.​ Install Node.js

44
Install Angular CLI:​

npm install -g @angular/cli

2.​ Create project:​


ng new my-test
3.​ cd my-test
ng serve

4.​ Open: http://localhost:4200/

✅ Angular Project Structure


src/
└── app/
├── app.component.ts // class logic
├── app.component.html // template
├── app.component.css
└── app.module.ts // root module

✅ Angular Examples
Example 1:

app.component.ts:
export class AppComponent {
title = 'my-test';
}
app.component.html:
<span>{{ title }} app is running!</span>

Example 2 (Interpolation + Pipes):


export class AppComponent {
stName: string = 'Mary Smith';
stId: number = 500100600;
}
<ul>
<li>Student Name: {{ stName }}</li>
<li>Student ID: {{ stId }}</li>
</ul>
<h3>Your Signature is: {{ stName | uppercase }}</h3>

Example 3 (Event + ngFor):


export class AppComponent {
courses = ['Math', 'Lab', 'Web'];

addCourse(course: string) {
this.courses.push(course);
}
}
<ol>
<li *ngFor="let course of courses">{{ course }}</li>
45
</ol>
<input #Course type="text">
<button (click)="addCourse(Course.value)">Add</button>

✅ Routing in Angular
1.​ Importing

import { RouterModule, Routes } from '@angular/router';

2.​ Router Outlet​

●​ Used in template to display components:

<router-outlet></router-outlet>

3.​ Router Links

<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>

4.​ Active Links

<a routerLink="/home" routerLinkActive="active">Home</a>

✅ Migration from AngularJS to Angular


●​ For mobile support, CLI, TypeScript, memory efficiency, and modular design.​

●​ Reusable components and type-safe compilation make Angular more scalable.

✅ React (briefly)
●​ Used to build hybrid mobile/web apps with React Native.​

●​ Used by Instagram, Facebook, Skype, Airbnb.​

📘 Chapter 18: Web Security – Exam Prep


🔐 1. Security Principles (CIA Triad)
●​ Confidentiality: Prevent unauthorized access to data (e.g., encrypted data, cross-site scripting
risks).
●​ Integrity: Ensure data is correct and unaltered (e.g., session hijacking, fake orders).
●​ Availability: Ensure data/services are accessible when needed (e.g., DoS attacks prevent this).

🔎 Threats (STRIDE)
●​ Spoofing: Impersonating a user.
●​ Tampering: Altering data.
●​ Repudiation: Deleting logs to hide attacks.
46
●​ Information Disclosure: Unauthorized data access.
●​ Denial of Service: Overloading services.
●​ Elevation of Privilege: Gaining higher access.

⚠ Vulnerabilities (OWASP Top 5)

1.​ Injection (e.g., SQL)


2.​ Broken authentication/session
3.​ Cross-site scripting (XSS)
4.​ Insecure direct object references
5.​ Security misconfigurations

🧑‍💻 2. Authentication
🔐 Factors of Authentication
●​ Knowledge (password)
●​ Possession (ID, phone)
●​ Inherence (fingerprint)
●​ Single-Factor: Just one (e.g., password)
●​ Multi-Factor: More secure (e.g., password + OTP)

🧾 HTTP Authentication Methods


●​ Basic: Encodes credentials (base64) – insecure
●​ Digest: Hashes credentials
●​ Form-Based: Common in web apps (login forms)

🔗 Third-Party Authentication
●​ OAuth: External login (e.g., Google, Facebook)

🧑‍⚖️ Authorization
●​ Controls what users can do after login
●​ Use principle of least privilege, separate DB users, avoid root access

🔑 3. Cryptography
🔁 Symmetric Encryption
●​ Same key for encryption/decryption
●​ Fast but needs secure key sharing

🔓 Asymmetric Encryption (Public-Key)


●​ Public key encrypts, private key decrypts
●​ Used in HTTPS, email, digital signatures

🧮 Examples
●​ Caesar Cipher: Shift characters
●​ Vigenère Cipher: Keyword-based shifts

🧾 Digital Signatures
●​ Ensure authenticity, integrity, non-repudiation

47
🌐 4. HTTPS (SSL/TLS)
●​ HTTPS = HTTP + Encryption
●​ Uses TLS handshake to exchange keys securely
●​ Requires a certificate signed by a Certificate Authority (CA)
●​ Browsers trust certificates from known CAs

⚙️ Migration Issues
●​ Mixed content (HTTP inside HTTPS)
●​ Links with http://
●​ PHP hardcoded paths, redirects

🛡️ 5. Security Best Practices


🔒 Hashing Passwords
●​ MD5, SHA1 (not safe today, used in old systems)
●​ Store password hashes, not passwords

🧂 Salting
●​ Add unique value to each password before hashing to prevent rainbow table attacks

🔍 Monitoring Tools
●​ Access logs (e.g., access_log, mysql_log)
●​ Intrusion blocking scripts: Auto-ban IPs
●​ Tools: blockhosts.py, fail2ban

🧪 Self-Auditing
●​ Use tools like w3af to simulate attacks (e.g., SQLi, XSS)

🧨 Virtual Open Mail Relay


●​ Accepts unauthorized emails → used by spammers → blacklisted

✅ Sample Code Snippet (PHP)


// MD5 Hashing with Salt Example
$password = "mypassword";
$salt = "randomString123";
$hashed = md5($salt . $password);

🌐 What is Node.js?
Node.js is a server-side runtime that uses JavaScript instead of PHP or Python. It runs on the V8
engine (same as Chrome) and enables building event-driven, non-blocking web servers.

✅ Advantages of Node.js
1.​ JavaScript Everywhere
○​ One language (JS) for both client and server.
○​ Easier hiring and code reuse.
2.​ Push Architecture
48
○​ Server pushes data to client (like a phone call).
○​ Used in live chats, real-time updates.
3.​ Non-blocking Architecture
○​ Uses event loop (single-threaded) + async callbacks.
○​ More scalable under heavy load.
4.​ Rich Ecosystem
○​ Vast collection of libraries via npm.
○​ Used by giants: Netflix, Uber, LinkedIn.
5.​ Great for real-time + noSQL apps
○​ Example: A “Like” button with thousands of real-time updates.

❌ Disadvantages
●​ Not ideal for:
○​ Relational DBs (e.g., MySQL)
○​ Heavy computation (e.g., video processing)
○​ May increase development complexity

🔧 Hello World in Node.js


const http = require('http');

const server = http.createServer(function (request, response) {


response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello this is our first node.js application");
response.end();
});

const port = 8080;


server.listen(port);

console.log("Server running at port=" + port);

Run via terminal:

node hello.js
Visit: http://localhost:8080

⚡ Express.js & Static Server


Install Express via npm install express.

var express = require("express");


var app = express();
var path = require("path");

app.use("/static", express.static(path.join(__dirname, "public")));

app.listen(8080, () => {
console.log("Server started");
});

49
🔁 Middleware in Express
Middleware functions are executed sequentially with app.use(). Great for:

●​ Logging​

●​ Authentication​

●​ Modifying requests/responses

🌱 Environment Variables
Use dotenv:

npm install dotenv

.env file:

PORT=8080
BUILD=development

Code:

require('dotenv').config();
console.log(process.env.BUILD);
server.listen(process.env.PORT);

📡 Creating a Simple API


Example (read JSON and return data):
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
const jsonPath = path.join(__dirname, 'public', 'companies.json');
let companies;
fs.readFile(jsonPath, (err, data) => {
if (err) console.log('Unable to read file');
else companies = JSON.parse(data);
});
app.get('/', (req, res) => res.json(companies));
app.listen(8080, () => console.log("Running"));

🛣️ Add Routes
// Return by symbol
app.get('/companies/:symbol', (req, res) => {
const symbol = req.params.symbol.toUpperCase();
const match = companies.filter(c => c.symbol === symbol);
res.json(match);
});

50
// Return by name substring
app.get('/companies/name/:substring', (req, res) => {
const sub = req.params.substring.toLowerCase();
const matches = companies.filter(c => c.name.toLowerCase().includes(sub));
res.json(matches);
});

📦 Modular Code
// dataModule.js
const fs = require('fs').promises;
const path = require('path');
const jsonPath = path.join(__dirname, '../public', 'companies.json');
let companies;
async function getCompanyData() {
try {
const data = await fs.readFile(jsonPath, 'utf-8');
companies = JSON.parse(data);
} catch (err) {
console.log("Error reading data");
}
}
getCompanyData();
function getData() {
return companies;
}
module.exports = { getData };

🧩 CRUD API
Use HTTP methods:

●​ GET: Read
●​ POST: Create
●​ PUT: Update
●​ DELETE: Delete​

Example:

app.put('/companies/:symbol', (req, res) => {


// logic to update a company
});

📤 Passing Data
●​ GET: ?key=value in URL
●​ POST: Body payload (requires Content-Type)
●​ Accepts: text, JSON, XML, files

🧪 API Testing Tools


Use:
51
●​ Postman
●​ Insomnia

These allow:

●​ URL + headers
●​ Method (GET/POST/...)
●​ Send raw or JSON body

🧠 WebSockets
●​ Two-way connection
●​ Uses Socket.io

Install:

npm install socket.io

Used for:

●​ Chat apps
●​ Live dashboards

🧱 View Engine (EJS Example)


Install EJS:

npm install ejs

<h1><%= title %></h1>


<% for (let p of paintings) { %>
<div>
<img src="<%= p.filename %>">
<h2><%= p.artist %></h2>
</div>
<% } %>

☁️ Serverless Computing
●​ You don’t manage servers.
●​ Used in:
○​ AWS Lambda
○​ Google Firebase
●​ Reduces cost & complexity
●​ Common models:
○​ FaaS (Functions as a Service)
○​ PaaS (Platform as a Service)
○​ DBaaS (Database as a Service)

52
✅ 1. XML Overview
What is XML?

●​ XML (eXtensible Markup Language) is not limited to displaying data like HTML. It’s used to
store and transport data in a structured way.
●​ It's plain text, making it platform-independent and applicable across different systems.

Key Benefits:

●​ Used in AJAX, web services, and data interchange between systems (e.g., financial apps,
DBMS).​
Self-descriptive structure—you define your own tags.

✅ 2. Well-Formed XML
Rules for XML:

●​ Single root element.


●​ Elements must be properly nested and closed.
●​ Element names:
○​ Can’t start with a number.
○​ Are case-sensitive.
●​ Attributes:
○​ Must be quoted.

Example:
<?xml version="1.0" encoding="ISO-8859-1"?>
<art>
<painting id="290">
<title>Balcony</title>
<artist>
<name>Manet</name>
<nationality>France</nationality>
</artist>
<year>1868</year>
<medium>Oil on canvas</medium>
</painting>
</art>

✅ 3. Valid XML vs Well-Formed


●​ Well-Formed = syntactically correct.
●​ Valid = follows rules of a DTD or Schema.

Example DTD:
<!DOCTYPE art [
<!ELEMENT art (painting*)>
<!ELEMENT painting (title, artist, year, medium)>
<!ATTLIST painting id CDATA #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ELEMENT artist (name, nationality)>
<!ELEMENT name (#PCDATA)>

53
<!ELEMENT nationality (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT medium (#PCDATA)>
]>

✅ 4. Processing XML
JavaScript (with XMLHttpRequest):
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","art.xml",false);
xmlhttp.send();
var xmlDoc = xmlhttp.responseXML;
var paintings = xmlDoc.getElementsByTagName("painting");

Here's a line-by-line explanation in simple terms of the code:

var xmlhttp = new XMLHttpRequest();

▶ This creates a new object called xmlhttp that can be used to send a request to a server and receive
data — in this case, we’ll be fetching an XML file.

xmlhttp.open("GET","art.xml",false);

▶ This tells the xmlhttp object:

●​ We want to GET data (not send or update),


●​ From the file named "art.xml",
●​ And do it synchronously (false means the browser will wait until the file is loaded before
moving on).

xmlhttp.send();

▶ This line actually sends the request to the server to load the "art.xml" file.

var xmlDoc = xmlhttp.responseXML;

▶ After the file is loaded, this stores the XML data into a variable called xmlDoc. Now we can work with
this XML as a structured object.

var paintings = xmlDoc.getElementsByTagName("painting");

▶ This searches the XML document and gets all <painting> elements and stores them in a list called
paintings. You can then loop through this list to read titles, artists, years, etc.

👉
So, in short:​
You're asking the browser to get an XML file (art.xml), wait for it to load, and then extract all the
<painting> entries from it so you can use them in your JavaScript code.

jQuery:

var art = '<?xml version="1.0"?><art>...</art>';


var xmlDoc = $.parseXML(art);
var xml = $(xmlDoc);
54
var paintings = xml.find("painting");

Here's a simple line-by-line explanation of the code:


var art = '<?xml version="1.0"?><art>...</art>';

▶ This creates a string that contains XML data. It's stored in a variable
named art.​
📝 In a real example, instead of ..., you'd have real XML content like
<painting>...</painting> inside <art>.

var xmlDoc = $.parseXML(art);

▶ This uses jQuery’s parseXML() function to convert the XML string into an
actual XML document object that JavaScript can work with.

var xml = $(xmlDoc);

▶ This wraps the XML document (xmlDoc) with jQuery so you can use jQuery
functions like .find(), .text(), etc., to work with it easily.

var paintings = xml.find("painting");

▶ This searches the entire XML document for all <painting> elements and stores
them in a variable called paintings.​
You can now loop over them or extract information like title, artist, etc.

🔍 Summary:​
You create XML as a string ➝ convert it into a document ➝ wrap it with
jQuery ➝ search it for specific tags (<painting>).

✅ 5. XML in PHP
Using SimpleXML:
$art = simplexml_load_file("art.xml");
echo $art->painting[0]->title;

With XPath:
$titles = $art->xpath('/art/painting/title');
foreach ($titles as $t) {
echo $t . '<br/>';}

Using XMLReader (Pull Approach):


$reader = new XMLReader();
$reader->open('art.xml');
while($reader->read()) {
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'painting') {
$doc = new DOMDocument();
$painting = simplexml_import_dom($doc->importNode($reader->expand(), true));
echo '<h2>' . $painting->title . '</h2>';
}
}

55
✅ 6. JSON vs XML
XML:
<Countries>
<Country>
<Name>Britain</Name>
<Capital>London</Capital>
</Country>
</Countries>

JSON:
{"Countries":[
{"Name":"Britain", "Capital":"London"}
]}

JSON is lighter, easier to parse in JavaScript. XML supports metadata and schemas.

✅ 7. Web Services: Asynchronous Interaction


jQuery Autocomplete Example:
<script>
$(function() {
$("#search").autocomplete({
source: "serviceTravelCountries.php",
minlength: 2,
delay: 1
});
});
</script>

✅ 8. Google Maps Integration


HTML + JavaScript Example:
<script src="https://maps.googleapis.com/maps/api/js?key=yourkey"></script>
<div id="map" style="height:500px;width:600px"></div>

<script>
var ourLatLong = {lat: 51.011179 , lng: -114.132866};
var ourMap = new google.maps.Map(document.getElementById('map'), {
center: ourLatLong,
zoom: 14
});
</script>

56
🌟 React.js Exam Guide (MCQ-Friendly)
✅ What is a Framework?
●​ A framework is a reusable code library that simplifies and accelerates the development of
applications.
●​ Popular JavaScript front-end frameworks: React, Angular, Vue.

✅ Why Use Frameworks?


●​ Speeds up UI development.
●​ React uses a virtual DOM → faster DOM manipulation.
●​ Enables component-based design: reusable, nestable UI blocks.

🔹 React Overview
📌 React
●​ Developed by Facebook.
●​ Focuses on the View in MVC.
●​ Supports component-based architecture.
●​ Excellent for Single-Page Applications (SPAs).

🔹 JSX (JavaScript XML)


🔑 JSX Rules
●​ Similar to XML.
●​ Must have one root element.
●​ Every tag must be closed.
●​ Use className instead of class.
●​ Attributes must be in quotes.​

const Hello = () => <h1 className="title">Hello</h1>;

🔹 React Components
🧱 Two Types:
1.​ Functional Components (simpler):

const Logo = (props) => {


return <img src="logo.png" alt="logo" />;
};

2.​ Class Components:

class Header extends React.Component {


render() {
return (
<header>
<Logo />

57
<Title />
</header>
);
}
}

🔹 Props, State, and Behavior


🎁 Props (Read-Only)
●​ Used to pass data into components.

const MovieList = (props) => {


return <ul>{props.movies.map((m, i) => <li key={i}>{m.title}</li>)}</ul>;
};

💾 State (Mutable, Internal Data)


●​ Use when data changes over time.
●​ Must be updated using setState().

this.setState({ count: this.state.count + 1 });

🎬 Behavior (Events)
●​ Define event handlers inside components.

const MovieListItem = (props) => {


const handleClick = () => {
alert('Clicked on ID=' + props.movie.id);
};
return (
<li>
{props.movie.title}
<button onClick={handleClick}>View</button>
</li>
);
};

🔹 Conditional Rendering
🧠 Based on State
render() {
if (this.state.editing) {
return this.renderEdit();
} else {
return this.renderNormal();
}
}

🔹 Forms in React
58
✍️ Controlled vs. Uncontrolled
●​ Controlled: State is in React.
●​ Uncontrolled: DOM manages its own state.

🔹 Data Flow Between Components


📡 One-way Flow
●​ Props go downward.
●​ Changes must be handled at the common parent.

<App>
<PaintingList />
<EditPaintingForm />
</App>

🔹 React Build Toolchain


🛠️ Features:
●​ Transcompiles JSX → JS.
●​ Bundles, minifies, splits code.
●​ Supports dev vs. production builds.

Tool: Create React App


npx create-react-app my-app
cd my-app
npm start

🔹 React Lifecycle Methods


🔄 Lifecycle Order:
1.​ constructor()
2.​ render()
3.​ componentDidMount()
4.​ shouldComponentUpdate()
5.​ componentDidUpdate()

Used for:

●​ Fetching API data after render.


●​ Controlling re-renders.

🔹 React Router
🧭 Routing in SPAs
●​ Uses <Link> instead of <a>.

import { Link } from 'react-router-dom';


const Menu = () => (

59
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/products">Products</Link></li>
<li><Link to="/login">Login</Link></li>
</ul>
);

🔹 CSS in React
🎨 Styling Methods:
●​ External CSS with <link>.
●​ Component-level CSS:

import './Header.css';

All styles are merged into one by the build tool.

60

You might also like