Monday, February 10, 2025

Chapter 3: Web technology II

 

NOTES:

3.1 Introduction

Web Technology refers to the tools, programming languages, frameworks, and protocols used to develop and maintain websites and web applications. It includes both client-side and server-side technologies that enable communication, interaction, and data exchange over the internet.

Key Components of Web Technology: Web Browsers (Chrome), Markup & Styling Languages (HTML, CSS), Client-Side Scripting (JavaScript), Server-Side Scripting (PHP), Databases (MySQL), Web Protocols (HTTP, FTP) and Web Servers (Apache)


3.2 Server side and Client-Side Scripting

Feature

Server-side Scripting

Client-side Scripting

Definition

Server-side scripting is executed on the web server before sending the result to the user’s browser.

Client-side scripting is executed in the user’s browser after the page is loaded.

Execution

It takes place on the server.

It takes place on the client’s browser.

Languages Used

Languages like PHP, Python, Ruby, ASP.NET, and Node.js are used.

Languages like JavaScript, HTML, and CSS are used for scripting and interaction.

Interaction with Database

It can directly interact with databases.

It cannot directly interact with databases and requires a server request.

Security

It is more secure because the code is hidden from the user.

It is less secure because the code is visible to the user.

Page Load Time

Pages may load slower because the server processes the script before sending it.

Pages are more responsive since scripts run locally in the browser.

Examples

Examples include login authentication, fetching data from a database, and sending emails.

Examples include form validation, animations, interactive menus, and image sliders.


3.4 Adding JavaScript to an HTML Page

JavaScript can be added to an HTML page in three main ways:

1. Inline JavaScript

JavaScript can be written inside HTML elements using the onclick or other event attributes. 

<!DOCTYPE html>

<html>

<head>

    <title>Inline JavaScript</title>

</head>

<body>

    <button onclick="document.write('Hello, World!')">Click Me</button>

</body>

</html>


2. Internal JavaScript

JavaScript can be placed inside a <script> tag in the HTML document, usually in the <head> or before the closing </body> tag.

<!DOCTYPE html>

<html>

<head>

    <title>Internal JavaScript</title>

</head>

<body>

    <script>

        function showMessage() 

        {

            document.write("Hello, World!");

        }

    </script>

    <button onclick="showMessage()">Click Me</button>

</body>

</html>


3. External JavaScript

JavaScript can be written in a separate .js file and linked to the HTML page using the <script> tag with the src attribute.

script.js (External JavaScript file):

function greet() 

{

    document.write("Hello from external JavaScript!");

}


HTML file (index.html):

<!DOCTYPE html>

<html>

<head>

    <title>External JavaScript</title>

    <script src="script.js"></script>

</head>

<body>

    <button onclick="greet()">Click Me</button>

</body>

</html>



3.5 JavaScript Fundamentals

JavaScript is a high-level, interpreted, client-side programming language used to create dynamic and interactive web pages. It works alongside HTML (structure) and CSS (styling) to form the core of modern web development.

Importance (Features) of JavaScript in Web Development:

  1. Enhances User Experience – Creates interactive elements (dropdowns, sliders, form validation).

  2. Client-Side Execution – Runs in the browser, reducing server load and improving performance.

  3. Asynchronous Operations (AJAX) – Allows partial page updates without full reloads.

  4. Cross-Browser Compatibility – Works consistently across modern browsers.

  5. Mobile & Web App Development – Used with frameworks (React Native, PWAs).

  6. Security – Enables client-side validation before server submission.

  7. Large Community Support – Extensive resources and libraries available.

  8. Full-Stack Capability – Used for both frontend and backend (Node.js) development.

Basic Syntax:

  • Case-sensitive – myVar ≠ myvar

  • Statements end with ; (optional but recommended)

  • Code blocks use { }

  • Comments:

    1. Single-line: // comment

    2. Multi-line: /* comment */


3.6 JavaScript Data Types

JavaScript has different types of data that can be used to store and manipulate values. The main data types in JavaScript are:

