Comp Computer Science

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), or var (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>

DOM tree structure diagram**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).
Client (Browser)HTML/CSS/JSNetworkHTTPServer (PHP)PHP scriptsDatabaseSQL
Typical client‑server flow for a web app using JavaScript on the client and PHP on the server.

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

  1. Syntax Error: Missing ; or {.
    let x = 5  // Error: Missing semicolon
    
  2. Reference Error: Using an undefined variable.
    console.log(y);  // Error: y is not defined
    
  3. Type Error: Calling a non-function.
    "5".toUpperCase();  // Error: Strings don’t have this method
    
init()handleClick()updateDOM()updateDOM()
Call stack at the moment a JavaScript runtime error is thrown.

PHP Errors

  1. Undefined Variable: Not declaring $var.
    echo $name;  // Error if $name isn’t defined
    
  2. 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

  1. Syntax Matters: Memorize basic syntax (e.g., for loops, if conditions).
  2. Trace Programs: Given a short script, predict the output (e.g., loop iterations).
  3. DOM Questions: Know how to select elements (getElementById, querySelector).
  4. PHP Forms: Understand $_POST/$_GET and input sanitization.
  5. Debugging: Practice fixing errors in given code snippets.
  6. 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

  1. Differentiate between == and === in JavaScript.
  2. Write a PHP script to check if a number is even or odd.

Programming

  1. Write a JavaScript function to reverse a string.
    function reverseString(str) {
      return str.split("").reverse().join("");
    }
    console.log(reverseString("hello"));  // "olleh"
    
  2. Create a PHP page that displays "Welcome" if the URL parameter ?name=John is passed.

Debugging

  1. Fix the error in this JavaScript code:
    let sum = 0;
    for (let i = 1 to 5) {  // Error: Use <, not 'to'
      sum += i;
    }
    console.log(sum);  // Should output 15
    
    Correction:
    for (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…