Cheat Sheet
Cheat Sheet
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:
Common structure:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph.</p>
</body>
</html>
1
6. HTML5 Semantic Elements:
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;
}
3. Location of Styles:
4. Selectors:
● Consists of:
○ Content
○ Padding
○ Border
○ Margin
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:
5. Responsive Design:
Media Queries:
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
Transitions:
div {
transition: all 0.5s ease;
}
Animations:
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
div {
animation: example 2s infinite;
}
3
JavaScript Extra Notes – Comprehensive Guide
1. Introduction to JavaScript
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
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.
○ Arithmetic: +, -, *, /, %
○ Relational: <, <=, >, >=, ==, !=
○ Logical: &&, ||, !
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;
}
Output:
12000
<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!");
});
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
● 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.
● 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.
● 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.
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.
● 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.
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:
○ 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:
$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;
}
Including Files:
include and require to reuse code.
include 'header.php';
require 'config.php';
4. Functions
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
1. Arrays in PHP
Defining Arrays:
Syntax:
$days = array("Mon", "Tue", "Wed", "Thu", "Fri");
// Alternate syntax
$days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
Associative Arrays:
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)
);
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);
2. Superglobal Arrays
Common Superglobals:
Example:
echo $_SERVER['HTTP_USER_AGENT']; // Displays user's browser info
14
</form>
echo "You selected: ";
foreach ($_GET['day'] as $day) {
echo $day . "<br>";
}
● Sanitizing Input:
$name = htmlspecialchars($_POST['name']);
Example:
$browser = $_SERVER['HTTP_USER_AGENT'];
echo "You are using: $browser";
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;
7. Summary
With these fundamentals, you can now build dynamic and data-driven PHP applications!
Importance of Databases
● Users Table
○ UserID (Primary Key)
○ Name
○ Email
● Orders Table
○ OrderID (Primary Key)
○ UserID (Foreign Key)
○ OrderDate
16
2. SQL (Structured Query Language)
● 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
● COMMIT;
Expected Output: New order inserted only if all queries succeed.
3. NoSQL Databases
Example:
{
"UserID": "user123",
17
4. Database APIs
Connecting to MySQL
MySQLi Procedural
$connection = mysqli_connect("localhost", "user", "pass", "database");
if (!$connection) {
PDO Object-Oriented
try {
die($e->getMessage());
Command-Line Interface
● Connecting to MySQL
mysql -h localhost -u user -p
● Import SQL File
mysql -u user -p database < file.sql
GUI Tools
Basic Steps
Example
$result = $pdo->query($sql);
$pdo = null;
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);
Editing a Record
Example Databases
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.
● 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:
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.
7. Lack of Real Device Testing: Relying only on simulators can miss real-world issues.
20
○ Frameworks like AngularJS, Bootstrap, jQuery, and Animate.css are designed for
compatibility across browsers.
○ Create conditional stylesheets tailored for specific browsers to handle unique quirks.
○ Use tools like LambdaTest or BrowserStack to test how your site behaves on multiple
browsers and devices.
● Link CSS files at the top of your HTML and JavaScript files at the bottom for better page
loading.
21
Useful Tools & Resources
🚀 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;
Using Constructor:
$picasso = new Artist("Pablo", "Picasso", "Malaga", "Oct 25, 1881", "Apr 8, 1973");
class Artist {
public $firstName;
public $lastName;
class Artist {
private $birthDate;
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.
private $name;
🏛️ Inheritance
Inheritance allows one class to inherit properties and methods from another.
class Art {
public $title;
}
class Painting extends Art {
public $medium;
}
🧩 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";
}
}
🔗 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();
}
📋 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.
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>
<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.
26
gstart when dragging starts (drag(event) is called).
gover when dragging over the drop area (must use preventDefault).
<!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>
<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.
🔑 Origin Components:
1. Protocol/Scheme: http, https
2. Domain/Hostname: www.ryerson.ca
3. Port: :80, :443 (default for HTTP/HTTPS)
● 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.
💡 Example:
A frontend on https://example.com calling an API on https://api.example.com would need
CORS enabled.
● 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.
Advantages:
Disadvantages:
Example Flow:
29
1.2.2 Model-View-ViewModel (MVVM)
Advantages:
Disadvantages:
Example Flow:
2. Geolocation API
The Geolocation API allows web applications to access the user's geographical location.
● 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.
<h2>Geolocation Example</h2>
<p id="demo">Click the button to get your location:</p>
<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:
● 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.
Expected Output:
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.
JavaScript frameworks help organize and streamline web application development by providing structured
ways of managing code. Popular frameworks include:
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:
● 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.
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) {
✅ 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:
});
✅ Line 7:
server.listen(7000, "localhost");
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.
MongoDB:
MongoDB is a document-oriented NoSQL database system. Unlike relational databases, MongoDB
stores data in flexible, JSON-like documents.
SQL Example:
SELECT * FROM students WHERE age > 20;
MongoDB Equivalent:
db.students.find({ age: { $gt: 20 } });
Running MongoDB Shell Example:
mongo
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.
<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>
✅ Line 1:
<html ng-app>
✅ Line 2:
<body>
● Starts the HTML body section where the content of the page will go.
✅ Line 3:
<div ng-controller="myController">
✅ Line 4:
35
{{message}}
✅ Line 5:
</div>
✅ Line 6:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
✅ Line 7–10:
<script>
function myController($scope) {
$scope.message = "Hello, Angular!";
}
</script>
● sets a variable named message, which is then used in the view with
{{message}}.
✅ Line 11:
</body>
✅ Line 12:
</html>
Hello, Angular!
● 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.
📌 1. Introduction to AngularJS
● What: A client-side JavaScript framework for building dynamic web apps.
● Key Features:
37
> npm install -g @angular/cli
> ng version
<html>
<head><script src="angular.js"></script></head>
<body>
<div ng-app>{{3*2*10}}</div>
</body>
</html>
💡 Expressions
<p>{{ 10 + 5 }}</p>
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>
🧾 6. Templates
● Combine data model and view
● Auto-update based on model changes
● Includes: ng-directives, {{expressions}}, filters, forms
🛠 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
39
● Controller: Connects them
Example 4:
<div ng-controller="fullName">
{{Student.FName}}
</div>
<script>
function fullName($scope) {
$scope.Student = { FName: "John", LName: "Smith" };
}
</script>
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";
});
⚠️ 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.
2. Performance
3. Offline Support
4. Responsiveness
5. Modern Usability
41
<html ng-app="myApp">
<body ng-controller="HomeController">
<h1>{{message}}</h1>
</body>
</html>
And:
app.controller('ReviewsController', function($scope) {
$scope.message = 'Hello from ReviewsController';
});
✅ 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
43
● Must learn TypeScript.
● Migration from AngularJS is non-trivial.
● Complex component management.
✅ Angular Architecture
1. Modules
2. Components
3. Templates
✅ Directives
Structural
Attribute
✅ Getting Started
1. Install Node.js
44
Install Angular CLI:
npm install -g @angular/cli
✅ Angular Examples
Example 1:
app.component.ts:
export class AppComponent {
title = 'my-test';
}
app.component.html:
<span>{{ title }} app is running!</span>
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
<router-outlet></router-outlet>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
✅ React (briefly)
● Used to build hybrid mobile/web apps with React Native.
🔎 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.
🧑💻 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)
🔗 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
🧮 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
🧂 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)
🌐 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
node hello.js
Visit: http://localhost:8080
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:
.env file:
PORT=8080
BUILD=development
Code:
require('dotenv').config();
console.log(process.env.BUILD);
server.listen(process.env.PORT);
🛣️ 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:
📤 Passing Data
● GET: ?key=value in URL
● POST: Body payload (requires Content-Type)
● Accepts: text, JSON, XML, files
These allow:
● URL + headers
● Method (GET/POST/...)
● Send raw or JSON body
🧠 WebSockets
● Two-way connection
● Uses Socket.io
Install:
Used for:
● Chat apps
● Live dashboards
☁️ 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:
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>
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");
▶ 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);
xmlhttp.send();
▶ This line actually sends the request to the server to load the "art.xml" file.
▶ 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.
▶ 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:
▶ 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>.
▶ This uses jQuery’s parseXML() function to convert the XML string into an
actual XML document object that JavaScript can work with.
▶ This wraps the XML document (xmlDoc) with jQuery so you can use jQuery
functions like .find(), .text(), etc., to work with it easily.
▶ 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/>';}
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.
<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.
🔹 React Overview
📌 React
● Developed by Facebook.
● Focuses on the View in MVC.
● Supports component-based architecture.
● Excellent for Single-Page Applications (SPAs).
🔹 React Components
🧱 Two Types:
1. Functional Components (simpler):
57
<Title />
</header>
);
}
}
🎬 Behavior (Events)
● Define event handlers inside components.
🔹 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.
<App>
<PaintingList />
<EditPaintingForm />
</App>
Used for:
🔹 React Router
🧭 Routing in SPAs
● Uses <Link> instead of <a>.
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';
60