1.    Primitive Data Types (immutable, stored directly in memory)

Ø String → "Hello, World!"

Ø Number → 42, 3.14

Ø Boolean → true, false

Ø Undefined → let x; // x is undefined

Ø Null → let y = null;

Ø Symbol (ES6) → let sym = Symbol('unique');

Ø BigInt (ES11) → let big = 9007199254740991n;

2.    Non-Primitive (Reference) Data Types (stored by reference in memory)

Ø Object → { name: "John", age: 25 }

Ø Array → [1, 2, 3, 4]

Ø Function → function sayHello() { console.log("Hello"); }


3.7 Variables and Operators

Variables:

Variables in JavaScript store data values. There are three ways to declare a variable:

  • var (function-scoped, can be redeclared)
  • let (block-scoped, cannot be redeclared)
  • const (block-scoped, cannot be reassigned)

Example:

var a = 10;

let b = 20;

const c = 30;

Operators:

Operators: An operator is a symbol or word that indicates the type of calculation or operation to be performed on one or more operands. In JavaScript, operators are used to perform operations on variables and values. The different types of operators in JavaScript with examples are as follows:

1. Arithmetic Operators: Used to perform mathematical operations.

Operator

Description

Example (let a = 10, b = 5;)

Output

+

Addition

a + b

15

-

Subtraction

a – b

5

*

Multiplication

a * b

50

/

Division

a / b

2

%

Modulus (Remainder)

a % b

0

**

Exponentiation (Power)

a ** b

100000

2. Assignment Operators: Used to assign values to variables.

Operator

Description

Example (let a = 10;)

Equivalent To

=

Assign value

a = 10

a = 10

+=

Add & Assign

a += 5

a = a + 5

-=

Subtract & Assign

a -= 5

a = a – 5

*=

Multiply & Assign

a *= 5

a = a * 5

/=

Divide & Assign

a /= 5

a = a / 5

%=

Modulus & Assign

a %= 5

a = a % 5

3. Comparison Operators: Used to compare values (returns true or false).

Operator

Description

Example (let a = 10, b = 5;)

Output

==

Equal (loose comparison)

a == "10"

True

===

Identical (strict comparison)

a === "10"

False

!=

Not equal

a != b

True

!==

Not identical

a !== "10"

True

> 

Greater than

a > b

True

< 

Less than

a < b

False

>=

Greater than or equal

a >= 10

True

<=

Less than or equal

a <= 5

False

4. Logical Operators: Used to perform logical operations.

Operator

Description

Example (let x = true, y = false;)

Output

&&

Logical AND

x && y

False

||

Logical OR

X || y

true

!

Logical NOT

!x

false

5. Increment & Decrement Operators: Used to increase or decrease values.

Operator

Description

Example (let a = 10;)

Output

++a

Pre-increment

++a

11

a++

Post-increment

a++

10 (then 11)

--a

Pre-decrement

--a

9

a--

Post-decrement

a--

10 (then 9)

6. String Operators: Used for working with strings.

Operator

Description

Example (let str1 = "Hello"; let str2 = "World";)

Output

+

Concatenation

str1 + " " + str2

"Hello World"

+=

Concatenate & assign

str1 += " JavaScript"

"Hello JavaScript"

7. Bitwise Operators: Used to Perform operations on binary representations of numbers (0s and 1s).

Operator

Name

&

Bitwise AND

|

Bitwise OR

^

Bitwise XOR (Exclusive OR)

~

Bitwise NOT (Complement)

<< 

Left Shift

>> 

Right Shift

>>> 

Unsigned Right Shift

8. Ternary Operator: A short-hand if-else statement.

Operator

Example

Output

? :

(5 > 3) ? "Yes" : "No";

"Yes"

9. Type Operators: Used to check data types.

Operator

Name

Example

Output

typeof

Type Check

typeof "Hello"

"string"

instanceof

Instance Check

arr instanceof Array

True

 

3.8 Functions and control structure if-else, if-else- if, switch-case, for, while, do while loop

Functions in JavaScript:

