Web Technology II
Unit:- 3
Class 12: Web Technology II┬╖ NEB Exam Preparation Guide
How to use this guide: Learn the concepts and comparison tables first, then type out every code example yourself and run it in a browser (JavaScript) or XAMPP (PHP). Code questions are a major part of this unit, so practice the programs at the end of each section. Practice questions are at the end of the guide.
Table of Contents
- Web Technology and Web Development
- Scripting Languages
- Client-Side vs Server-Side Scripting
- Static vs Dynamic Websites
- JavaScript: Introduction
- Adding JavaScript to HTML
- JavaScript Fundamentals
- Operators in JavaScript
- Functions
- Control Structures
- Objects in JavaScript
- Document Object Model (DOM)
- Events and Event Handling
- Form Validation
- jQuery
- Server-Side Scripting with PHP
- PHP Basics
- PHP Data Types and Operators
- Object-Oriented Programming in PHP
- PHP Form Handling
- Database Connectivity with PHP and MySQL
- Sample Programs
- Quick Revision Table
- Practice Questions
1. Web Technology and Web Development
Web technology
Web technology means the tools and techniques that let computers communicate and share content over the Internet. It combines:
- The Web (WWW): a huge collection of web pages and resources, each located by a URL
- Technology: browsers, markup and programming languages, databases, protocols (HTTP/HTTPS), and multimedia
Web development
Web development is the process of designing, building, and maintaining websites or web applications that run on the Internet or an intranet. It ranges from a simple static page to complex systems like social media or e-commerce sites.
It includes web design, content creation, client-side scripting, server-side scripting, and database work.
Front end vs back end
| Basis | Front end (client side) | Back end (server side) |
|---|---|---|
| Concerned with | What the user sees and interacts with | What happens on the server |
| Technologies | HTML, CSS, JavaScript, jQuery, AJAX | PHP, Python, Java, Ruby, Node.js, ASP.NET, databases |
| Developer | Front-end developer | Back-end developer |
A full-stack developer works on both the front end and the back end, including connecting to databases.
2. Scripting Languages
Definition
A scripting language is a programming language, usually interpreted (run line by line), used to automate tasks and add behavior to other software such as web pages, servers, and applications. Scripts commonly run inside another program (for example, a browser or a web server).
Applications of scripting languages
- Creating dynamic web pages and web applications
- Games and multimedia
- Automating repeated tasks
- Statistics and research (Python, R)
- Plug-ins and extensions for existing software
Common scripting languages
| Language | Key points |
|---|---|
| JavaScript | The main language of the web; runs in browsers (and on servers with Node.js); makes pages interactive |
| PHP | Server-side language for dynamic websites; works well with MySQL |
| Python | Simple, English-like syntax; used in web, automation, data science |
| Perl | Strong in text processing and system administration |
| Ruby | Clean syntax, focus on productivity (used with Ruby on Rails) |
| Bash | Shell scripting for Linux/Unix command automation |
| Node.js | Runtime environment that lets JavaScript run on the server |
| VBScript | Microsoft's scripting language based on Visual Basic; worked mainly in old Internet Explorer, so JavaScript is preferred today |
Note: jQuery is a JavaScript library, and ASP.NET is a web framework by Microsoft (not languages themselves).
Scripting language vs programming language
| Basis | Scripting language | Programming language |
|---|---|---|
| Execution | Mostly interpreted | Mostly compiled |
| Speed | Generally slower | Generally faster |
| Code length | Usually less code to write | Usually more code |
| Standalone programs | Normally runs inside another program (browser, server) | Can create standalone applications |
| Typing | Mostly dynamic | Often static |
| Examples | JavaScript, PHP, Python, Perl | C, C++, Java |
The line between the two is not strict: Python and JavaScript are used for both scripting and full applications.
3. Client-Side vs Server-Side Scripting
Client-side scripting
Code that runs in the user's web browser, without needing the server to process it. It is mostly used to make the interface interactive. Examples: JavaScript, jQuery.
| Advantages | Disadvantages |
|---|---|
| Instant response to the user | Code is visible to anyone (less secure) |
| Reduces load on the server and network traffic | Users can disable it in the browser |
| Makes pages more interactive and attractive | Depends on browser support |
| Faster page behavior | Cannot connect to a database directly |
Server-side scripting
Code that runs on the web server, which processes the request, works with databases/files, and sends HTML output back to the browser. Examples: PHP, ASP.NET, Python, Ruby, Node.js.
| Advantages | Disadvantages |
|---|---|
| Can create dynamic pages from database data | Needs a server and scripting software installed |
| Source code stays hidden from the user | Response is slower because it needs a request to the server |
| Can access databases and server files | Server may slow or crash under heavy load |
| User authentication and secure control | Hosting and development can cost more |
| Independent of the user's browser |
Difference between client-side and server-side scripting
| Basis | Client-side | Server-side |
|---|---|---|
| Runs on | User's browser | Web server |
| Code visible to user? | Yes | No |
| Database access | Not directly | Yes |
| Security | Lower | Higher |
| Response speed | Faster (no server trip) | Slower |
| Can user disable it? | Yes | No |
| Depends on browser? | Yes | No |
| Examples | JavaScript, jQuery | PHP, ASP.NET, Python |
4. Static vs Dynamic Websites
Static website
A website whose pages are fixed: every visitor sees the same content until the developer edits the page's source code.
- Built with HTML and CSS (sometimes with JavaScript for small effects)
- Interactivity is mostly limited to hyperlinks
| Advantages | Disadvantages |
|---|---|
| Quick and cheap to build and host | Needs a developer to update content |
| Fast loading | No real interaction or personalization |
| Simple, secure, few technical errors | Content can become outdated |
| Needs little technical knowledge | Hard to manage when the site grows |
Examples: a small business info page, a personal portfolio, a school notice page.
Dynamic website
A website whose content changes according to the user, time, or database data. Different visitors can see different content from the same page code.
- Uses server-side languages (PHP, ASP.NET, JSP, Python) and a database (MySQL)
- Examples of features: login, sign-up, forms, shopping cart, comments
| Advantages | Disadvantages |
|---|---|
| Content is easy to update (often via a CMS) | Costlier and more complex to develop |
| Interactive and personalized | Needs skilled developers |
| Shows real-time data | Needs a more powerful (costlier) server |
| Can be used for e-commerce, forums, bookings | Generally slower than a static page |
Static vs dynamic website
| Basis | Static | Dynamic |
|---|---|---|
| Content | Fixed | Changes with user/data |
| Technologies | HTML, CSS | HTML, CSS, JavaScript + PHP/ASP/Python + database |
| Update | Edit source code | Update through admin panel / database |
| Development cost | Low | High |
| Speed | Faster | Slower |
| Interactivity | Low | High |
| Examples | Brochure site | Online store, social media |
5. JavaScript: Introduction
JavaScript (JS) is a lightweight, interpreted scripting language used to make web pages interactive and dynamic. It runs in the browser (client side).
Important: JavaScript and Java are completely different languages. They share part of a name only.
Features
- Interpreted (no compilation) and lightweight
- Runs in all major browsers on all operating systems
- Case sensitive (
nameandNameare different) - Embedded directly in HTML
- Supports events, objects, functions, and dynamic typing
Advantages
- Less server load: can validate user input before sending it to the server
- Immediate feedback to users
- Interactive pages: menus, sliders, pop-ups, games
- Easy to learn and quick to develop
- Richer interfaces: drag-and-drop, animations
- Works on all browsers and platforms
Uses of JavaScript
- Client-side form validation
- Dynamic menus and pop-up windows/dialog boxes
- Displaying date and time
- Event handling
- Browser games and mobile apps
- Building servers (with Node.js)
6. Adding JavaScript to HTML
There are three ways to add JavaScript to a web page.
6.1 Embedded (internal) script
Place code inside <script> tags in the <head> or <body>.
<!DOCTYPE html>
<html>
<head>
<title>Embedded Script</title>
</head>
<body>
<script>
document.write("Welcome to JavaScript");
</script>
</body>
</html>
6.2 Inline script
Put JavaScript directly inside an HTML event attribute (e.g. onclick).
<button onclick="alert('Hello Class 12')">Click Here</button>
6.3 External file
Save code in a separate .js file and link it with the src attribute. This keeps code reusable and pages clean.
hello.js
function display() {
alert("Hello Friends!");
}
index.html
<!DOCTYPE html>
<html>
<body>
<input type="button" value="Result" onclick="display()">
<script src="hello.js"></script>
</body>
</html>
| Method | Best for |
|---|---|
| Embedded | Small scripts used on one page |
| Inline | Quick, single event actions |
| External | Reusing code across many pages (best practice) |
7. JavaScript Fundamentals
Statements and comments
A JavaScript program is a series of statements executed in order, usually ending with a semicolon ;.
// Single-line comment
var area = 5 * 4; // comment after a statement
/* Multi-line
comment */
- JavaScript ignores extra spaces, tabs, and blank lines.
- JavaScript is case sensitive:
TimeandTIMEare different names.
Ways to display output
| Method | Where it shows | Example |
|---|---|---|
document.write() | On the web page | document.write(7 + 5); |
innerHTML | Inside an HTML element | document.getElementById("demo").innerHTML = "Hi"; |
alert() | In a pop-up alert box | alert(7 + 5); |
console.log() | In the browser's developer console | console.log(7 + 5); |
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
window.prompt()takes input from the user andwindow.confirm()asks OK/Cancel.
Variables
A variable is a named storage location for data.
Rules for variable names (identifiers):
- Must start with a letter, underscore (
_), or dollar sign ($) - After the first character, digits are allowed
- Reserved words (like
if,for,class) cannot be used - Names are case sensitive
| Valid | Invalid |
|---|---|
var x = 10; | var 123 = 30; (starts with a digit) |
var _value = "Hari"; | var *aa = 320; (illegal character) |
var total_marks = 85; | var for = 5; (reserved word) |
var x = 10;
var y = 20;
var z = x + y;
document.write(z); // 30
Modern JavaScript also uses
letandconst.varis used in most NEB examples.
Local vs global variables: a variable declared inside a function is local (works only there); one declared outside is global (works everywhere).
Reserved words (examples)
break, case, catch, class, const, continue, default, delete, do, else, false, finally, for, function, if, in, instanceof, new, null, return, switch, this, throw, true, try, typeof, var, void, while, with
Data types
JavaScript is dynamically typed: you do not declare a type, it is decided from the value.
var a = 40; // number
var b = "Rahul"; // string
| Category | Type | Description | Example |
|---|---|---|---|
| Primitive | String | Text | "hello" |
| Number | Integers and decimals | 100, 3.14 | |
| Boolean | true or false | true | |
| Undefined | Variable declared but no value assigned | var x; | |
| Null | Intentional "no value" | var y = null; | |
| Non-primitive | Object | Collection of properties and methods | {id: 1} |
| Array | Ordered list of values | [1, 2, 3] | |
| RegExp | Regular expression pattern | /abc/ |
8. Operators in JavaScript
An operator performs an operation on operands. In 10 + 20, + is the operator and 10 and 20 are operands.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 20 | 30 |
- | Subtraction | 20 - 10 | 10 |
* | Multiplication | 10 * 20 | 200 |
/ | Division | 20 / 10 | 2 |
% | Modulus (remainder) | 20 % 3 | 2 |
++ | Increment | a++ (a=10) | 11 |
-- | Decrement | a-- (a=10) | 9 |
Comparison (relational) operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to (value) | 10 == 20 | false |
=== | Strictly equal (value and type) | 10 === "10" | false |
!= | Not equal | 10 != 20 | true |
> | Greater than | 20 > 10 | true |
>= | Greater than or equal | 20 >= 10 | true |
< | Less than | 20 < 10 | false |
<= | Less than or equal | 20 <= 10 | false |
Logical operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
&& | AND (both true) | (10 == 10 && 5 > 2) | true |
|| | OR (at least one true) | (10 == 20 || 5 > 2) | true |
! | NOT (reverses) | !(10 == 20) | true |
Assignment operators
| Operator | Meaning | Example (a = 10) | Result |
|---|---|---|---|
= | Assign | a = 10 | 10 |
+= | Add and assign | a += 20 | 30 |
-= | Subtract and assign | a -= 5 | 5 |
*= | Multiply and assign | a *= 2 | 20 |
/= | Divide and assign | a /= 2 | 5 |
%= | Modulus and assign | a %= 3 | 1 |
Bitwise operators
They work on the binary form of numbers (32-bit).
| Operator | Name | Example | Binary | Result |
|---|---|---|---|---|
& | AND | 5 & 1 | 0101 & 0001 | 1 |
| | OR | 5 | 1 | 0101 | 0001 | 5 |
^ | XOR | 5 ^ 1 | 0101 ^ 0001 | 4 |
~ | NOT | ~5 | inverts all bits | -6 |
<< | Left shift | 5 << 1 | 0101 тЖТ 1010 | 10 |
>> | Right shift | 5 >> 1 | 0101 тЖТ 0010 | 2 |
Special operators
| Operator | Purpose |
|---|---|
?: | Conditional (ternary): condition ? valueIfTrue : valueIfFalse |
typeof | Gives the data type of a value |
new | Creates a new object |
delete | Deletes an object property |
instanceof | Checks whether an object belongs to a type |
in | Checks whether a property exists in an object |
void | Discards the return value of an expression |
, | Comma: evaluates several expressions in one statement |
String operator
The + operator joins (concatenates) strings.
var first = "Rajesh";
var last = "Hamal";
document.write(first + " " + last); // Rajesh Hamal
9. Functions
A function is a reusable block of code that performs a specific task and runs only when it is called.
Advantages of functions
- Reusability: write once, use many times
- Divides a large program into small, manageable parts (modular)
- Makes code easier to read, test, and maintain
- Reduces repeated code
Syntax
function functionName(parameter1, parameter2) {
// statements
return value; // optional
}
Calling a function
<script>
function hello() {
document.write("Hello Class 12");
}
hello(); // function call
</script>
Function with parameters
<script>
function add(a, b) {
var sum = a + b;
document.write("Sum = " + sum);
}
add(3, 4); // Sum = 7
</script>
Function with return value
The return statement sends a value back to the caller and stops the function.
<script>
function multiply(x, y) {
return x * y;
}
var result = multiply(12, 20);
document.write(result); // 240
</script>
Calling a function from an event
<input type="button" value="Click Here" onclick="hello()">
10. Control Structures
10.1 Selection (decision) statements
if statement
if (a > 10) {
document.write("a is greater than 10");
}
if...else statement
var a = 17;
if (a % 2 == 0) {
document.write("Even number");
} else {
document.write("Odd number");
}
if...else if...else statement
var num = Number(prompt("Enter a number"));
if (num > 0) {
document.write("Positive");
} else if (num < 0) {
document.write("Negative");
} else {
document.write("Zero");
}
switch statement
Chooses one block from many options by comparing a value with each case. break stops execution from "falling through" to the next case.
var grade = 'B';
var result;
switch (grade) {
case 'A':
result = "Excellent";
break;
case 'B':
result = "Good";
break;
case 'C':
result = "Average";
break;
default:
result = "No grade";
}
document.write(result);
Day-name example:
var n = Number(prompt("Enter a number between 1 and 7"));
switch (n) {
case 1: document.write("Sunday"); break;
case 2: document.write("Monday"); break;
case 3: document.write("Tuesday"); break;
case 4: document.write("Wednesday"); break;
case 5: document.write("Thursday"); break;
case 6: document.write("Friday"); break;
case 7: document.write("Saturday"); break;
default: document.write("Invalid day");
}
10.2 Loops (iteration)
A loop repeats a block of code.
| Loop | When to use | Condition checked |
|---|---|---|
for | Number of repetitions is known | Before each iteration |
while | Repeat while a condition is true | Before each iteration (entry-controlled) |
do...while | Must run at least once | After each iteration (exit-controlled) |
for loop
for (var i = 1; i <= 5; i++) {
document.write(i + "<br>");
}
// Output: 1 2 3 4 5 (each on a new line)
while loop (even numbers 1 to 20)
var i = 2;
while (i <= 20) {
document.write(i + " ");
i = i + 2;
}
do...while loop
var i = 1;
do {
document.write(i + "<br>");
i = i + 2;
} while (i <= 10);
11. Objects in JavaScript
An object is a collection of properties (values) and methods (functions) stored as name: value pairs. A variable holds one value; an object can hold many.
- Property: a variable inside an object
- Method: a function inside an object
- Access with the dot (
.) operator:objectName.propertyName
Three ways to create an object
1. Object literal
var emp = { id: 101, name: "Ram Prasad", salary: 50000 };
document.write(emp.id + " " + emp.name + " " + emp.salary);
With a method:
var vehicle = {
color: "green",
move: function () {
document.write("Vehicle moves");
}
};
vehicle.move();
2. Using new Object()
var student = new Object();
student.roll = 10;
student.name = "Rajesh Hamal";
student.class = 12;
document.write(student.roll + "<br>" + student.name + "<br>" + student.class);
3. Using an object constructor
The this keyword refers to the current object.
function Emp(id, name, salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
var e = new Emp(103, "Anjan Bista", 30000);
document.write(e.id + " " + e.name + " " + e.salary);
12. Document Object Model (DOM)
Definition
The DOM represents an HTML page as a tree of objects. When a page loads, the browser creates a document object (window.document), which is the root. JavaScript can use it to read and change the page.
What JavaScript can do with the DOM
- Change HTML elements and attributes
- Change CSS styles
- Add or remove elements
- React to events
Common methods of the document object
| Method | Purpose |
|---|---|
write("text") | Writes text into the document |
writeln("text") | Writes text followed by a newline |
getElementById("id") | Returns the element with that id |
getElementsByName("name") | Returns all elements with that name |
getElementsByTagName("tag") | Returns all elements of that tag (e.g., p, h2) |
getElementsByClassName("class") | Returns all elements with that class |
getElementById() and innerHTML
getElementById is a method; innerHTML is a property that gets or sets an element's content.
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "How are you?";
</script>
Cube of a number:
<script>
function getCube() {
var n = document.getElementById("number").value;
alert(n * n * n);
}
</script>
<form>
Enter number: <input type="text" id="number"><br>
<input type="button" value="Cube" onclick="getCube()">
</form>
getElementsByName()
<script>
function totalElements() {
var g = document.getElementsByName("gender");
alert("Total options: " + g.length);
}
</script>
<form>
Male: <input type="radio" name="gender" value="male">
Female: <input type="radio" name="gender" value="female">
<input type="button" value="Count" onclick="totalElements()">
</form>
getElementsByTagName()
<script>
function countPara() {
var p = document.getElementsByTagName("p");
alert("Total paragraphs: " + p.length);
}
</script>
<p>First paragraph</p>
<p>Second paragraph</p>
<button onclick="countPara()">Count paragraphs</button>
Accessing a form field value
Syntax: document.formName.fieldName.value
<script>
function printValue() {
var name = document.form1.name.value;
alert("Welcome: " + name);
}
</script>
<form name="form1">
Enter name: <input type="text" name="name">
<input type="button" value="Print name" onclick="printValue()">
</form>
Changing an image (Image object)
Each <img> is an image object; its src property can be changed with JavaScript (used for rollover effects).
<img id="pic" src="image1.jpg" width="150"
onmouseover="document.getElementById('pic').src='image2.jpg'"
onmouseout="document.getElementById('pic').src='image1.jpg'">
Dynamic HTML with innerHTML
<script>
function showCommentForm() {
var data = "Name: <input type='text'><br>" +
"Comment:<br><textarea rows='4' cols='40'></textarea><br>" +
"<input type='submit' value='Post Comment'>";
document.getElementById("mylocation").innerHTML = data;
}
</script>
<form>
<input type="button" value="Comment" onclick="showCommentForm()">
<div id="mylocation"></div>
</form>
13. Events and Event Handling
Definition
An event is an action or change that happens on a web page, such as a click, key press, or page load. Event handling is reacting to events using JavaScript code, via event handlers (such as onclick).
Common events
| Category | Event | Handler | Occurs when |
|---|---|---|---|
| Mouse | Click | onclick | Element is clicked |
| Mouse over | onmouseover | Pointer moves over an element | |
| Mouse out | onmouseout | Pointer leaves an element | |
| Mouse down | onmousedown | Mouse button pressed over element | |
| Mouse up | onmouseup | Mouse button released | |
| Mouse move | onmousemove | Mouse moves | |
| Keyboard | Key down | onkeydown | A key is pressed |
| Key up | onkeyup | A key is released | |
| Form | Focus | onfocus | Element receives focus |
| Blur | onblur | Element loses focus | |
| Change | onchange | Value of a form element changes | |
| Submit | onsubmit | Form is submitted | |
| Window / document | Load | onload | Page finishes loading |
| Unload | onunload | User leaves the page | |
| Resize | onresize | Browser window is resized |
Examples
Click event
<script>
function clickEvent() {
document.write("Button was clicked");
}
</script>
<input type="button" value="Click to view" onclick="clickEvent()">
Mouse over event
<script>
function mouseOverEvent() {
alert("Mouse is over the paragraph");
}
</script>
<p onmouseover="mouseOverEvent()">Keep the mouse pointer over me</p>
Focus event (changes background colour)
<input type="text" id="input1" onfocus="focusEvent()">
<script>
function focusEvent() {
document.getElementById("input1").style.background = "aqua";
}
</script>
Key down event
<input type="text" onkeydown="keyDownEvent()">
<script>
function keyDownEvent() {
alert("A key was pressed");
}
</script>
Load event
<body onload="alert('Page loaded successfully')">
<p>Welcome</p>
</body>
14. Form Validation
Why validate?
Form validation checks user input before it is sent to the server, so wrong or empty data is caught early. Client-side validation with JavaScript is fast and reduces server load.
Important: Client-side validation can be bypassed, so important data must also be validated on the server.
How it works
The form's onsubmit event calls a function. If the function returns false, the form is not submitted.
Name and password validation
<script>
function validateForm() {
var name = document.myform.name.value;
var password = document.myform.password.value;
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (password.length < 6) {
alert("Password must be at least 6 characters long");
return false;
}
return true;
}
</script>
<form name="myform" method="post" action="register.php" onsubmit="return validateForm()">
Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
Retype (confirm) password validation
<script>
function matchPass() {
var p1 = document.f1.password.value;
var p2 = document.f1.password2.value;
if (p1 == p2) {
return true;
} else {
alert("Passwords must be the same");
return false;
}
}
</script>
<form name="f1" action="register.php" onsubmit="return matchPass()">
Password: <input type="password" name="password"><br>
Re-enter password: <input type="password" name="password2"><br>
<input type="submit">
</form>
Number validation
isNaN() returns true if the value is Not a Number.
<script>
function validateNumber() {
var num = document.myform.num.value;
if (isNaN(num) || num == "") {
document.getElementById("numloc").innerHTML = "Enter numeric value only";
return false;
}
return true;
}
</script>
<form name="myform" onsubmit="return validateNumber()">
Number: <input type="text" name="num">
<span id="numloc"></span><br>
<input type="submit" value="Submit">
</form>
Email validation
A valid email must contain @ and ., with at least one character before @, and at least two characters after the last dot.
<script>
function validateEmail() {
var x = document.myform.email.value;
var atPos = x.indexOf("@");
var dotPos = x.lastIndexOf(".");
if (atPos < 1 || dotPos < atPos + 2 || dotPos + 2 >= x.length) {
alert("Please enter a valid e-mail address");
return false;
}
return true;
}
</script>
<form name="myform" method="post" action="#" onsubmit="return validateEmail()">
Email: <input type="text" name="email"><br>
<input type="submit" value="Register">
</form>
15. jQuery
Definition
jQuery is a fast, small, feature-rich JavaScript library with the motto "write less, do more." It makes DOM manipulation, event handling, animation, and AJAX much simpler, and works across browsers.
Features
- Small, fast, and lightweight
- Easy DOM selection and manipulation
- Simple event handling
- Built-in animation effects
- Easy AJAX support
- Cross-browser compatible
- Free and open source
Basic example
jQuery must be included before use (from a CDN or a downloaded file).
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$("p").hide();
});
});
</script>
</head>
<body>
<p>This paragraph will disappear.</p>
<button id="btn">Hide</button>
</body>
</html>
$()selects elements;$(document).ready()runs code after the page loads.
16. Server-Side Scripting with PHP
Definition
PHP (Hypertext Preprocessor) is an open-source, server-side scripting language used to build dynamic web pages. PHP code runs on the server; the browser receives only the resulting HTML.
Characteristics
- Simple and easy to learn
- Interpreted (no compilation needed)
- Open source and free
- Cross-platform (Windows, Linux, macOS)
- Embedded directly in HTML
- Works especially well with MySQL
- Supports many protocols (HTTP, POP3, IMAP, LDAP, SNMP)
- Supports object-oriented programming
- Loosely (dynamically) typed
Strengths (advantages)
- Free, widely used, and has a large community
- Built for web development
- Easy to install and connect to databases
- Handles forms, sessions, and cookies
- Can control user access, encrypt data, and handle files
Weaknesses (disadvantages)
- Very flexible, so careless coding can lead to poor structure and security problems
- Interpreted languages can be slower than compiled ones
- Some inconsistencies in older functions
- Large applications can become hard to maintain without good planning
Common uses
- Creating, reading, writing, and deleting files on the server
- Processing forms and sending data by email
- Adding, deleting, and modifying database records
- Setting and reading cookies; managing sessions
- Restricting access to pages
Requirements to run PHP
| Requirement | Purpose |
|---|---|
| Web browser | Viewing the output |
| Web server (Apache) | Receives requests and runs PHP |
| PHP interpreter | Executes PHP code |
| MySQL (optional) | Database storage |
Packages such as XAMPP, WAMP (Windows), and LAMP (Linux) install all of these together. PHP files are saved with the .php extension inside the web server's root folder (e.g., htdocs in XAMPP) and opened through http://localhost/.
17. PHP Basics
Basic syntax
A PHP script starts with <?php and ends with ?>. Every statement ends with a semicolon ;.
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello Class 12";
?>
</body>
</html>
Case sensitivity
- Keywords, functions, and class names are not case sensitive (
echo,ECHO,EcHoall work) - Variable names are case sensitive (
$ageand$AGEare different)
Comments
<?php
// single-line comment
# also a single-line comment
/* multi-line
comment */
?>
Variables
Rules:
- Start with a
$sign followed by the name - The name must start with a letter or underscore, not a number
- Can contain only letters, digits, and underscores
- Case sensitive
PHP is loosely typed: it decides the data type automatically from the value.
<?php
$str = "hello string";
$x = 200;
$y = 44.6;
echo "String is: $str <br>";
echo "Integer is: $x <br>";
echo "Float is: $y <br>";
?>
Variable scope
| Scope | Where it works |
|---|---|
| Local | Only inside the function where it is declared |
| Global | Declared outside functions; to use it inside a function, write global $name; |
| Static | Local variable declared with static that keeps its value between function calls |
<?php
// Local variable
function localVar() {
$num = 45;
echo "Local variable: $num";
}
localVar();
// Global variable
$name = "Sanaya Sharma";
function globalVar() {
global $name;
echo "Inside function: $name";
}
globalVar();
echo "Outside function: $name";
// Static variable
function counter() {
static $count = 0;
$count++;
echo $count;
}
counter(); // 1
counter(); // 2
?>
echo vs print
| Basis | echo | |
|---|---|---|
| Type | Language construct | Language construct |
| Return value | None | Always returns 1 |
| Multiple arguments | Yes (comma separated) | No |
| Speed | Slightly faster | Slightly slower |
| Parentheses | Optional | Optional |
<?php
echo "<h2>PHP is fun!</h2>";
echo "This ", "string ", "uses multiple parameters.";
print "<br>Hello Class 12!";
?>
18. PHP Data Types and Operators
Data types
| Type | Description | Example |
|---|---|---|
| String | Text in single or double quotes | "Hello" |
| Integer | Whole number (positive or negative, no decimal point) | 34 |
| Float (double) | Number with a decimal point | 19.34 |
| Boolean | TRUE or FALSE | true |
| Array | Stores multiple values in one variable | array("a", "b") |
| Object | Instance of a class | new Bike() |
| NULL | Special type with only one value, no value | $n = NULL; |
| Resource | Reference to an external resource, like a database connection | mysqli connection |
Compound types: array, object Special types: resource, NULL
Integer notation: decimal 34, octal 0243 (= 163), hexadecimal 0x45 (= 69).
Single vs double quotes: variables are expanded inside double quotes only.
<?php
$company = "ABC";
echo "Hello $company"; // Hello ABC
echo 'Hello $company'; // Hello $company
?>
Array example
<?php
$bikes = array("Royal Enfield", "Yamaha", "KTM");
echo "First: $bikes[0] <br>";
echo "Second: $bikes[1] <br>";
echo "Third: $bikes[2]";
?>
Operators
Arithmetic
| Operator | Name | Example |
|---|---|---|
+ | Addition | $a + $b |
- | Subtraction | $a - $b |
* | Multiplication | $a * $b |
/ | Division | $a / $b |
% | Modulus (remainder) | $a % $b |
** | Exponentiation | $a ** $b |
Assignment
| Operator | Meaning |
|---|---|
= | Assign |
+= | $a = $a + $b |
-= | $a = $a - $b |
*= | $a = $a * $b |
/= | $a = $a / $b |
%= | $a = $a % $b |
Comparison
| Operator | Meaning |
|---|---|
== | Equal (value) |
=== | Identical (value and data type) |
!= or <> | Not equal |
!== | Not identical |
<, >, <=, >= | Less than, greater than, and so on |
<=> | Spaceship: returns -1, 0, or 1 |
Increment / decrement
| Operator | Name | Effect |
|---|---|---|
++$a | Pre-increment | Increase first, then use |
$a++ | Post-increment | Use first, then increase |
--$a | Pre-decrement | Decrease first, then use |
$a-- | Post-decrement | Use first, then decrease |
Logical
| Operator | Meaning |
|---|---|
&& or and | True if both are true |
|| or or | True if either is true |
xor | True if exactly one is true |
! | NOT: reverses the result |
Bitwise
& (AND), | (OR), ^ (XOR: 1 only if bits differ), ~ (NOT), << (shift left), >> (shift right)
Other categories: string operators (. joins strings), array operators, type operators, and execution operators.
19. Object-Oriented Programming in PHP
Object-oriented programming (OOP) models software around real-world objects. A class is a blueprint that defines properties and methods; an object is an instance of a class.
Three principles of OOP
| Principle | Meaning | Purpose |
|---|---|---|
| Encapsulation | Hiding internal details and exposing only needed methods (using private/public access and getter/setter methods) | Reduces complexity, protects data |
| Inheritance | A child class takes properties and methods from a parent class (using extends) | Code reuse |
| Polymorphism | One interface, many forms; the same method name behaves differently in different classes (method overriding, interfaces using implements) | Easier maintenance and extension |
Example: class and object
<?php
class Bike {
public $model = "Royal Enfield";
function showModel() {
echo "Bike model: " . $this->model;
}
}
$obj = new Bike();
$obj->showModel();
?>
Example: inheritance
<?php
class Vehicle {
function start() { echo "Vehicle started<br>"; }
}
class Car extends Vehicle {
function honk() { echo "Car honks"; }
}
$c = new Car();
$c->start(); // inherited from Vehicle
$c->honk();
?>
20. PHP Form Handling
PHP receives form data through the super global arrays $_GET and $_POST. The form's method attribute decides which one to use.
GET method
Data is sent in the URL (visible in the address bar). GET is the default method.
form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name">
<input type="submit" value="Visit">
</form>
welcome.php
<?php
$name = $_GET["name"];
echo "Welcome, $name";
?>
POST method
Data is sent in the body of the request (not shown in the URL).
form2.html
<form action="login.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
login.php
<?php
$name = $_POST["name"];
$password = $_POST["password"];
echo "Welcome, $name";
?>
GET vs POST
| Basis | GET | POST |
|---|---|---|
| Data location | In the URL | In the request body |
| Visibility | Visible in the address bar | Not shown in the URL |
| Amount of data | Limited | Much larger (files, long text) |
| Security | Less secure for sensitive data | Better, but still use HTTPS for real security |
| Bookmark | Can be bookmarked | Cannot be bookmarked |
| Caching | Can be cached | Not cached |
| Typical use | Searching, fetching data | Login, registration, uploads |
| Default | Yes | No (must be specified) |
| Super global | $_GET | $_POST |
21. Database Connectivity with PHP and MySQL
MySQL is the most popular database used with PHP. PHP connects to it using the mysqli extension. (Review SQL commands in Unit 1.)
Steps
- Connect to the MySQL server and select the database
- Run an SQL query
- Process the result
- Close the connection
Connecting to the database
<?php
$servername = "localhost";
$username = "root";
$password = ""; // default empty in XAMPP
$dbname = "school";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Inserting a record
<?php
$sql = "INSERT INTO Students (StudentID, FName, LName, Address, Class)
VALUES (101, 'Ram', 'Sharma', 'Pokhara', 7)";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $conn->error;
}
?>
Selecting and displaying records
<?php
$sql = "SELECT StudentID, FName, LName FROM Students";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["StudentID"] . " - " . $row["FName"] . " " . $row["LName"] . "<br>";
}
} else {
echo "No records found";
}
$conn->close();
?>
22. Sample Programs
JavaScript programs
1. Sum of two numbers (using prompt)
<script>
var a = parseInt(prompt("Enter the first number"));
var b = parseInt(prompt("Enter the second number"));
document.write("Sum = " + (a + b));
</script>
2. Sum of two numbers using a form
<script>
function add() {
var a = Number(document.getElementById("first").value);
var b = Number(document.getElementById("second").value);
document.getElementById("answer").value = a + b;
}
</script>
First number: <input id="first"><br>
Second number: <input id="second"><br>
<button onclick="add()">Add</button>
<input id="answer">
3. Check positive, negative, or zero
<script>
var a = Number(prompt("Enter a number"));
if (a > 0) {
document.write("Number is positive");
} else if (a < 0) {
document.write("Number is negative");
} else {
document.write("Number is zero");
}
</script>
4. Even or odd
<script>
var num = Number(prompt("Enter a number"));
if (num % 2 == 0) {
document.write("Even number");
} else {
document.write("Odd number");
}
</script>
5. Prime number check
<script>
var num = Number(prompt("Enter a number"));
var isPrime = true;
if (num < 2) {
isPrime = false;
}
for (var i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
document.write(num + " is a prime number");
} else {
document.write(num + " is not a prime number");
}
</script>
6. Sum of array elements
<script>
var arr = new Array(1, 2, 3, 5, 9);
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
document.write("Sum = " + sum); // 20
</script>
PHP programs
1. Enter a name and display it
<html>
<body>
<form method="post">
Enter your name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo "Your name = $name";
}
?>
</body>
</html>
2. Factorial of a number
<html>
<body>
<form method="post">
Input a number: <input type="number" name="number">
<input type="submit" value="Calculate">
</form>
<?php
if (isset($_POST['number'])) {
$n = $_POST['number'];
$fact = 1;
for ($i = 1; $i <= $n; $i++) {
$fact = $fact * $i;
}
echo "The factorial of $n = $fact";
}
?>
</body>
</html>
3. Even numbers up to 50
<?php
for ($i = 2; $i <= 50; $i += 2) {
echo $i . " ";
}
?>
4. Simple interest
<html>
<body>
<form method="post">
Principal: <input type="number" name="p"><br>
Time (years): <input type="number" name="t"><br>
Rate (%): <input type="number" name="r"><br>
<input type="submit" value="Calculate SI">
</form>
<?php
if (isset($_POST['p'], $_POST['t'], $_POST['r'])) {
$p = $_POST['p'];
$t = $_POST['t'];
$r = $_POST['r'];
$si = ($p * $t * $r) / 100;
echo "Simple Interest = $si";
}
?>
</body>
</html>
23. Quick Revision Table
| Topic | Key point |
|---|---|
| Web development | Designing and building websites; front end + back end |
| Client-side script | Runs in browser (JavaScript); visible; no DB access |
| Server-side script | Runs on server (PHP); hidden; can access DB |
| Static website | Fixed content; HTML + CSS |
| Dynamic website | Content changes; needs server language + database |
| JavaScript | Interpreted, case sensitive, not Java |
| Ways to add JS | Embedded, inline, external file |
| Output in JS | document.write, innerHTML, alert, console.log |
| Data types (JS) | String, Number, Boolean, Undefined, Null, Object, Array |
== vs === | Value only vs value and type |
| Loops | for, while, do...while |
| Object creation | Literal, new Object(), constructor |
| DOM | Tree representation of an HTML page |
| Event | An action such as click or load; handled by handlers |
| Form validation | Checks input before submission; onsubmit + return false |
| jQuery | JavaScript library: "write less, do more" |
| PHP | Server-side, open source, embedded in HTML |
| PHP variable | Starts with $; case sensitive |
| echo vs print | echo has no return value; print returns 1 |
| GET vs POST | URL vs body; limited vs large data |
$_GET, $_POST | PHP super globals for form data |
| MySQL connection | new mysqli(host, user, password, database) |
| OOP principles | Encapsulation, inheritance, polymorphism |
24. Practice Questions
Short-answer questions
- What is web technology? Differentiate between front end and back end.
- What is a scripting language? Differentiate between scripting and programming languages.
- Differentiate between client-side and server-side scripting.
- Differentiate between static and dynamic websites.
- What is JavaScript? List its advantages.
- Write the three ways to add JavaScript to an HTML page.
- What is a function? Write its advantages.
- What is DOM? Name any four methods of the document object.
- What is an event? List any four JavaScript events and their handlers.
- What is form validation? Why is it needed?
- What is jQuery? Write any four features.
- Differentiate between
echoandprintin PHP. - Differentiate between GET and POST methods.
- Write the rules for naming variables in PHP.
- Name the three principles of OOP.
Long-answer questions
- Explain client-side and server-side scripting with their advantages and disadvantages.
- Explain the different types of operators in JavaScript with examples.
- Explain the control structures in JavaScript with syntax and examples.
- Explain the different ways of creating objects in JavaScript.
- What is PHP? Explain its strengths, weaknesses, and uses.
- Explain PHP data types with examples.
- Explain how a PHP script connects to a MySQL database.
Programs to practice
JavaScript:
- Input two numbers and display their sum.
- Check whether a number is positive, negative, or zero.
- Check whether a number is even or odd.
- Check whether a number is prime.
- Display numbers from 1 to 10 using a
forloop. - Validate a form: name must not be empty and password must be at least 6 characters.
- Validate an email address.
- Create a function that returns the product of two numbers.
PHP:
- Display your name using a form.
- Find the factorial of a number.
- Display all even numbers up to 50.
- Calculate simple interest.
- Connect to a database and display all records from a
Studentstable.
Fill in the blanks
- JavaScript is a ______ sensitive language. (case)
- The ______ attribute of the
<script>tag links an external JavaScript file. (src) - In PHP, every variable name starts with the ______ sign. (
$) - The ______ loop always executes at least once. (do...while)
- PHP receives data sent by the POST method using the ______ array. (
$_POST) - The ______ operator in JavaScript compares both value and data type. (
===)
Prepared for NEB Class 12 Computer Science exam revision. Always cross-check key definitions with your prescribed textbook and your teacher's guidance.