PHP, JavaScript, and jQuery: Key Concepts
Associative Arrays in PHP
Associative arrays use named keys instead of index numbers. Here’s an example of a two-dimensional associative array:
$students = array(
"John" => array("age" => 20, "grade" => "A"),
"Jane" => array("age" => 22, "grade" => "B")
);
foreach ($students as $name => $details) {
echo "$name: Age - " . $details["age"] . ", Grade - " . $details["grade"] . "<br>";
}
Sessions and Cookies in PHP
Session: A way to store data across multiple pages securely on the server-side.
session_start();
$_SESSION["user"] = "JohnDoe";
echo $_SESSION["user"];
Cookie: Stores data on the client-side with an expiration time.
setcookie("user", "JohnDoe", time() + 3600, "/");
echo $_COOKIE["user"];
Difference Between GET and POST (File Upload)
GET: Appends data to the URL, insecure for sensitive information. POST: Sends data in the request body, more secure. Here is an example of file upload using POST:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"])) {
echo "File uploaded successfully";
} else {
echo "Upload failed";
}
}
AJAX Example
AJAX allows updating web pages asynchronously.
<input type="text" id="num1"> + <input type="text" id="num2">
<button onclick="calculate()">Check Even/Odd</button>
<p id="result"></p>
<script></script>
Importance of Server-Side Scripting
Server-side scripting:
- Handles authentication
- Manages database interactions
- Provides security and validation
Example of form validation in PHP:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["name"])) {
echo "Hello, " . htmlspecialchars($_POST["name"]);
} else {
echo "Name is required!";
}
}
Content Management System (CMS)
A CMS like WordPress manages digital content efficiently. Key components include:
- Themes: Define the website’s design.
- Templates: Predefined page layouts.
- Plugins: Extend functionalities (SEO, forms, etc.).
- Pages: Static content (About Us, Contact, etc.).
Display Customer Records with Delete Option in PHP
$conn = new mysqli("localhost", "root", "", "myDB");
$result = $conn->query("SELECT * FROM customers");
while ($row = $result->fetch_assoc()) {
echo "{$row['name']} <a href='delete.php?id={$row['id']}'>Delete</a><br>";
}
Delete Script (delete.php)
$conn = new mysqli("localhost", "root", "", "myDB");
$id = $_GET["id"];
$conn->query("DELETE FROM customers WHERE id=$id");
header("Location: index.php");
DOM Manipulation in jQuery
Changing Content:
$("#id").text("New text");
Modifying CSS:
$("#id").css("color", "red");
Adding Elements:
$("#id").append("<p>New</p>");
Removing Elements:
$("#id").remove();
Abstract Class vs Interface in PHP
Abstract class: Contains both implemented and abstract methods.
abstract class Animal {
abstract function makeSound();
}
Interface: Defines a contract that classes must implement.
interface Vehicle {
public function drive();
}
JavaScript Event Handling
Two methods to register event handlers:
Inline Event Handler:
<button onclick="alert('Clicked!')">Click</button>
Event Listener:
document.getElementById("btn").addEventListener("click", function() {
alert("Clicked!");
});
Common JavaScript Events:
onclick
– When an element is clicked.onmouseover
– When the mouse hovers over an element.onkeydown
– When a key is pressed.onchange
– When an input field value changes.onload
– When a page is loaded.
Signup Form Validation in JavaScript
document.getElementById("submit").addEventListener("click", function() {
let name = document.getElementById("name").value;
if (name == "") {
document.getElementById("error").innerText = "Name is required";
}
});
What is JavaScript?
JavaScript is a scripting language used to create dynamic and interactive web pages.
Four JavaScript Functions
alert() – Displays a pop-up alert box.
alert("Welcome to JavaScript!");
parseInt() – Converts a string into an integer.
let num = parseInt("123"); console.log(num);
setTimeout() – Executes a function after a delay.
setTimeout(function() { alert("Hello after 3 seconds!"); }, 3000);
toUpperCase() – Converts a string to uppercase.
let text = "hello"; console.log(text.toUpperCase()); // Outputs: HELLO
Why is jQuery Needed?
jQuery is a JavaScript library that simplifies tasks like DOM manipulation, AJAX, animations, and event handling.
Example: Hiding an <img> tag using jQuery
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<img id="image" src="image.jpg" width="200px">
<button onclick="$('#image').hide();">Hide Image</button>
</body>
</html>
File Upload Function in PHP
PHP allows users to upload files using the $_FILES
superglobal.
Example: Uploading a File in PHP
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload">
<input type="submit" value="Upload">
</form>
</body>
</html>
if ($_FILES["fileToUpload"]["error"] == 0) {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/" . $_FILES["fileToUpload"]["name"]);
echo "File uploaded successfully!";
} else {
echo "Error uploading file!";
}
Server-Side Script to Check Unique Username
This script checks if the username already exists without refreshing the page.
JavaScript (AJAX Request)
function checkUsername() {
let username = document.getElementById("username").value;
let xhr = new XMLHttpRequest();
xhr.open("GET", "check_username.php?username=" + username, true);
xhr.onload = function() {
document.getElementById("result").innerHTML = xhr.responseText;
};
xhr.send();
}
HTML Form
<input type="text" id="username" onkeyup="checkUsername()" placeholder="Enter Username">
<span id="result"></span>
PHP (check_username.php)
$conn = new mysqli("localhost", "root", "", "users_db");
$username = $_GET["username"];
$result = $conn->query("SELECT * FROM users WHERE username='$username'");
if ($result->num_rows > 0) {
echo "Username already taken!";
} else {
echo "Username available!";
}
Different Types of Arrays in PHP
PHP supports three types of arrays:
Indexed Array (Stores values with numeric keys)
$fruits = ["Apple", "Banana", "Mango"];
echo $fruits[1]; // Output: Banana
$student = ["name" => "John", "age" => 22];
echo $student["name"]; // Output: John
$cars = [
["BMW", 2023, "Black"],
["Toyota", 2022, "White"]
];
echo $cars[0][0]; // Output: BMW
Form to Calculate the Area of a Circle in JavaScript
<!DOCTYPE html>
<html>
<body>
<input type="text" id="radius" placeholder="Enter Radius">
<button onclick="calculateArea()">Calculate</button>
<p>Area: <span id="result"></span></p>
<script></script>
</body>
</html>
Object-Oriented PHP Code to Display Color/Mileage
<?php
class Car {
public $color;
public $mileage;
public function __construct($color, $mileage) {
$this->color = $color;
$this->mileage = $mileage;
}
public function displayInfo() {
echo "Color: " . $this->color . ", Mileage: " . $this->mileage;
}
}
$myCar = new Car("Red", 15000);
$myCar->displayInfo();
?>
JavaScript Program: Numbers, Even, Odd, and Prime
<!DOCTYPE html>
<html>
<head>
<title>Number Highlighter</title>
<style>
.even { color: blue; }
.odd { color: green; }
.prime { color: red; }
</style>
</head>
<body>
<input type="number" id="userInput" placeholder="Enter a number">
<button onclick="generateNumbers()">Generate</button>
<div id="result"></div>
<script></script>
</body>
</html>
NoScript Tag and JavaScript Event
NoScript Tag: Used to display alternate content for users who have disabled JavaScript.
JavaScript Event: An action that occurs on an HTML element, such as click, hover, or keypress.
Example of Event Handling:
<button onclick="displayMessage()">Click Me</button>
<p id="message"></p>
<script></script>
jQuery and Selectors
jQuery is a lightweight JavaScript library that simplifies HTML DOM manipulation.
Types of Selectors in jQuery:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p class="classSelector">Class Selector</p>
<p id="idSelector">ID Selector</p>
<p>Element Selector</p>
<script></script>
</body>
</html>
PHP Data Types and Finding the Largest Number
PHP Data Types: Integer, Float, String, Boolean, Array, Object, NULL, Resource.
PHP Program to Find Largest Among Three Numbers:
<?php
$a = 10; $b = 20; $c = 15;
$largest = ($a > $b) ? (($a > $c) ? $a : $c) : (($b > $c) ? $b : $c);
echo "Largest number is: " . $largest;
?>
Sessions vs Cookies
Feature | Sessions | Cookies |
---|---|---|
Storage | Server-side | Client-side |
Expiry | Ends when browser closes or session timeout | Set expiration time |
Security | More secure | Less secure |
Example:
PHP Session:
session_start();
$_SESSION["user"] = "John";
echo $_SESSION["user"];
PHP Cookie:
setcookie("user", "John", time() + 3600);
echo $_COOKIE["user"];
Short Notes
Creating Sub-menu in WordPress
Go to WordPress Dashboard > Appearance > Menus. Add a menu item and drag it under another item to create a sub-menu. Save the menu.
Constructor in PHP
A special function in a class that initializes objects.
class Car {
function __construct() {
echo "Car Created";
}
}
$c = new Car();
PHP Form Validation and CRUD Operations
HTML Form with JavaScript Calculation
<form>
<input type="number" id="num1">
<input type="number" id="num2">
<button type="button" onclick="calculate()">Calculate</button>
<div id="result"></div>
</form>
<script></script>
Implementing Interface in PHP
<?php
interface Shape {
public function area();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * $this->radius * $this->radius;
}
}
$circle = new Circle(5);
echo $circle->area();
?>
Define JavaScript Event
A JavaScript Event is an action or occurrence detected by the browser, such as a user clicking a button, pressing a key, or loading a page.
Event Handling Example:
<!DOCTYPE html>
<html>
<head>
<title>Event Handling Example</title>
<script>
function showMessage() {
alert('Button Clicked!');
}
</script>
</head>
<body>
<button onclick="showMessage()">Click Me</button>
</body>
</html>
Explanation:
- The
onclick
event is triggered when the button is clicked. - The
showMessage()
function is executed, displaying an alert box with a message.
Immediately Invoked Function in JavaScript
An Immediately Invoked Function Expression (IIFE) is a JavaScript function that executes immediately after being defined. It is useful for creating a private scope and avoiding global variable conflicts.
Example of an IIFE:
(function() {
console.log("This function runs immediately!");
})();
Explanation:
- The function is wrapped in
()
to make it an expression. - The
()
at the end invokes it immediately after declaration.
Array and foreach Loop in PHP
Array in PHP:
An array is a data structure that stores multiple values in a single variable.
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[0]; // Output: Apple
Using foreach
Loop in PHP:
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
Explanation:
- The
foreach
loop iterates over each element of the array. - The variable
$fruit
holds the value of the current array element.
What is jQuery?
jQuery is a fast, lightweight JavaScript library used to simplify HTML DOM manipulation, event handling, and animations.
Types of jQuery Selectors:
Element Selector: Selects HTML elements by tag name.
$("p").css("color", "blue");
Class Selector: Selects elements by class.
$(".myClass").hide();
ID Selector: Selects an element by ID.
$("#myID").fadeOut();
Attribute Selector: Selects elements by attributes.
$("input[type='text']").val("Hello");
Group Selector: Selects multiple elements.
$("h1, p").css("background-color", "yellow");
MVC Architecture
MVC (Model-View-Controller) is a software design pattern used for developing web applications.
- Model: Manages data and business logic.
- View: Displays data (UI).
- Controller: Handles user input and updates the Model/View.
Diagram:
+-------------+ +------------+ +------------+
| Model |----->| View |<-----| Controller |
+-------------+ +------------+ +------------+
| ↑ |
| | |
+---------------------+-------------------+
Function sum() to Add Arbitrary Parameters
<?php
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2); // Output: 3
echo sum(1, 3, 4); // Output: 8
?>
Program to Display Continuous Time
<!DOCTYPE html>
<html>
<head>
<script>
function updateTime() {
var now = new Date();
var time = now.toLocaleTimeString();
document.getElementById("clock").textContent = time;
}
setInterval(updateTime, 1000);
</script>
</head>
<body onload="updateTime()">
<h1 id="clock"></h1>
</body>
</html>
CRUD Operations in PHP (HTML + PHP + SQL)
Database Table (SQL)
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
HTML Form
<form method="POST" action="insert.php">
Name: <input type="text" name="name">
Email: <input type="email" name="email">
<button type="submit">Submit</button>
</form>
Insert Data (PHP)
<?php
$conn = new mysqli("localhost", "root", "", "test");
$name = $_POST['name'];
$email = $_POST['email'];
$conn->query("INSERT INTO users (name, email) VALUES ('$name', '$email')");
?>
Different Ways to Define Functions in JavaScript
JavaScript allows defining functions in multiple ways:
- Function Declaration: A traditional way to define a function that can be hoisted.
function add(a, b) {
return a + b;
}
- Function Expression: Functions stored in variables, not hoisted.
const add = function(a, b) {
return a + b;
};
- Arrow Function: A concise syntax introduced in ES6.
const add = (a, b) => a + b;
Example using an Arrow Function:
const greet = (name) => console.log(`Hello, ${name}!`);
greet("John");
Ways to Add JavaScript in an HTML File
There are three ways to add JavaScript in an HTML file:
Inline JavaScript: Written inside an HTML tag.
<button onclick="alert('Hello from Inline JavaScript!')">Click Me</button>
Internal JavaScript: Written inside the
<script>
tag in the same HTML file.<!DOCTYPE html> <html> <head> <script> function showMessage() { alert('Hello from Internal JavaScript!'); } </script> </head> <body> <button onclick="showMessage()">Click Me</button> </body> </html>
External JavaScript: Written in a separate
.js
file and linked to the HTML file.<!DOCTYPE html> <html> <head> <script src="script.js"></script> </head> <body> <button onclick="showMessage()">Click Me</button> </body> </html>
In
script.js
:function showMessage() { alert('Hello from External JavaScript!'); }
Implementing AJAX in Web Development
AJAX can be implemented using XMLHttpRequest
or fetch API
.
Example: Load content dynamically using JavaScript and PHP
<!DOCTYPE html>
<html>
<head>
<script>
function loadContent() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'content.php', true);
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('content').innerHTML = xhr.responseText;
}
};
xhr.send();
}
</script>
</head>
<body>
<button onclick="loadContent()">Load Content</button>
<div id="content"></div>
</body>
</html>
PHP (content.php)
<?php
echo "This is dynamically loaded content!";
?>
What is JavaScript and its Potential Platforms?
JavaScript is a high-level, interpreted programming language used for adding interactivity, dynamic behavior, and complex functionalities to web pages. It is a lightweight, object-oriented language primarily used for client-side scripting but also supports server-side development through environments like Node.js.
Potential Platforms where JavaScript can be used:
Web Browsers: Used in front-end development for dynamic web applications (Chrome, Firefox, Edge, Safari)… Server-Side Development: Using Node.js, JavaScript can handle backend operations, APIs, and databases. ..Mobile Applications: Frameworks like React Native, Ionic, and NativeScript allow JavaScript to build cross-platform mobile apps. //Game Development: JavaScript is used with WebGL and frameworks like Phaser.js to create browser-based games. .. //Desktop Applications: JavaScript can be used in frameworks like Electron.js to build cross-platform desktop apps.
4. What is CMS? Write steps to handle menu management in CMS.
CMS (Content Management System) is a software that allows users to create, edit, and manage website content without coding.
Steps to Handle Menu Management in CMS:
Login to the CMS Admin Panel (e.g., WordPress, Joomla).
Navigate to Menu Section (Usually under “Appearance” or “Navigation”).
Add/Edit Menu Items (Pages, Categories, Custom Links).
Set Menu Structure (Drag & Drop to reorder).
Save Changes and Publish.
6. What is the benefit of using AJAX? Discuss major methods that communicate with server-side scripting.
Benefits of AJAX:
Allows web pages to be updated asynchronously without reloading.
Improves user experience and application speed.
Reduces server load by fetching only required data.
AJAX Methods:
$.get() – Fetches data from a server.//$.get("data.php", function(response) {
//console.log(response);
//});
$.post() – Sends data to a server. //$.post("save.php", { name: "John" }, function(response) {
//alert(response);
//});
$.ajax() – Custom AJAX request.//$.ajax({
// url: "fetch.php",
// type: "GET",
//success: function(response) {
// console.log(response);
// }
// });