Home
Perfect! Let's do a rapid-fire learning session. I'll teach you the most critical concepts NOW.
🔥 SESSION 1: JAVASCRIPT FUNDAMENTALS (30 mins)
1. Array Operations - SUPER IMPORTANT
// Accept n numbers, find sum, average, largest
let numbers = [10, 25, 8, 42, 15];
// Sum using reduce
let sum = numbers.reduce((total, num) => total + num, 0);
// reduce walks through array: total starts at 0, adds each num
// Average
let average = sum / numbers.length;
// Largest number
let largest = Math.max(...numbers);
// ... spreads array: Math.max(10, 25, 8, 42, 15)
console.log("Sum: " + sum); // 100
console.log("Average: " + average); // 20
console.log("Largest: " + largest); // 42
Key Methods You MUST Know:
// map - transforms each element, RETURNS NEW ARRAY
let doubled = [1,2,3].map(x => x * 2); // [2,4,6]
// forEach - just loops, RETURNS NOTHING
[1,2,3].forEach(x => console.log(x)); // prints 1, 2, 3
// filter - keeps elements that pass test
let evens = [1,2,3,4].filter(x => x % 2 === 0); // [2,4]
Difference between map and forEach:
- map: Creates new array with transformed values
- forEach: Just executes function on each element, no return value
2. EVENT HANDLING - CRITICAL
What is an Event? An event is an action that happens in the browser: click, mouseover, keypress, load, etc.
Three Ways to Handle Events:
<!-- Method 1: Inline (not recommended but simple) -->
<button onclick="alert('Clicked!')">Click Me</button>
<!-- Method 2: Property assignment -->
<button id="btn">Click Me</button>
<script>
document.getElementById('btn').onclick = function() {
alert('Clicked!');
};
</script>
<!-- Method 3: addEventListener (BEST) -->
<script>
document.getElementById('btn').addEventListener('click', function() {
alert('Clicked!');
});
</script>
Common Events:
onclick- when element is clickedonmouseover- mouse enters elementonmouseout- mouse leaves elementonchange- input value changesonload- page/image finishes loading
3. DOM ACCESS - YOU'LL BE ASKED THIS
// By ID (returns single element)
let elem1 = document.getElementById('myId');
// By Class Name (returns HTMLCollection - array-like)
let elem2 = document.getElementsByClassName('myClass');
// By Tag Name (returns HTMLCollection)
let elem3 = document.getElementsByTagName('div');
// Query Selector (CSS selector, returns FIRST match)
let elem4 = document.querySelector('.myClass'); // first element with class
let elem5 = document.querySelector('#myId'); // by ID
// Query Selector All (returns NodeList - array-like)
let elem6 = document.querySelectorAll('.myClass'); // ALL elements
Changing Content:
document.getElementById('demo').innerHTML = 'New content';
document.getElementById('demo').style.backgroundColor = 'red';
4. CALCULATOR PROGRAM - 10 MARKS GUARANTEED
This appears in 2019, 2020, 2021, 2022, 2023, 2025!
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<style>
.calculator {
width: 300px;
margin: 50px auto;
}
input {
width: 100%;
height: 50px;
font-size: 24px;
text-align: right;
margin-bottom: 10px;
}
button {
width: 70px;
height: 50px;
font-size: 18px;
margin: 2px;
}
</style>
</head>
<body>
<div class="calculator">
<input type="text" id="display" disabled>
<br>
<button onclick="appendToDisplay('7')">7</button>
<button onclick="appendToDisplay('8')">8</button>
<button onclick="appendToDisplay('9')">9</button>
<button onclick="appendToDisplay('+')">+</button>
<br>
<button onclick="appendToDisplay('4')">4</button>
<button onclick="appendToDisplay('5')">5</button>
<button onclick="appendToDisplay('6')">6</button>
<button onclick="appendToDisplay('-')">-</button>
<br>
<button onclick="appendToDisplay('1')">1</button>
<button onclick="appendToDisplay('2')">2</button>
<button onclick="appendToDisplay('3')">3</button>
<button onclick="appendToDisplay('*')">*</button>
<br>
<button onclick="clearDisplay()">C</button>
<button onclick="appendToDisplay('0')">0</button>
<button onclick="calculate()">=</button>
<button onclick="appendToDisplay('/')">/</button>
</div>
<script>
function appendToDisplay(value) {
document.getElementById('display').value += value;
}
function clearDisplay() {
document.getElementById('display').value = '';
}
function calculate() {
try {
let result = eval(document.getElementById('display').value);
document.getElementById('display').value = result;
} catch(error) {
document.getElementById('display').value = 'Error';
}
}
</script>
</body>
</html>
KEY POINTS:
eval()evaluates mathematical expressions: eval('2+3') returns 5try-catchhandles errors if user enters invalid expression- Each button calls function with its value
+=appends to existing display value
5. ARROW FUNCTIONS - ASKED EVERY YEAR
Old Way (Function Expression):
let add = function(a, b) {
return a + b;
};
Arrow Function Way:
let add = (a, b) => {
return a + b;
};
// Even shorter (one-line, implicit return):
let add = (a, b) => a + b;
// Single parameter (parentheses optional):
let square = x => x * x;
// No parameters:
let greet = () => console.log('Hello');
Factorial Using Arrow Function:
const factorial = (n) => {
if (n <= 1) return 1;
return n * factorial(n - 1);
};
// Or one-liner with ternary:
const factorial = (n) => n <= 1 ? 1 : n * factorial(n - 1);
console.log(factorial(5)); // 120
6. CHANGE BACKGROUND COLOR EVERY SECOND
Asked in 2021, 2022, 2023!
// Array of colors
let colors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange'];
let index = 0;
// setInterval runs function every X milliseconds
setInterval(function() {
document.body.style.backgroundColor = colors[index];
index = (index + 1) % colors.length; // Loop back to 0 after last color
}, 1000); // 1000ms = 1 second
Key Concepts:
setInterval(function, delay)- repeats function every delay millisecondssetTimeout(function, delay)- runs function once after delay% colors.length- modulo operator keeps index in bounds
7. NaN (Not a Number)
// NaN occurs when math operation fails
let result = 'hello' / 5; // NaN
// Check for NaN
if (isNaN(result)) {
console.log('Not a valid number');
}
// NaN is weird: NaN !== NaN (always use isNaN())
8. DIALOG BOXES
// Alert - just shows message
alert('Hello World!');
// Confirm - shows OK/Cancel, returns true/false
let answer = confirm('Are you sure?');
if (answer) {
console.log('User clicked OK');
}
// Prompt - gets user input, returns string or null
let name = prompt('Enter your name:');
console.log('Hello ' + name);
9. DISPLAYING TIME - HH:MM:SS FORMAT
function displayTime() {
let now = new Date();
let hours = now.getHours().toString().padStart(2, '0');
let minutes = now.getMinutes().toString().padStart(2, '0');
let seconds = now.getSeconds().toString().padStart(2, '0');
let timeString = hours + ':' + minutes + ':' + seconds;
document.getElementById('clock').innerHTML = timeString;
}
// Update every second
setInterval(displayTime, 1000);
Key Method:
padStart(2, '0')- adds '0' to start if length < 2: '5' becomes '05'
🔥 SESSION 2: PHP & DATABASE (45 mins)
This is where you'll score the MOST marks! Form validation + database is worth 10 marks and appears EVERY YEAR!
1. PHP BASICS - MUST KNOW
What is PHP?
- Server-side scripting language
- Runs on server, outputs HTML to browser
- Perfect for database operations, form processing
PHP Syntax:
<?php
// PHP code goes here
echo "Hello World"; // outputs to browser
?>
Variables:
<?php
$name = "John"; // String (no type declaration needed!)
$age = 25; // Integer
$price = 99.99; // Float
$isStudent = true; // Boolean
// Concatenation with . (dot)
echo "My name is " . $name . " and I am " . $age;
// Or use double quotes (variables work inside)
echo "My name is $name and I am $age";
?>
2. SUPER GLOBAL VARIABLES - ALWAYS ASKED
These are built-in arrays available everywhere:
// $_POST - data from POST method forms
$_POST['username']
// $_GET - data from URL or GET method forms
$_GET['id'] // from URL: page.php?id=123
// $_SESSION - stores data across pages for a user
$_SESSION['user_id']
// $_COOKIE - stores data in browser
$_COOKIE['theme']
// $_FILES - uploaded file information
$_FILES['photo']
// $_SERVER - server information
$_SERVER['REQUEST_METHOD'] // 'GET' or 'POST'
3. ARRAYS IN PHP - SUPER IMPORTANT
Three Types:
<?php
// 1. INDEXED ARRAY (numeric keys: 0, 1, 2...)
$colors = array("Red", "Green", "Blue");
// OR
$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Red
// 2. ASSOCIATIVE ARRAY (named keys)
$student = array(
"name" => "John",
"age" => 20,
"grade" => "A"
);
// OR
$student = [
"name" => "John",
"age" => 20,
"grade" => "A"
];
echo $student["name"]; // John
// 3. MULTIDIMENSIONAL ARRAY (array of arrays)
$students = [
"Anshis" => ["OS" => 85, "Scripting" => 90, "DBMS" => 78],
"Jayanti" => ["OS" => 92, "Scripting" => 88, "DBMS" => 95],
"Niraj" => ["OS" => 75, "Scripting" => 80, "DBMS" => 70]
];
echo $students["Anshis"]["Scripting"]; // 90
?>
foreach Loop - MASTER THIS:
<?php
// For indexed arrays
$colors = ["Red", "Green", "Blue"];
foreach($colors as $color) {
echo $color . "<br>";
}
// For associative arrays
$student = ["name" => "John", "age" => 20];
foreach($student as $key => $value) {
echo "$key: $value<br>";
}
// Output:
// name: John
// age: 20
// Calculate average from multidimensional array
$students = [
"Anshis" => ["OS" => 85, "Scripting" => 90, "DBMS" => 78],
"Jayanti" => ["OS" => 92, "Scripting" => 88, "DBMS" => 95]
];
foreach($students as $name => $marks) {
$sum = array_sum($marks); // adds all values
$avg = $sum / count($marks);
echo "$name: Average = $avg<br>";
}
?>
4. FORM HANDLING - 10 MARKS QUESTION!
HTML Form:
<form method="POST" action="process.php">
Name: <input type="text" name="fullname"><br>
Email: <input type="email" name="email"><br>
Mobile: <input type="text" name="mobile"><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br>
<input type="submit" value="Submit">
</form>
process.php - VALIDATION + DATABASE:
<?php
// Check if form was submitted
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get form data
$name = $_POST['fullname'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$gender = $_POST['gender'];
// VALIDATION - Initialize error array
$errors = [];
// 1. Check if required fields are empty
if(empty($name)) {
$errors[] = "Name is required";
}
if(empty($email)) {
$errors[] = "Email is required";
}
// 2. Validate email format
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
// 3. Validate mobile (10 digits starting with 98, 97, or 96)
if(!preg_match('/^(98|97|96)\d{8}$/', $mobile)) {
$errors[] = "Mobile must be 10 digits starting with 98, 97, or 96";
}
// 4. Validate name length (max 40 characters)
if(strlen($name) > 40) {
$errors[] = "Name must be less than 40 characters";
}
// If no errors, insert into database
if(empty($errors)) {
// Database connection
$conn = mysqli_connect('localhost', 'root', '', 'FOHSS');
// Check connection
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Insert query
$sql = "INSERT INTO BCA (name, email, mobile, gender)
VALUES ('$name', '$email', '$mobile', '$gender')";
if(mysqli_query($conn, $sql)) {
echo "Data inserted successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
} else {
// Display errors
foreach($errors as $error) {
echo $error . "<br>";
}
}
}
?>
VALIDATION PATTERNS YOU MUST MEMORIZE:
// Required field
if(empty($variable)) { }
// Email validation
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { }
// Mobile: 10 digits starting with 98/97/96
if(!preg_match('/^(98|97|96)\d{8}$/', $mobile)) { }
// Date format YYYY-MM-DD
if(!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) { }
// Password length (min 8 characters)
if(strlen($password) < 8) { }
// Username starts with letter, followed by numbers
if(!preg_match('/^[a-zA-Z][a-zA-Z0-9]*$/', $username)) { }
Regex Breakdown:
^= start of string$= end of string\d= digit (0-9){8}= exactly 8 times*= zero or more times+= one or more times[a-zA-Z]= any letter
5. DATABASE CONNECTION - CRITICAL
Step-by-Step:
<?php
// 1. CONNECT to database
$conn = mysqli_connect('hostname', 'username', 'password', 'database_name');
// Common: mysqli_connect('localhost', 'root', '', 'mydatabase');
// 2. CHECK connection
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// 3. PREPARE SQL query
$sql = "INSERT INTO students (name, email, age) VALUES ('John', '[email protected]', 20)";
// 4. EXECUTE query
if(mysqli_query($conn, $sql)) {
echo "Record inserted successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
// 5. CLOSE connection
mysqli_close($conn);
?>
SQL Queries You Need:
// INSERT
$sql = "INSERT INTO table_name (col1, col2) VALUES ('val1', 'val2')";
// SELECT (retrieve data)
$sql = "SELECT * FROM table_name WHERE condition";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
echo $row['column_name'];
}
// UPDATE
$sql = "UPDATE table_name SET col1='value' WHERE id=1";
// DELETE
$sql = "DELETE FROM table_name WHERE id=1";
6. FILE UPLOAD - $_FILES ARRAY
HTML Form (must have enctype):
<form method="POST" enctype="multipart/form-data" action="upload.php">
<input type="file" name="myfile">
<input type="submit" value="Upload">
</form>
upload.php:
<?php
if(isset($_FILES['myfile'])) {
// $_FILES array contains:
$filename = $_FILES['myfile']['name']; // original filename
$filesize = $_FILES['myfile']['size']; // size in bytes
$filetype = $_FILES['myfile']['type']; // MIME type
$tmp_name = $_FILES['myfile']['tmp_name']; // temporary location
$error = $_FILES['myfile']['error']; // error code
// VALIDATION
$allowed_types = ['pdf', 'doc', 'docx', 'jpg', 'jpeg'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// Check file type
if(!in_array($extension, $allowed_types)) {
echo "Invalid file type";
exit;
}
// Check file size (5MB = 5 * 1024 * 1024 bytes)
if($filesize > 5 * 1024 * 1024) {
echo "File too large. Max 5MB";
exit;
}
// Move file from temp to permanent location
$destination = "uploads/" . $filename;
if(move_uploaded_file($tmp_name, $destination)) {
echo "File uploaded successfully";
} else {
echo "Upload failed";
}
}
?>
7. SESSIONS - STORE DATA ACROSS PAGES
Sessions keep data for a specific user across multiple pages.
Start Session (must be at TOP of every page using sessions):
<?php
session_start(); // ALWAYS first line
// Store data
$_SESSION['username'] = 'john123';
$_SESSION['user_id'] = 42;
?>
Access Session Data:
<?php
session_start();
// Check if user is logged in
if(isset($_SESSION['username'])) {
echo "Welcome " . $_SESSION['username'];
} else {
echo "Please login";
}
?>
Destroy Session (logout):
<?php
session_start();
session_destroy(); // destroys all session data
// Or unset specific variable:
unset($_SESSION['username']);
?>
8. COOKIES - STORE DATA IN BROWSER
<?php
// CREATE cookie (before any HTML output!)
setcookie('username', 'john123', time() + 3600); // expires in 1 hour
// time() + (days * 24 * 60 * 60) for multiple days
// ACCESS cookie
if(isset($_COOKIE['username'])) {
echo "Welcome back " . $_COOKIE['username'];
}
// DELETE cookie (set expiry to past)
setcookie('username', '', time() - 3600);
?>
9. CHESS BOARD - COMMON 5 MARK QUESTION
<?php
echo "<table border='1' cellspacing='0' cellpadding='20'>";
for($row = 0; $row < 8; $row++) {
echo "<tr>";
for($col = 0; $col < 8; $col++) {
// If sum is even: white, if odd: black
if(($row + $col) % 2 == 0) {
echo "<td style='background-color: white;'></td>";
} else {
echo "<td style='background-color: black;'></td>";
}
}
echo "</tr>";
}
echo "</table>";
?>
10. COMPLETE FORM + VALIDATION + DATABASE EXAMPLE
<!DOCTYPE html>
<html>
<head><title>Registration</title></head>
<body>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$gender = $_POST['gender'];
$dob = $_POST['dob'];
$errors = [];
// Validations
if(empty($name) || empty($email) || empty($mobile) || empty($gender) || empty($dob)) {
$errors[] = "All fields are required";
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email";
}
if(!preg_match('/^(98|97|96)\d{8}$/', $mobile)) {
$errors[] = "Mobile must be 10 digits starting with 98/97/96";
}
if(!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dob)) {
$errors[] = "Date must be in YYYY-MM-DD format";
}
if(empty($errors)) {
$conn = mysqli_connect('localhost', 'root', '', 'FOHSS');
if($conn) {
$sql = "INSERT INTO BCA (name, email, mobile, gender, dob)
VALUES ('$name', '$email', '$mobile', '$gender', '$dob')";
if(mysqli_query($conn, $sql)) {
echo "<p style='color:green'>Registration successful!</p>";
} else {
echo "<p style='color:red'>Error: " . mysqli_error($conn) . "</p>";
}
mysqli_close($conn);
}
} else {
foreach($errors as $error) {
echo "<p style='color:red'>$error</p>";
}
}
}
?>
<form method="POST">
Name: <input type="text" name="name"><br><br>
Email: <input type="email" name="email"><br><br>
Mobile: <input type="text" name="mobile"><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
DOB: <input type="date" name="dob"><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
🔥 SESSION 3: OOP, AJAX, jQuery (Final 45 mins)
Let's crush the advanced topics!
1. OBJECT-ORIENTED PHP - HIGH MARKS TOPIC
Basic Class Structure:
<?php
// Define a class
class Student {
// Properties (variables)
public $name;
public $age;
public $grade;
// Constructor - runs automatically when object is created
function __construct($name, $age, $grade) {
$this->name = $name; // $this refers to current object
$this->age = $age;
$this->grade = $grade;
}
// Method (function)
function display() {
echo "Name: " . $this->name . "<br>";
echo "Age: " . $this->age . "<br>";
echo "Grade: " . $this->grade . "<br>";
}
}
// Create object
$student1 = new Student("John", 20, "A");
$student1->display();
// Create another object
$student2 = new Student("Sarah", 22, "B");
$student2->display();
?>
Key Points:
public= accessible everywhereprivate= only inside classprotected= inside class and child classes$this->= refers to current object's property/method__construct()= constructor (two underscores!)
2. INHERITANCE - VERY IMPORTANT
Inheritance = Child class inherits properties/methods from Parent class
<?php
// PARENT CLASS
class Person {
public $name;
public $age;
function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
function display() {
echo "Name: $this->name, Age: $this->age<br>";
}
}
// CHILD CLASS (inherits from Person)
class Student extends Person {
public $studentID;
public $grade;
function __construct($name, $age, $studentID, $grade) {
parent::__construct($name, $age); // call parent constructor
$this->studentID = $studentID;
$this->grade = $grade;
}
function displayStudent() {
$this->display(); // inherited method
echo "Student ID: $this->studentID, Grade: $this->grade<br>";
}
}
// ANOTHER CHILD CLASS
class Employee extends Person {
public $salary;
public $position;
function __construct($name, $age, $salary, $position) {
parent::__construct($name, $age);
$this->salary = $salary;
$this->position = $position;
}
function displayEmployee() {
$this->display();
echo "Position: $this->position, Salary: $this->salary<br>";
}
}
// Create objects
$student = new Student("John", 20, "S123", "A");
$student->displayStudent();
$employee = new Employee("Sarah", 30, 50000, "Manager");
$employee->displayEmployee();
?>
Types of Inheritance:
- Single: Child → Parent
- Hierarchical: Multiple children from one parent (above example)
- Multilevel: Grandchild → Child → Parent
Hierarchical Example:
Person (parent)
├── Student (child)
└── Employee (child)
3. METHOD OVERRIDING
Child class redefines parent's method:
<?php
class Animal {
function makeSound() {
echo "Some generic sound<br>";
}
}
class Dog extends Animal {
// Override parent method
function makeSound() {
echo "Bark! Bark!<br>";
}
}
class Cat extends Animal {
// Override parent method
function makeSound() {
echo "Meow! Meow!<br>";
}
}
$animal = new Animal();
$animal->makeSound(); // Some generic sound
$dog = new Dog();
$dog->makeSound(); // Bark! Bark!
$cat = new Cat();
$cat->makeSound(); // Meow! Meow!
?>
4. POLYMORPHISM (Method Overloading)
PHP doesn't have true overloading, but we can simulate it:
<?php
class Calculator {
// Simulate overloading using default parameters
function add($a, $b = 0, $c = 0) {
return $a + $b + $c;
}
}
$calc = new Calculator();
echo $calc->add(5); // 5
echo $calc->add(5, 10); // 15
echo $calc->add(5, 10, 15); // 30
// OR using variable arguments (better way)
class Calculator2 {
function sum(...$numbers) { // ... means "all arguments"
return array_sum($numbers);
}
}
$calc2 = new Calculator2();
echo $calc2->sum(1, 2); // 3
echo $calc2->sum(1, 2, 3, 4); // 10
?>
5. INTERFACE - ASKED IN 2025!
Interface = Contract that classes must follow
<?php
// Define interface
interface Shape {
public function calculateArea(); // just declaration, no implementation
}
// Circle class implements interface
class Circle implements Shape {
private $radius;
function __construct($radius) {
$this->radius = $radius;
}
// MUST implement calculateArea (interface requirement)
public function calculateArea() {
return 3.14 * $this->radius * $this->radius;
}
}
// Square class implements interface
class Square implements Shape {
private $side;
function __construct($side) {
$this->side = $side;
}
// MUST implement calculateArea
public function calculateArea() {
return $this->side * $this->side;
}
}
// Triangle class implements interface
class Triangle implements Shape {
private $base;
private $height;
function __construct($base, $height) {
$this->base = $base;
$this->height = $height;
}
// MUST implement calculateArea
public function calculateArea() {
return 0.5 * $this->base * $this->height;
}
}
// Use them
$circle = new Circle(5);
echo "Circle Area: " . $circle->calculateArea() . "<br>";
$square = new Square(4);
echo "Square Area: " . $square->calculateArea() . "<br>";
$triangle = new Triangle(6, 8);
echo "Triangle Area: " . $triangle->calculateArea() . "<br>";
?>
Interface Rules:
- All methods are public and abstract (no body)
- Classes MUST implement all interface methods
- Use
implementskeyword - Multiple interfaces allowed:
class X implements A, B, C
6. AJAX - SUPER IMPORTANT
What is AJAX?
- Asynchronous JavaScript And XML
- Updates part of webpage WITHOUT reloading entire page
- Communicates with server in background
How it Works:
Browser → AJAX Request → Server (PHP)
Browser ← AJAX Response ← Server
(only part of page updates)
Basic AJAX Example:
HTML File (index.html):
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
</head>
<body>
<h2>Check Username Availability</h2>
<input type="text" id="username" onkeyup="checkUsername()">
<div id="result"></div>
<script>
function checkUsername() {
let username = document.getElementById('username').value;
// 1. Create XMLHttpRequest object
let xhr = new XMLHttpRequest();
// 2. Define what happens when response comes back
xhr.onload = function() {
if(xhr.status == 200) {
document.getElementById('result').innerHTML = xhr.responseText;
}
};
// 3. Open connection (method, URL, async=true)
xhr.open('GET', 'check.php?username=' + username, true);
// 4. Send request
xhr.send();
}
</script>
</body>
</html>
Server File (check.php):
<?php
// Get username from AJAX request
$username = $_GET['username'];
// Check in database (simplified example)
$conn = mysqli_connect('localhost', 'root', '', 'mydb');
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0) {
echo "<span style='color:red'>Username already taken</span>";
} else {
echo "<span style='color:green'>Username available</span>";
}
mysqli_close($conn);
?>
XMLHttpRequest Object:
let xhr = new XMLHttpRequest();
// Properties:
xhr.status // HTTP status: 200=OK, 404=Not Found, 500=Server Error
xhr.responseText // Response as text
xhr.readyState // 0=unsent, 1=opened, 2=sent, 3=loading, 4=done
// Methods:
xhr.open(method, url, async) // method='GET'/'POST', async=true/false
xhr.send() // for GET
xhr.send(data) // for POST
// Events:
xhr.onload = function() { } // when response received
xhr.onerror = function() { } // when error occurs
POST Method AJAX:
function submitData() {
let xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.open('POST', 'submit.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('name=John&age=25&[email protected]');
}
7. jQuery - MAKES JAVASCRIPT EASIER
What is jQuery?
- JavaScript library
- Simplifies DOM manipulation, events, AJAX
- "Write less, do more"
Include jQuery (in HTML head):
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Syntax:
$(selector).action();
// $ = jQuery object
// selector = finds HTML elements
// action = what to do with elements
jQuery Selectors:
// By ID
$('#myId')
// By Class
$('.myClass')
// By Tag
$('p')
// By Attribute
$('input[type="text"]')
// Multiple
$('div, p, span')
// Descendant
$('div p') // all <p> inside <div>
// Child
$('div > p') // direct children only
// First/Last
$('li:first')
$('li:last')
// Even/Odd
$('tr:even')
$('tr:odd')
Common jQuery Methods:
// Get/Set content
$('#demo').html(); // get HTML content
$('#demo').html('New content'); // set HTML content
$('#demo').text(); // get text only
$('#demo').val(); // get input value
// CSS
$('#demo').css('color', 'red');
$('#demo').css({'color': 'red', 'font-size': '20px'});
// Show/Hide
$('#demo').hide();
$('#demo').show();
$('#demo').toggle(); // switch between hide/show
// Fade effects
$('#demo').fadeIn();
$('#demo').fadeOut();
$('#demo').fadeToggle();
// Slide effects
$('#demo').slideDown();
$('#demo').slideUp();
$('#demo').slideToggle();
// Add/Remove classes
$('#demo').addClass('highlight');
$('#demo').removeClass('highlight');
$('#demo').toggleClass('highlight');
// Events
$('#btn').click(function() {
alert('Clicked!');
});
$('#input').keyup(function() {
console.log($(this).val());
});
$('#div').hover(
function() { $(this).css('background', 'yellow'); }, // mouse enter
function() { $(this).css('background', 'white'); } // mouse leave
);
jQuery AJAX (much simpler!):
// GET request
$.ajax({
url: 'getData.php',
method: 'GET',
success: function(response) {
$('#result').html(response);
},
error: function() {
alert('Error occurred');
}
});
// Even simpler GET
$.get('getData.php', function(response) {
$('#result').html(response);
});
// POST request
$.post('saveData.php', {name: 'John', age: 25}, function(response) {
alert(response);
});
jQuery DatePicker Widget:
<!DOCTYPE html>
<html>
<head>
<!-- Include jQuery UI CSS -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Include jQuery UI JS -->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd', // 2025-02-02
changeMonth: true,
changeYear: true,
yearRange: '1990:2025'
});
});
</script>
</head>
<body>
<input type="text" id="datepicker" placeholder="Select date">
</body>
</html>
8. COMPLETE AJAX + PHP EXAMPLE
Check Phone Number Uniqueness (2025 Question):
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Phone Check</title>
<script>
function checkPhone() {
let phone = document.getElementById('phone').value;
if(phone.length == 10) {
let xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status == 200) {
document.getElementById('message').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'checkPhone.php?phone=' + phone, true);
xhr.send();
}
}
</script>
</head>
<body>
<h2>Student Registration</h2>
Phone: <input type="text" id="phone" onkeyup="checkPhone()" maxlength="10">
<span id="message"></span>
</body>
</html>
checkPhone.php:
<?php
$phone = $_GET['phone'];
$conn = mysqli_connect('localhost', 'root', '', 'school');
$sql = "SELECT * FROM students WHERE phone='$phone'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0) {
echo "<span style='color:red'>⚠️ Phone number already exists</span>";
} else {
echo "<span style='color:green'>✓ Phone number available</span>";
}
mysqli_close($conn);
?>
9. CMS (Content Management System)
What is CMS?
- Software to create/manage websites without coding
- Examples: WordPress, Joomla, Drupal
Features of CMS:
- User-friendly interface - No coding needed
- Multiple users - Different roles (admin, editor, author)
- Templates/Themes - Ready-made designs
- Plugins/Extensions - Add functionality easily
- SEO-friendly - Built-in optimization
- Media management - Upload/organize images/videos
- Content scheduling - Publish posts at specific times
WordPress Basics:
Adding Pages:
- Login to WordPress admin
- Dashboard → Pages → Add New
- Enter title and content
- Click "Publish"
Creating Submenus:
- Appearance → Menus
- Create new menu
- Add pages to menu
- Drag items to create hierarchy (indent = submenu)
- Assign menu to location
- Save
Theme vs Template:
- Theme: Complete design package (all styling, layout, functionality)
- Template: Individual page layout within theme (e.g., homepage template, blog template)
10. MVC ARCHITECTURE
MVC = Model-View-Controller
User → Controller → Model → Database
↓ ↓
View ←------┘
Controller: Handles user input, decides what to do
Model: Interacts with database, business logic
View: Displays data to user (HTML)
Example:
User clicks "Show Users"
→ Controller receives request
→ Controller asks Model to get users from database
→ Model queries database and returns data
→ Controller passes data to View
→ View displays users in HTML table
Benefits:
- Separation of concerns
- Easier to maintain
- Multiple developers can work simultaneously
- Reusable code
🎯 QUICK REVISION CHECKLIST
Must Know for Exam:
JavaScript:
- ✅ Array operations (reduce, map, forEach)
- ✅ Event handling (onclick, onmouseover)
- ✅ DOM access (getElementById, querySelector)
- ✅ Calculator program
- ✅ Arrow functions
- ✅ Dialog boxes (alert, confirm, prompt)
PHP:
- ✅ Form validation (empty, filter_var, preg_match)
- ✅ Database connection (mysqli_connect, mysqli_query)
- ✅ $_POST, $_GET, $_SESSION, $_FILES
- ✅ Arrays (indexed, associative, multidimensional)
- ✅ File upload validation
- ✅ Chess board program
OOP:
- ✅ Class, Constructor (__construct)
- ✅ Inheritance (extends, parent::)
- ✅ Interface (implements)
- ✅ Method overriding
AJAX:
- ✅ XMLHttpRequest object
- ✅ open(), send(), onload
- ✅ Checking data without reload
jQuery:
- ✅ Selectors ($('#id'), $('.class'))
- ✅ Effects (hide, show, fade, slide)
- ✅ DatePicker widget
- ✅ jQuery AJAX
🔥 FINAL EXAM STRATEGY
Group B (5 marks each) - Answer 4-5:
- Pick questions with code examples (more marks)
- Write code neatly with comments
- If explaining concepts, give 1-2 examples
Group C (10 marks each) - Answer 2:
- ALWAYS attempt: Form + Database validation question
- Second choice: Calculator OR OOP inheritance
- Write complete, working code
- Add validation and error handling
Time Management:
- Group B: 10-12 minutes each
- Group C: 25-30 minutes each
- Keep 15 minutes for review
Scoring Tips:
- Even partial code gets marks
- Comments show understanding
- Proper indentation = professional
- Test your logic mentally before writing
You're ready! Which topic do you want me to clarify or drill down on before your exam?