A function is a block of reusable code designed to perform a specific task.

Example:

function greet(name)

{

    return "Hello, " + name;

}

document.write(greet("Alice"));   // Output: Hello, Alice

 

Here:

Ø  greet is the function name.

Ø  name is the parameter.

Ø  The function returns a greeting message.

 Alternative method:

Function Declaration is shown in an example below:

function greet()    //function definition, declaration

{

    document.write("Hello World”);

}

greet();    //function call

Control Structures:

Control structures allow user to control the flow of execution based on conditions or repetitions. They are categorized into three main types: Conditional Statements, Looping Statements and Jump Statements.

A) Conditional Statements:

These structures execute different blocks of code based on conditions.

1)   if-else

The if-else structure executes different blocks of code based on whether a condition is true or false.

<!DOCTYPE html>

<html>

<head>

    <title>If-Else Example</title>

</head>

<body>

<script>

    var num;

        num = parseInt(prompt("Enter a number:"));

    if (num > 0)

    {

        document.write("Positive number");

    } else {

        document.write("Negative number");

    }

</script>

</body>

</html>

2)   if-else-if

The if-else-if structure is an extension of the if-else statement that allows multiple conditions to be evaluated sequentially. If one condition is true, its corresponding block of code executes, and the rest are ignored. If none of the conditions are true, the else block (if present) executes.

<!DOCTYPE html>

<html>

<head>

    <title>If-Else-If Example</title>

</head>

<body>

<script>

    var num;

        num = parseInt(prompt("Enter a number:"));

    if (num > 0)

    {

        document.write("Positive number");

    } else if (num < 0) {

        document.write("Negative number");

    } else {

        document.write("Zero");

    }

</script>

</body>

</html>

   3)switch-case

A switch statement is useful for comparing a variable with multiple values. It's cleaner than multiple if-else statements when checking one variable for several possible values.

<!DOCTYPE html>

<html>

<head>

    <title>Switch-Case Example</title>

</head>

<body>

<script>

var day, dayName;

     day= parseInt(prompt("Enter day:"));

    switch (day) 

    {

        case 1:

            dayName = "Monday";

            break;

        case 2:

            dayName = "Tuesday";

            break;

        case 3:

            dayName = "Wednesday";

            break;

        case 4:

            dayName = "Thursday";

            break;

        case 5:

            dayName = "Friday";

            break;

        case 6:

            dayName = "Saturday";

            break;

        case 7:

            dayName = "Sunday";

            break;

        default:

            dayName = "Invalid day";

    }

    document.write("Today is: " + dayName);

</script>

</body>

</html> 

B) Looping Statements

Loops allow user to execute a block of code multiple times.

1) for loop

A for loop is used when user know the number of iterations(loops) ahead of time.

<!DOCTYPE html>

<html>

<head>

    <title>For Loop Example</title>

</head>

<body>

<script>

    for (var i = 1; i <= 5; i++)

    {

        document.write("Number: " + i + "<br>");

    }

</script>

</body>

</html>

Output:

Number: 0

Number: 1

Number: 2

Number: 3

Number: 4


2) while loop

A while loop repeats the code as long as the condition is true. It’s useful when the number of iterations is not known in advance.

<!DOCTYPE html>

<html>

<head>

    <title>While Loop Example</title>

</head>

<body>

<script>

    var i = 1;

    while (i <= 5)

    {

        document.write("Number: " + i + "<br>");

        i++;

    }

</script>

</body>

</html>


3) do-while loop

The do-while loop ensures that the code is executed at least once, regardless of the condition. After the first iteration, the condition is checked.

<!DOCTYPE html>

<html>

<head>

    <title>Do-While Loop Example</title>

</head>

<body>

<script>

    let i = 0;

    do

    {

        document.write("Number: " + i + "<br>");

        i++;

    } while (i < 5);

</script>

</body>

</html>



Some Workout Examples: 

 1) Write a program to enter two numbers and find the sum of two numbers in JavaScript.

 <!DOCTYPE html>

<html>

