Computer ScienceUnit 310 min read
JavaScript & PHP: Scripting, DOM, AJAX, and Server-Side Basics
Unit 3 of Computer Science covers how JavaScript makes web pages interactive (DOM, events, AJAX) and how PHP connects web pages to databases (forms, sessions, security). You’ll learn syntax, real-world examples, and how these technologies work together.
TAKEAWAYS:
- JavaScript runs in browsers and manipulates HTML/DOM to create dynamic content (e.g., form validation, animations).
- PHP executes on the server, processes data, and sends HTML back to the browser (e.g., handling user logins).
- AJAX lets web pages fetch data from the server without reloading (e.g., live search boxes).
- Both languages use variables, loops, and functions but serve different roles (client-side vs. server-side).
- Security is critical: sanitize inputs in PHP and validate data in JavaScript to prevent attacks like SQL injection.
- NEB exams test syntax, debugging, and simple projects (e.g., a login system or a to-do list app).
1. JavaScript: The Language of Interactive Web Pages
JavaScript (JS) is a client-side scripting language that runs in the browser. It makes web pages dynamic—meaning they can respond to user actions (like clicks or typing) without needing to reload.
How JavaScript Works
- Embedded in HTML: You can write JS directly in an HTML file using
<script>tags or link an external.jsfile. - DOM (Document Object Model): JS interacts with the HTML structure of a page. Think of the DOM as a tree where each HTML element (like
<div>,<button>) is a node. - Events: JS listens for user actions (e.g.,
onclick,onload) and executes code in response.
flowchart TD
A["User Clicks Button"] --> B["JS Event Listener"]
B --> C["JS Code Runs"]
C --> D["DOM Updates (e.g., hide/show elements)"]
D --> E["User Sees Change"]Key Concepts
Variables and Data Types
let,const,vardeclare variables.- Data types:
string,number,boolean,array,object.
let name = "Alice"; // string const age = 20; // number let isStudent = true; // booleanFunctions
- Reusable blocks of code. Example:
function greet(user) { return "Hello, " + user + "!"; } console.log(greet("Bob")); // Output: "Hello, Bob!"DOM Manipulation
- Change HTML content, styles, or attributes using methods like:
document.getElementById("id").innerHTML = "New text";element.style.color = "red";
- Change HTML content, styles, or attributes using methods like:
Events
- Common events:
onclick: When a button is clicked.onload: When the page loads.onchange: When a dropdown value changes.
<button onclick="alert('Clicked!')">Click Me</button>- Common events:
AJAX (Asynchronous JavaScript and XML)
- Lets web pages fetch data from a server without reloading.
- Used in live search boxes, social media feeds, etc.
- Example: Fetching data from a PHP script.
fetch("getdata.php") .then(response => response.json()) .then(data => console.log(data));
2. PHP: Server-Side Scripting
PHP (Hypertext Preprocessor) runs on the server and generates HTML sent to the browser. It’s used for:
- Handling form data.
- Connecting to databases (MySQL).
- Managing user sessions (logins).
How PHP Works
- Embedded in HTML: PHP code is written inside
<?php ... ?>tags. - Executed on the Server: The server processes PHP, sends pure HTML to the browser.
- Dynamic Content: PHP can generate HTML based on user input or database queries.
sequenceDiagram
User->>Browser: Sends HTTP request (e.g., form submission)
Browser->>Server: Request reaches server
Server->>PHP: Executes PHP script
PHP->>Database: Queries MySQL (if needed)
Database-->>PHP: Returns data
PHP->>Browser: Sends HTML response
Browser->>User: Displays updated pageKey Concepts
Variables and Data Types
- Variables start with
$. - Data types:
string,integer,float,boolean,array.
$name = "Alice"; // string $age = 20; // integer $isStudent = true; // boolean- Variables start with
Forms and User Input
- PHP processes data from HTML forms using
$_POSTor$_GET.
<form method="post" action="process.php"> <input type="text" name="username"> <button type="submit">Submit</button> </form>// process.php $username = $_POST['username']; echo "Hello, " . htmlspecialchars($username);- PHP processes data from HTML forms using
Database Connection (MySQLi)
- PHP connects to MySQL databases using
mysqli_connect().
$conn = mysqli_connect("localhost", "user", "password", "dbname"); $result = mysqli_query($conn, "SELECT * FROM users"); while($row = mysqli_fetch_assoc($result)) { echo $row['name']; }- PHP connects to MySQL databases using
Sessions and Cookies
- Sessions: Store user data temporarily (e.g., login status).
session_start(); $_SESSION['user'] = "Alice"; - Cookies: Store data on the user’s browser.
setcookie("user", "Alice", time() + 3600);
- Sessions: Store user data temporarily (e.g., login status).
Security
- Sanitize Inputs: Use
htmlspecialchars()to prevent XSS attacks. - Prepared Statements: Use
mysqli_prepare()to prevent SQL injection.
$stmt = $conn->prepare("INSERT INTO users (name) VALUES (?)"); $stmt->bind_param("s", $username); $stmt->execute();- Sanitize Inputs: Use
3. JavaScript vs. PHP: Key Differences
| Feature | JavaScript | PHP |
|---|---|---|
| Where it runs | Client-side (browser) | Server-side |
| Purpose | Makes pages interactive | Processes data, connects to DBs |
| Execution | Runs instantly in the browser | Runs on the server, sends HTML |
| Example Use | Form validation, animations | Handling logins, database queries |
| Syntax | let x = 5; |
$x = 5; |
| Security | Validate inputs to prevent XSS | Sanitize inputs to prevent SQLi |
4. Combining JavaScript and PHP
- JavaScript handles user interactions (e.g., clicking a button).
- PHP processes the request (e.g., saves data to a database).
- AJAX lets JS send data to PHP without reloading the page.
Example: Live Search Box
- User types in a search box (JS listens for
onkeyup). - JS sends the query to
search.phpvia AJAX. - PHP queries the database and returns results.
- JS updates the page with the results.
sequenceDiagram
User->>JS: Types in search box
JS->>PHP: Sends AJAX request to search.php
PHP->>Database: Queries for matches
Database-->>PHP: Returns results
PHP-->>JS: Sends JSON data
JS->>User: Updates search results dynamically5. Common Errors and Debugging
| Error Type | Example | Fix |
|---|---|---|
| Syntax Error (JS) | Missing ; or } |
Check for typos or missing brackets. |
| Undefined Variable (PHP) | $name not declared |
Declare variables with $. |
| SQL Injection | SELECT * FROM users WHERE id='1 OR 1=1' |
Use prepared statements. |
| AJAX Not Working | fetch() fails silently |
Check server URL and CORS settings. |
| Form Not Submitting | Missing action attribute |
Ensure form has action="script.php". |
Exam Tip: How to Score Full Marks
- Syntax Matters: NEB exams test exact syntax. For example:
- JS:
document.getElementById("id")(notgetElementByIdalone). - PHP:
<?php ... ?>(not<script>tags).
- JS:
- Practical Questions: Expect questions like:
- "Write JS code to validate a form."
- "Explain how AJAX works with a diagram."
- "Write PHP code to connect to a MySQL database."
- Debugging: Questions may ask you to fix broken code. Always:
- Check for typos.
- Verify variable names.
- Test with sample inputs.
- Projects: Some exams include short project questions (e.g., a login system). Break it down:
- HTML form → JS validation → PHP processing → Database storage.
- Security: Always mention sanitization (PHP) or validation (JS) in answers.
Solved Examples
Example 1: JS Form Validation
Question: Write JS code to check if a username is at least 5 characters long.
function validateUsername() {
let username = document.getElementById("username").value;
if (username.length < 5) {
alert("Username must be at least 5 characters!");
return false;
}
return true;
}
HTML:
<input type="text" id="username" onblur="validateUsername()">
Example 2: PHP Database Query
Question: Write PHP to fetch all users from a users table.
<?php
$conn = mysqli_connect("localhost", "user", "password", "dbname");
$result = mysqli_query($conn, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
echo $row['name'] . "<br>";
}
mysqli_close($conn);
?>
Example 3: AJAX Request
Question: Use JS to fetch data from data.php and display it.
fetch("data.php")
.then(response => response.json())
.then(data => {
let div = document.getElementById("result");
div.innerHTML = data.message;
});
NEB Board-Style Questions
Short Answer:
- What is the difference between
letandconstin JavaScript? Answer:letcan be reassigned;constcannot be changed after declaration. - Why is PHP called a server-side language? Answer: PHP executes on the web server, not in the browser.
- What is the difference between
Code Writing:
- Write JS code to change the background color of a
<div>to red when clicked.document.getElementById("myDiv").onclick = function() { this.style.backgroundColor = "red"; }; - Write PHP to create a new user in a MySQL table.
$conn = mysqli_connect("localhost", "user", "password", "dbname"); mysqli_query($conn, "INSERT INTO users (name) VALUES ('Alice')");
- Write JS code to change the background color of a
Explanation:
- Explain how AJAX improves user experience. Answer: AJAX allows pages to update dynamically without reloading, making apps faster and smoother (e.g., Gmail’s live updates).
- What is SQL injection? How can PHP prevent it?
Answer: SQL injection is an attack where malicious SQL code is inserted. PHP prevents it using prepared statements (
mysqli_prepare()).
Debugging:
- Fix this PHP code to display "Hello, World!":
Fix: No fix needed—it’s correct! (But if the output was missing, check for syntax errors or server issues.)// Broken: echo "Hello, World!";
- Fix this PHP code to display "Hello, World!":
Summary Checklist
Before the exam, ensure you can: ✅ Write JS to manipulate the DOM (e.g., change text, handle events). ✅ Use PHP to process forms and connect to MySQL. ✅ Explain AJAX with a diagram. ✅ List security measures for JS and PHP. ✅ Debug common errors in both languages.
Based on the NEB +2 Management syllabus for Computer Science (Comp), unit 3.
Discussion
Loading…