Computer ScienceUnit 39 min read
JavaScript & PHP: Scripting, DOM, and Server-Side Logic
Unit 3 of Computer Science covers JavaScript’s core features (variables, loops, DOM manipulation) and PHP’s server-side workflow, with hands-on examples, syntax comparisons, and real-world applications like form handling and dynamic web pages.
TAKEAWAYS:
- JavaScript runs in browsers and manipulates web pages using the DOM API (e.g., changing HTML/CSS dynamically).
- PHP executes on the server, processes data (e.g., form submissions), and generates HTML before sending it to the browser.
- Both languages use variables, loops, and functions but differ in execution environment (client vs. server).
- Common tasks: JavaScript handles user interactions; PHP handles database queries and secure data processing.
- NEB exams test syntax, debugging, and simple program traces—practice writing short scripts and identifying errors.
1. JavaScript: The Client-Side Scripting Language
JavaScript (JS) is a programming language that runs in web browsers. It makes web pages interactive by responding to user actions (e.g., clicks, form inputs) and dynamically updating content without reloading the page.
Key Concepts
A. Variables and Data Types
Variables store data. JS uses:
let(re-declarable),const(fixed), orvar(older, avoid).- Data types:
Example: Variable Declaration
let age = 20; // Number
const name = "Alice"; // String
let isStudent = true; // Boolean
B. Operators
JS supports arithmetic (+, -, *), comparison (==, ===), and logical (&&, ||) operators.
Example: Comparison
console.log(5 == '5'); // true (loose equality)
console.log(5 === '5'); // false (strict equality)
C. Conditional Statements
Control flow using if, else if, else, and switch.
Example: Grade Checker
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B"); // Output
}
D. Loops
Repeat code with for, while, or do...while.
Example: Print Numbers 1–5
for (let i = 1; i <= 5; i++) {
console.log(i); // Output: 1, 2, 3, 4, 5
}
E. Functions
Reusable blocks of code. Use function or arrow syntax () => {}.
Example: Greeting Function
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Bob")); // Output: "Hello, Bob!"
F. The Document Object Model (DOM)
The DOM is a tree-like structure representing HTML elements. JS can:
- Access elements:
document.getElementById("id"). - Modify content:
element.innerHTML = "New text". - Handle events:
button.addEventListener("click", myFunction).
Example: Change Text on Click
<button id="myBtn">Click Me</button>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
document.body.innerHTML = "<h1>Button Clicked!</h1>";
});
</script>
Visualization of how HTML elements are nested in the DOM (Image: Lubaochuan, CC BY-SA 4.0, via Wikimedia Commons)
2. PHP: Server-Side Scripting
PHP (Hypertext Preprocessor) runs on the server and generates HTML before sending it to the browser. It’s used for:
- Processing form data.
- Interacting with databases (e.g., MySQL).
- Dynamic content (e.g., user logins).
erDiagram
USER ||--o{ POST : writes
USER {
int id PK
string username
string password_hash
timestamp created_at
}
POST {
int id PK
int user_id FK
string title
string content
timestamp posted_at
}
COMMENT "PHP interacts with databases via SQL queries (e.g., INSERT INTO POST...)"Database schema for a blog system (PHP + MySQL example)Key Concepts
A. PHP Syntax Basics
- Code is embedded in HTML using
<?php ... ?>. - Variables start with
$.
Example: Hello World
<?php
echo "Hello, World!";
?>
B. Variables and Data Types
PHP supports:
- Strings (
"text"), numbers (5,3.14), booleans (true/false), arrays ($arr = [1, 2, 3]).
Example: Array
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[1]; // Output: "Banana"
C. Conditional Logic
Same as JS but with elseif.
Example: Check User Role
$role = "admin";
if ($role == "admin") {
echo "Welcome, Admin!";
} elseif ($role == "user") {
echo "Welcome, User!";
}
D. Loops
for, while, and foreach work similarly to JS.
Example: Loop Through Array
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
E. Forms and PHP
PHP processes form data using $_POST or $_GET.
Example: Form Handling
<!-- HTML Form -->
<form action="process.php" method="POST">
Name: <input type="text" name="name"><br>
<input type="submit" value="Submit">
</form>
// process.php
$name = $_POST["name"];
echo "Hello, " . htmlspecialchars($name); // Sanitize input!
F. File Handling
Read/write files with fopen(), fwrite(), fread().
Example: Write to a File
$file = fopen("data.txt", "w");
fwrite($file, "Hello, File!");
fclose($file);
3. JavaScript vs. PHP: Key Differences
| Feature | JavaScript | PHP |
|---|---|---|
| Execution | Client-side (browser) | Server-side |
| Use Case | User interactions, DOM manipulation | Form processing, database queries |
| Syntax | let x = 5; |
$x = 5; |
| Example | document.getElementById() |
mysql_query() (for databases) |
4. Practical Applications
- JavaScript:
- Validating forms before submission.
- Creating animations (e.g., sliders).
- Fetching data from APIs (e.g., weather apps).
- PHP:
- User authentication (login systems).
- Database-driven websites (e.g., blogs).
- Processing payments (e.g., e-commerce).
5. Common Errors and Debugging
stateDiagram-v2
[*] --> Debugging
Debugging --> CheckSyntax: "SyntaxError?"
CheckSyntax --> FixCode: "Yes"
FixCode --> [*]
CheckSyntax --> CheckVariables: "No"
CheckVariables --> LogOutput: "Undefined variable?"
LogOutput --> [*]
CheckVariables --> CheckTypes: "Type mismatch?"
CheckTypes --> [*]
state Debugging {
note "PHP/JS debugging workflow"
}Debugging process for JavaScript/PHP errors (trace execution flow)JavaScript Errors
- Syntax Error: Missing
;or{.let x = 5 // Error: Missing semicolon - Reference Error: Using an undefined variable.
console.log(y); // Error: y is not defined - Type Error: Calling a non-function.
"5".toUpperCase(); // Error: Strings don’t have this method
PHP Errors
- Undefined Variable: Not declaring
$var.echo $name; // Error if $name isn’t defined - SQL Injection: Always use
htmlspecialchars()or prepared statements.// UNSAFE: Vulnerable to SQL injection $sql = "SELECT * FROM users WHERE name = '" . $_POST['name'] . "'";// SAFE: Use prepared statements $stmt = $pdo->prepare("SELECT * FROM users WHERE name = ?"); $stmt->execute([$_POST['name']]);
6. NEB Exam Tips
- Syntax Matters: Memorize basic syntax (e.g.,
forloops,ifconditions). - Trace Programs: Given a short script, predict the output (e.g., loop iterations).
- DOM Questions: Know how to select elements (
getElementById,querySelector). - PHP Forms: Understand
$_POST/$_GETand input sanitization. - Debugging: Practice fixing errors in given code snippets.
- Diagrams: Draw client-server interactions or DOM trees if asked.
Solved Examples
Example 1: JavaScript Output Prediction
let x = 10;
for (let i = 0; i < 3; i++) {
x += i;
console.log(x);
}
Output:
10 (i=0: 10 + 0 = 10)
11 (i=1: 10 + 1 = 11)
13 (i=2: 11 + 2 = 13)
Example 2: PHP Form Handling
HTML (index.html):
<form action="process.php" method="POST">
Email: <input type="text" name="email"><br>
<input type="submit">
</form>
PHP (process.php):
$email = $_POST["email"];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email: " . htmlspecialchars($email);
} else {
echo "Invalid email!";
}
NEB Board-Style Questions
Short Answer
- Differentiate between
==and===in JavaScript. - Write a PHP script to check if a number is even or odd.
Programming
- Write a JavaScript function to reverse a string.
function reverseString(str) { return str.split("").reverse().join(""); } console.log(reverseString("hello")); // "olleh" - Create a PHP page that displays "Welcome" if the URL parameter
?name=Johnis passed.
Debugging
- Fix the error in this JavaScript code:
Correction:let sum = 0; for (let i = 1 to 5) { // Error: Use <, not 'to' sum += i; } console.log(sum); // Should output 15for (let i = 1; i <= 5; i++) { ... }
Summary
- JavaScript: Client-side, dynamic content, DOM manipulation.
- PHP: Server-side, form processing, database interactions.
- Practice: Write small scripts, debug errors, and understand client-server flow.
Based on the NEB +2 Science syllabus for Computer Science (Comp), unit 3.
Discussion
Loading…