<head>

    <title>Sum of Two Numbers</title>

</head>

<body>

    <script>

        var a, b, s; 

        a = parseInt(prompt("Enter first number:"));

        b = parseInt(prompt("Enter second number:"));

        s = a + b;

        document.write("The sum is " + s); 

    </script>

</body>

</html>


 Write a function to enter two numbers and find the sum of two numbers in JavaScript.

<!DOCTYPE html>

<html>

<head>

    <title>Sum of Two Numbers</title>

</head>

<body>

    <script>

        function calculateSum()

        {

            var a, b, s;

            a = parseInt(prompt("Enter first number:"));

            b = parseInt(prompt("Enter second number:"));

            s = a + b;

            document.write("The sum is " + sum);

        }

        calculateSum(); 

    </script>

</body>

</html> 

Example Output:

Ø The user will be prompted to Enter first number (via the prompt).

For example, if the user enters 5.

Ø Then, the user will be prompted to Enter second number.

For example, if the user enters 10.

Ø The output on the page will be:

                              The sum is 15


2) Write a JavaScript code to checks if a number is even or odd.

<!DOCTYPE html>

<html>

<head>

    <title>Even or Odd Checker</title>

</head>

<body>

    <script>

        var n;

        n = parseInt(prompt("Enter a number:"));

        if (n % 2 === 0)

        {

            document.write("The number is Even");

        } else {

            document.write("The number is Odd");

        }

    </script>

</body>

</html>


Write a JavaScript function that checks if a number is even or odd and prints the result.

<!DOCTYPE html>

<html>

<head>

    <title>Even or Odd Checker</title>

</head>

<body>

    <script>

        function checkEvenOdd() 

            {

            var n;

            n = parseInt(prompt("Enter a number:"));

            if (n % 2 === 0)

            {

                document.write("The number is Even");

            } else {

                document.write("The number is Odd");

            }

        }

        checkEvenOdd(); 

    </script>

</body>

</html>

Example Output:

Ø The user will be prompted to Enter a number (via the prompt).

For example, If the user enters 4.

Ø The output on the page will be:

          The number is Even.

3) Write a JavaScript code to checks if a number is positive, negative or zero.

Ans:


Write a JavaScript function that checks if a number is positive, negative or zero.
  Ans:

  4) Write a program to find the largest number among three numbers in JavaScript.

Ans:




Write a JavaScript function to find the largest number among three numbers.
Ans:



5) Write a JavaScript code to calculate the factorial of a given number. 
Ans:


Write a function to calculate the factorial of a given number in JavaScript.

Ans: 

Write a program to test if a number is prime or composite. 
Ans:
<

Homework:

1) WAP in JavaScript to find simple interest by using function as well as normal.

2) WAP in JavaScript to find smallest number among three given numbers by using both.

NOTE: Different JavaScript user interaction functions:

1. alert(): Display a pop-up message

alert("Hello! This is an alert message.");

2. confirm(): Ask for confirmation (Yes/No)

let userResponse = confirm("Do you want to proceed?");

if (userResponse) {

    alert("You clicked OK!");

} else {

    alert("You clicked Cancel!");

}

3. prompt(): Get user input

let userName = prompt("What is your name?");

if (userName) {

    alert("Hello, " + userName + "!");

} else {

    alert("You didn't enter your name.");

}

4. document.write(): Write directly to the HTML document

document.write("This is written using document.write()");

5. console.log(): Log messages in the developer console

console.log("This message is logged in the console.");

6. console.error(): Log an error message

7. readline: The readline module helps to read user input from the terminal.

Java Scripted Completed

3.20 Database Connectivity

Database connectivity refers to the process of connecting a server-side script (like PHP) to a database (like MySQL) to store, retrieve, update, and delete data.

Syntax for Database Connection:

$con = new mysqli($servername, $username, $password, $database);

OR

$con = mysqli_connect($servername, $username, $password, $database);

 

3.21 Connecting Server-Side Script to Database

To connect a PHP script to a MySQL database, follow these steps:

