Web Technology II

    Web Technology II

    Reading Mode:

    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

    1. Web Technology and Web Development
    2. Scripting Languages
    3. Client-Side vs Server-Side Scripting
    4. Static vs Dynamic Websites
    5. JavaScript: Introduction
    6. Adding JavaScript to HTML
    7. JavaScript Fundamentals
    8. Operators in JavaScript
    9. Functions
    10. Control Structures
    11. Objects in JavaScript
    12. Document Object Model (DOM)
    13. Events and Event Handling
    14. Form Validation
    15. jQuery
    16. Server-Side Scripting with PHP
    17. PHP Basics
    18. PHP Data Types and Operators
    19. Object-Oriented Programming in PHP
    20. PHP Form Handling
    21. Database Connectivity with PHP and MySQL
    22. Sample Programs
    23. Quick Revision Table
    24. 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

    BasisFront end (client side)Back end (server side)
    Concerned withWhat the user sees and interacts withWhat happens on the server
    TechnologiesHTML, CSS, JavaScript, jQuery, AJAXPHP, Python, Java, Ruby, Node.js, ASP.NET, databases
    DeveloperFront-end developerBack-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

    LanguageKey points
    JavaScriptThe main language of the web; runs in browsers (and on servers with Node.js); makes pages interactive
    PHPServer-side language for dynamic websites; works well with MySQL
    PythonSimple, English-like syntax; used in web, automation, data science
    PerlStrong in text processing and system administration
    RubyClean syntax, focus on productivity (used with Ruby on Rails)
    BashShell scripting for Linux/Unix command automation
    Node.jsRuntime environment that lets JavaScript run on the server
    VBScriptMicrosoft'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

    BasisScripting languageProgramming language
    ExecutionMostly interpretedMostly compiled
    SpeedGenerally slowerGenerally faster
    Code lengthUsually less code to writeUsually more code
    Standalone programsNormally runs inside another program (browser, server)Can create standalone applications
    TypingMostly dynamicOften static
    ExamplesJavaScript, PHP, Python, PerlC, 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.

    AdvantagesDisadvantages
    Instant response to the userCode is visible to anyone (less secure)
    Reduces load on the server and network trafficUsers can disable it in the browser
    Makes pages more interactive and attractiveDepends on browser support
    Faster page behaviorCannot 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.

    AdvantagesDisadvantages
    Can create dynamic pages from database dataNeeds a server and scripting software installed
    Source code stays hidden from the userResponse is slower because it needs a request to the server
    Can access databases and server filesServer may slow or crash under heavy load
    User authentication and secure controlHosting and development can cost more
    Independent of the user's browser

    Difference between client-side and server-side scripting

    BasisClient-sideServer-side
    Runs onUser's browserWeb server
    Code visible to user?YesNo
    Database accessNot directlyYes
    SecurityLowerHigher
    Response speedFaster (no server trip)Slower
    Can user disable it?YesNo
    Depends on browser?YesNo
    ExamplesJavaScript, jQueryPHP, 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
    AdvantagesDisadvantages
    Quick and cheap to build and hostNeeds a developer to update content
    Fast loadingNo real interaction or personalization
    Simple, secure, few technical errorsContent can become outdated
    Needs little technical knowledgeHard 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
    AdvantagesDisadvantages
    Content is easy to update (often via a CMS)Costlier and more complex to develop
    Interactive and personalizedNeeds skilled developers
    Shows real-time dataNeeds a more powerful (costlier) server
    Can be used for e-commerce, forums, bookingsGenerally slower than a static page

    Static vs dynamic website

    BasisStaticDynamic
    ContentFixedChanges with user/data
    TechnologiesHTML, CSSHTML, CSS, JavaScript + PHP/ASP/Python + database
    UpdateEdit source codeUpdate through admin panel / database
    Development costLowHigh
    SpeedFasterSlower
    InteractivityLowHigh
    ExamplesBrochure siteOnline 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 (name and Name are different)
    • Embedded directly in HTML
    • Supports events, objects, functions, and dynamic typing

    Advantages

    1. Less server load: can validate user input before sending it to the server
    2. Immediate feedback to users
    3. Interactive pages: menus, sliders, pop-ups, games
    4. Easy to learn and quick to develop
    5. Richer interfaces: drag-and-drop, animations
    6. 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>
    
    MethodBest for
    EmbeddedSmall scripts used on one page
    InlineQuick, single event actions
    ExternalReusing 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: Time and TIME are different names.

    Ways to display output

    MethodWhere it showsExample
    document.write()On the web pagedocument.write(7 + 5);
    innerHTMLInside an HTML elementdocument.getElementById("demo").innerHTML = "Hi";
    alert()In a pop-up alert boxalert(7 + 5);
    console.log()In the browser's developer consoleconsole.log(7 + 5);
    <p id="demo"></p>
    <script>
      document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script>
    

    window.prompt() takes input from the user and window.confirm() asks OK/Cancel.

    Variables

    A variable is a named storage location for data.

    Rules for variable names (identifiers):

    1. Must start with a letter, underscore (_), or dollar sign ($)
    2. After the first character, digits are allowed
    3. Reserved words (like if, for, class) cannot be used
    4. Names are case sensitive
    ValidInvalid
    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 let and const. var is 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
    
    CategoryTypeDescriptionExample
    PrimitiveStringText"hello"
    NumberIntegers and decimals100, 3.14
    Booleantrue or falsetrue
    UndefinedVariable declared but no value assignedvar x;
    NullIntentional "no value"var y = null;
    Non-primitiveObjectCollection of properties and methods{id: 1}
    ArrayOrdered list of values[1, 2, 3]
    RegExpRegular 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

    OperatorMeaningExampleResult
    +Addition10 + 2030
    -Subtraction20 - 1010
    *Multiplication10 * 20200
    /Division20 / 102
    %Modulus (remainder)20 % 32
    ++Incrementa++ (a=10)11
    --Decrementa-- (a=10)9

    Comparison (relational) operators

    OperatorMeaningExampleResult
    ==Equal to (value)10 == 20false
    ===Strictly equal (value and type)10 === "10"false
    !=Not equal10 != 20true
    >Greater than20 > 10true
    >=Greater than or equal20 >= 10true
    <Less than20 < 10false
    <=Less than or equal20 <= 10false

    Logical operators

    OperatorMeaningExampleResult
    &&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

    OperatorMeaningExample (a = 10)Result
    =Assigna = 1010
    +=Add and assigna += 2030
    -=Subtract and assigna -= 55
    *=Multiply and assigna *= 220
    /=Divide and assigna /= 25
    %=Modulus and assigna %= 31

    Bitwise operators

    They work on the binary form of numbers (32-bit).

    OperatorNameExampleBinaryResult
    &AND5 & 10101 & 00011
    |OR5 | 10101 | 00015
    ^XOR5 ^ 10101 ^ 00014
    ~NOT~5inverts all bits-6
    <<Left shift5 << 10101 тЖТ 101010
    >>Right shift5 >> 10101 тЖТ 00102

    Special operators

    OperatorPurpose
    ?:Conditional (ternary): condition ? valueIfTrue : valueIfFalse
    typeofGives the data type of a value
    newCreates a new object
    deleteDeletes an object property
    instanceofChecks whether an object belongs to a type
    inChecks whether a property exists in an object
    voidDiscards 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.

    LoopWhen to useCondition checked
    forNumber of repetitions is knownBefore each iteration
    whileRepeat while a condition is trueBefore each iteration (entry-controlled)
    do...whileMust run at least onceAfter 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

    MethodPurpose
    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

    CategoryEventHandlerOccurs when
    MouseClickonclickElement is clicked
    Mouse overonmouseoverPointer moves over an element
    Mouse outonmouseoutPointer leaves an element
    Mouse downonmousedownMouse button pressed over element
    Mouse uponmouseupMouse button released
    Mouse moveonmousemoveMouse moves
    KeyboardKey downonkeydownA key is pressed
    Key uponkeyupA key is released
    FormFocusonfocusElement receives focus
    BluronblurElement loses focus
    ChangeonchangeValue of a form element changes
    SubmitonsubmitForm is submitted
    Window / documentLoadonloadPage finishes loading
    UnloadonunloadUser leaves the page
    ResizeonresizeBrowser 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

    1. Small, fast, and lightweight
    2. Easy DOM selection and manipulation
    3. Simple event handling
    4. Built-in animation effects
    5. Easy AJAX support
    6. Cross-browser compatible
    7. 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

    1. Simple and easy to learn
    2. Interpreted (no compilation needed)
    3. Open source and free
    4. Cross-platform (Windows, Linux, macOS)
    5. Embedded directly in HTML
    6. Works especially well with MySQL
    7. Supports many protocols (HTTP, POP3, IMAP, LDAP, SNMP)
    8. Supports object-oriented programming
    9. 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

    RequirementPurpose
    Web browserViewing the output
    Web server (Apache)Receives requests and runs PHP
    PHP interpreterExecutes 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, EcHo all work)
    • Variable names are case sensitive ($age and $AGE are different)

    Comments

    <?php
      // single-line comment
      # also a single-line comment
      /* multi-line
         comment */
    ?>
    

    Variables

    Rules:

    1. Start with a $ sign followed by the name
    2. The name must start with a letter or underscore, not a number
    3. Can contain only letters, digits, and underscores
    4. 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

    ScopeWhere it works
    LocalOnly inside the function where it is declared
    GlobalDeclared outside functions; to use it inside a function, write global $name;
    StaticLocal 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

    Basisechoprint
    TypeLanguage constructLanguage construct
    Return valueNoneAlways returns 1
    Multiple argumentsYes (comma separated)No
    SpeedSlightly fasterSlightly slower
    ParenthesesOptionalOptional
    <?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

    TypeDescriptionExample
    StringText in single or double quotes"Hello"
    IntegerWhole number (positive or negative, no decimal point)34
    Float (double)Number with a decimal point19.34
    BooleanTRUE or FALSEtrue
    ArrayStores multiple values in one variablearray("a", "b")
    ObjectInstance of a classnew Bike()
    NULLSpecial type with only one value, no value$n = NULL;
    ResourceReference to an external resource, like a database connectionmysqli 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

    OperatorNameExample
    +Addition$a + $b
    -Subtraction$a - $b
    *Multiplication$a * $b
    /Division$a / $b
    %Modulus (remainder)$a % $b
    **Exponentiation$a ** $b

    Assignment

    OperatorMeaning
    =Assign
    +=$a = $a + $b
    -=$a = $a - $b
    *=$a = $a * $b
    /=$a = $a / $b
    %=$a = $a % $b

    Comparison

    OperatorMeaning
    ==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

    OperatorNameEffect
    ++$aPre-incrementIncrease first, then use
    $a++Post-incrementUse first, then increase
    --$aPre-decrementDecrease first, then use
    $a--Post-decrementUse first, then decrease

    Logical

    OperatorMeaning
    && or andTrue if both are true
    || or orTrue if either is true
    xorTrue 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

    PrincipleMeaningPurpose
    EncapsulationHiding internal details and exposing only needed methods (using private/public access and getter/setter methods)Reduces complexity, protects data
    InheritanceA child class takes properties and methods from a parent class (using extends)Code reuse
    PolymorphismOne 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

    BasisGETPOST
    Data locationIn the URLIn the request body
    VisibilityVisible in the address barNot shown in the URL
    Amount of dataLimitedMuch larger (files, long text)
    SecurityLess secure for sensitive dataBetter, but still use HTTPS for real security
    BookmarkCan be bookmarkedCannot be bookmarked
    CachingCan be cachedNot cached
    Typical useSearching, fetching dataLogin, registration, uploads
    DefaultYesNo (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

    1. Connect to the MySQL server and select the database
    2. Run an SQL query
    3. Process the result
    4. 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

    TopicKey point
    Web developmentDesigning and building websites; front end + back end
    Client-side scriptRuns in browser (JavaScript); visible; no DB access
    Server-side scriptRuns on server (PHP); hidden; can access DB
    Static websiteFixed content; HTML + CSS
    Dynamic websiteContent changes; needs server language + database
    JavaScriptInterpreted, case sensitive, not Java
    Ways to add JSEmbedded, inline, external file
    Output in JSdocument.write, innerHTML, alert, console.log
    Data types (JS)String, Number, Boolean, Undefined, Null, Object, Array
    == vs ===Value only vs value and type
    Loopsfor, while, do...while
    Object creationLiteral, new Object(), constructor
    DOMTree representation of an HTML page
    EventAn action such as click or load; handled by handlers
    Form validationChecks input before submission; onsubmit + return false
    jQueryJavaScript library: "write less, do more"
    PHPServer-side, open source, embedded in HTML
    PHP variableStarts with $; case sensitive
    echo vs printecho has no return value; print returns 1
    GET vs POSTURL vs body; limited vs large data
    $_GET, $_POSTPHP super globals for form data
    MySQL connectionnew mysqli(host, user, password, database)
    OOP principlesEncapsulation, inheritance, polymorphism

    24. Practice Questions

    Short-answer questions

    1. What is web technology? Differentiate between front end and back end.
    2. What is a scripting language? Differentiate between scripting and programming languages.
    3. Differentiate between client-side and server-side scripting.
    4. Differentiate between static and dynamic websites.
    5. What is JavaScript? List its advantages.
    6. Write the three ways to add JavaScript to an HTML page.
    7. What is a function? Write its advantages.
    8. What is DOM? Name any four methods of the document object.
    9. What is an event? List any four JavaScript events and their handlers.
    10. What is form validation? Why is it needed?
    11. What is jQuery? Write any four features.
    12. Differentiate between echo and print in PHP.
    13. Differentiate between GET and POST methods.
    14. Write the rules for naming variables in PHP.
    15. Name the three principles of OOP.

    Long-answer questions

    1. Explain client-side and server-side scripting with their advantages and disadvantages.
    2. Explain the different types of operators in JavaScript with examples.
    3. Explain the control structures in JavaScript with syntax and examples.
    4. Explain the different ways of creating objects in JavaScript.
    5. What is PHP? Explain its strengths, weaknesses, and uses.
    6. Explain PHP data types with examples.
    7. Explain how a PHP script connects to a MySQL database.

    Programs to practice

    JavaScript:

    1. Input two numbers and display their sum.
    2. Check whether a number is positive, negative, or zero.
    3. Check whether a number is even or odd.
    4. Check whether a number is prime.
    5. Display numbers from 1 to 10 using a for loop.
    6. Validate a form: name must not be empty and password must be at least 6 characters.
    7. Validate an email address.
    8. Create a function that returns the product of two numbers.

    PHP:

    1. Display your name using a form.
    2. Find the factorial of a number.
    3. Display all even numbers up to 50.
    4. Calculate simple interest.
    5. Connect to a database and display all records from a Students table.

    Fill in the blanks

    1. JavaScript is a ______ sensitive language. (case)
    2. The ______ attribute of the <script> tag links an external JavaScript file. (src)
    3. In PHP, every variable name starts with the ______ sign. ($)
    4. The ______ loop always executes at least once. (do...while)
    5. PHP receives data sent by the POST method using the ______ array. ($_POST)
    6. 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.