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

Scripting in web development is broadly categorized into server-side and client-side scripting. Both play crucial roles in building dynamic and interactive web applications. 

1. Server-Side Scripting: Server-side scripting is executed on the web server before the page is sent to the user’s browser. It is used to handle database operations, authentication, and business logic.

2. Client-Side Scripting: Client-side scripting is executed on the user’s browser, allowing web pages to be interactive and dynamic without constant communication with the server.

Key Differences:

Feature (Aspect)

Server-Side Scripting

Client-Side Scripting

Execution

On the web server

On the user’s browser

Performance

Slower due to server processing

Faster as it runs locally

Security

More secure (hidden from users)

Less secure (visible to users)

Use Cases

Authentication, database handling, API requests

UI interactions, animations, form validation

Examples

PHP, Node.js, Python, Java

JavaScript, HTML, CSS

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="alert('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>Hello World</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()

{

    alert("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>


2080 GIE Set B Q.No. 11How do you add an event handler in JavaScript? Give an example. [5]

Ans:

In JavaScript, an event handler is a function that gets executed when a specific event occurs, such as a mouse click, a key press, or a form submission. We can add event handlers using either of the following methods:

a) Using the onclick attribute (Inline event handling)

b) Using addEventListener() (External event handling)

A simple example of an event handler using the onclick attribute in JavaScript is as follows:

<!DOCTYPE html>

<html>

<head>

    <title>Hello World</title>

</head>

<body>

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

    <script>

        function showMessage()

        {

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

        }

 </script>

</body>

</html>

Explanation:

The showMessage() function uses document.write() to directly write the text "Hello, World!" to the page.

(Click me) button triggers the showMessage() function when clicked.



3.5 JavaScript Fundamentals

JavaScript is a high-level, interpreted client-side programming language used to create dynamic and interactive web pages. It is an essential part of web development alongside HTML and CSS.

JavaScript is one of the most important programming languages in web development. It plays a crucial role in creating dynamic, interactive, and user-friendly websites. Uses/Importances/Necessities/Advantages/Features of JavaScript in webpage development are as follows:

1. Enhances User Experience: JavaScript allows developers to create interactive elements like dropdown menus, sliders, pop-ups, and form validations that improve user engagement.

2. Client-Side Scripting: JavaScript runs on the user's browser rather than the server, reducing load time and improving website performance.

3. Asynchronous Operations (AJAX): It enables asynchronous communication with servers, allowing websites to update content without requiring a full page reload.

4. Cross-Browser Compatibility: JavaScript works across all modern browsers, ensuring a consistent experience for users.

5. Mobile and Web App Development: JavaScript is used in mobile app development through frameworks like React Native and in progressive web apps (PWAs).

6. Security Features: It helps in real-time form validation and authentication before data is sent to the server.

7. Extensive Community Support: JavaScript has a vast developer community, making it easy to find resources, tutorials, and solutions to problems.

8. Rich Frontend Development and Backend Development

Basic Syntax:

Ø  Case-sensitive

Ø  Statements end with; (optional but recommended).

Ø  Uses {} for code blocks.

  • Note: Single-line comments start with // and continue to the end of the line


    Multi-line comments start with /* and end with */, and can span multiple lines

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