// Database configuration

<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "studentDB";

 

// Create a connection

$con = new mysqli($servername, $username, $password, $database);

 

// Check connection

if ($con->connect_error) {

    die("Connection failed: " . $con->connect_error);

} else {

    echo "Connected successfully!";

}

?>

 

3.22 Making SQL Queries

Once connected, SQL queries can be executed using query() for SELECT, INSERT, UPDATE, and DELETE statements.

Example: Inserting Data

$sql = "INSERT INTO student (first_name, last_name, mark, email)

        VALUES ('John', 'Doe', 85, 'john.doe@example.com')";

if ($con->query($sql) === TRUE) {

    echo "Record inserted successfully";

} else {

    echo "Error: " . $sql . "<br>" . $con->error;

}

Example: Updating Data

$sql = "UPDATE student SET mark = 90 WHERE first_name = 'John'";

$con->query($sql);

Example: Deleting Data

$sql = "DELETE FROM student WHERE first_name = 'John'";

$con->query($sql);

 

3.23 Fetching Data Sets & Getting Data About Data

Fetching data means retrieving information from a database table using SELECT queries as follows:

$sql = "SELECT * FROM student";

$result = $con->query($sql);

if ($result->num_rows > 0) {

    while ($row = $result->fetch_assoc()) {

        echo "Name: " . $row["first_name"] . " " . $row["last_name"] .

             " - Marks: " . $row["mark"] . " - Email: " . $row["email"] . "<br>";

    }

} else {

    echo "No records found";

}

 

3.24 Creating SQL Database AND a TABLE in that database with Server-Side Scripting

3.25 Displaying queries in tables

[Master ALL IN ONE PHP CODE]

// Database configuration

<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "studentDB";

 

// Create a connection

$con = new mysqli($servername, $username, $password, $database);

 

// Check connection

if ($con->connect_error) {

    die("Connection failed: " . $con->connect_error);

} else {

    echo "Connected successfully!";

}

 

// Creating a Database

$sql = "CREATE DATABASE studentDB";

if ($con->query($sql) === TRUE) {

    echo "Database created successfully";

} else {

    echo "Error creating database: " . $con->error;

}

 

//Creating a Table in the Database

$con = new mysqli("localhost", "root", "", "studentDB");

$sql = "CREATE TABLE student (

    id INT AUTO_INCREMENT PRIMARY KEY,

    first_name VARCHAR(50),

    last_name VARCHAR(50),

    mark INT,

    email VARCHAR(100)

)";

if ($con->query($sql) === TRUE) {

    echo "Table created successfully";

} else {

    echo "Error creating table: " . $con->error;

}

 

// Inserting Data

$sql = "INSERT INTO student (first_name, last_name, mark, email)

        VALUES ('John', 'Doe', 85, 'john.doe@example.com')";

if ($con->query($sql) === TRUE) {

    echo "Record inserted successfully";

} else {

    echo "Error: " . $sql . "<br>" . $con->error;

}

 

//Fetch Data and Displaying Queries in Tables

$sql = "SELECT * FROM student";

$result = $con->query($sql);

if ($result->num_rows > 0) {

    echo "<table border='1'>

            <tr>

                <th>ID</th>

                <th>First Name</th>

                <th>Last Name</th>

                <th>Marks</th>

                <th>Email</th>

            </tr>";

    while ($row = $result->fetch_assoc()) {

        echo "<tr>

                <td>" . $row["id"] . "</td>

                <td>" . $row["first_name"] . "</td>

                <td>" . $row["last_name"] . "</td>

                <td>" . $row["mark"] . "</td>

                <td>" . $row["email"] . "</td>

              </tr>";

    }

    echo "</table>";

} else {

    echo "No records found";

}

 

//Closing database connection

$con->close();

?>


Imp Question:

1)Write down the server-side script to create a database, connect with it, create a table and insert data in it.

2) Write down the server-side script for Displaying Queries in Tables.

3) How do you delete a data from database in PHP.

4)Explain the data insertion method in PHP.



0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home