KEMBAR78
Unit 3 Web Tech II | PDF | World Wide Web | Internet & Web
0% found this document useful (0 votes)
17 views90 pages

Unit 3 Web Tech II

The document outlines a comprehensive curriculum for a Web Technology II course, covering topics such as web development, client-side and server-side scripting, JavaScript, PHP, and database connectivity. It details the structure of web technologies, including web pages, browsers, and servers, and differentiates between front-end and back-end development. Additionally, it provides insights into JavaScript's history, features, data types, and variable management, along with practical examples of its application in web development.

Uploaded by

ioepreparation86
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views90 pages

Unit 3 Web Tech II

The document outlines a comprehensive curriculum for a Web Technology II course, covering topics such as web development, client-side and server-side scripting, JavaScript, PHP, and database connectivity. It details the structure of web technologies, including web pages, browsers, and servers, and differentiates between front-end and back-end development. Additionally, it provides insights into JavaScript's history, features, data types, and variable management, along with practical examples of its application in web development.

Uploaded by

ioepreparation86
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Unit 3

Web Technology II
Prepared by
Ganesh Raj Joshi

(Lecturer)
Department of Computer Engineering
Exam point of view
•Total credit hour- 12
•Short Question - 1*5= 5 marks
•MCQ - 2*1= 2 marks
OUTLINES
• Introduction to Web-Technology.
• Introduction to web development.
• Introduction to client side and server side scripting .
• Introduction to JavaScript and it’s uses.
• JavaScript Variables and fundamentals.
• JS data types, and different types of operators used in JS.
• Functions and Control structure of JS.
• OOP with JS and Event handling in JS.
• Introduction to PHP and it’s uses.
• Variables ,Data types and operators in PHP.
• Database connectivity
• SQL queries and Database with JS and PHP
Web technology
Web Technology refers to the various tools and techniques that
helps to communicate between the different types of devices over
the network by using the internet.

It consists of two words, WEB and TECHNOLOGY. The term web
simply refers to World Wide Web(WWW), is the cyber space
containing webpages, documents and other resources which can
be accessed by using their URL. The term Technology refers to
the tools and techniques that makes resources available on WEB
such as web browser(to view the content), programming language
and different frameworks(for development of websites), databases
(for storing the data and information) and protocols.
Web Technology can be classified into the following sections:

World Wide Web (WWW):


-World Wide Web, which is also known as a Web, is a collection of websites or
web pages stored in web servers and
connected to local computers through the internet. The three basic languages
that makes up www are HTML, CSS and
JavaScript.

Web Pages:
-A webpage is the collection of the digital document that is linked to the
WWW and viewable by anyone connected to the
internet. These web pages can be accessed through the different types of
web browsers.
-Web Page can contain text, images, videos, hyperlinks etc.
Web Browser:
-The web browser is an application software to explore www (World Wide
Web).
-It provides an interface between the server and the client. So that the users
can send requests to the server for web
documents and services.
Examples:- Chrome, Microsoft Edge, Safari etc.

Web Server:
-Web servers are the software or hardware system that store, process and
deliver web pages to the users.
-They respond to requests from web browser and give response to the
requested webpage and its data to the users
through browser.
Examples:- Popular web server includes Apache, Nginx, Microsoft Internet
Information Service(IIs) etc.
Web Development: -
Web development involves the process of building, creating, and maintaining of
websites or web applications.
It includes the different tasks such as web design, web publishing, web
programming, and database management etc.
 In one word we can say that the web development is the creation of an application
that works over the internet i.e. websites.
Web Development can be classified into two ways:
Frontend Development:-
-The part of a website that the user interacts directly is termed as front end. It is also
referred to as the client side of the application.
- Front-End web development refers to the process of developing the portion of the
site, app, or digital product that users will see and interact with.
- And a person who is responsible for development of front-end is called front-end
developer.
Backend Development:
- Backend is the server side of a website. It is the part of
the website that users cannot see and does not come in
direct contact with the users.
- It deals with how the actual process works on web.
- And a person who is responsible for development of
backend-end side of web is called backend-end
developer.
- It including the task related with database interactions,
user authentication, server, network and hosting
configuration,
and business logic
Frontend Languages:
HTML:

HTML: Stands for Hypertext Markup Language.


Purpose: Designs the front-end portion of web pages using a
markup language.
Components:
Hypertext: Defines links between web pages.
Markup Language: Defines the structure of web pages
using tags.
CSS:
CSS: Stands for Cascading Style Sheets.
Purpose: Simplifies the process of making
web pages presentable.
Function:
- Allows applying styles to web pages.
-Works independently of the HTML
structure of web pages.
JavaScript:

JavaScript: A popular scripting language for creating


interactive websites.
Purpose:
- Enhances website functionality.
- Enables interactive user experiences.
- Powers web-based games and software.
Frontend Frameworks:
- Examples include React JS, Angular, Vue JS, and Next.JS.
AJAX:

AJAX: Stands for Asynchronous JavaScript and XML.


Purpose:
- Communicates with the server without refreshing
the web page.
-Enhances user experience and performance.
Backend Languages:
•PHP: PHP is a server-side scripting language designed
specifically for web development.
•Since PHP code executed on the server-side, so it is called a
server-side scripting language.

•Python: Python is a programming language that lets you work


quickly and integrate systems more efficiently.

•Ruby: Ruby is a pure ,dynamic, reflective, object-oriented,


general-purpose programming language. The objective of Ruby’s
development was to make the development process rapid.
•Java: Java is one of the most popular and widely used programming
languages and platforms which is highly scalable.

•JavaScript: JavaScript can be used as both (front end and back end)
programming.

•C# :C# is a general-purpose, modern and object-oriented


programming language pronounced as “C sharp”.

•DBMS: The software which is used to manage database is called


Database Management System (DBMS).
Client-side scripting Server-side scripting
1. Source code is visible to the user. 1. Source code is not visible to the user
2. Its main function is to provide the requested output 2. Its primary function is to manipulate and provide
to the end user. access to the respective database as per the request.

3. It usually depends on the browser and its version. 3. In this any server-side technology can be used and it
does not depend on the client.
4. It runs on the user’s computer. 4. It runs on the webserver.
5. There are many advantages linked with this like 5. The primary advantage is its ability to highly
faster response times, a more interactive application. customize, response requirements, access rights based
on user.
6. It does not provide security for data. 6. It provides more security for data.
7. It is a technique used in web development in which 7. It is a technique that uses scripts on the webserver to
scripts run on the client’s browser. produce a response that is customized for each client’s
request.
8. HTML, CSS, and JavaScript are used. 8. PHP, Python, Java, Ruby are used.
9. No need of interaction with the server. 9. It is all about interacting with the servers.
10. It reduces load on processing unit of the server. 10. It increases the processing load on the server.
JavaScript
 JavaScript is a versatile programming language primarily
used for creating interactive and dynamic web pages.
 It is a client-side scripting language, which means it runs
directly in the user's web browser.
 JavaScript can also be used on the server side using
environments like Node.js.
 JS is Introduced in 1995 for the Netscape Navigator
browser, it enables dynamic content on webpages without
reloading.
JavaScript
JavaScript is a versatile programming language primarily used for
creating interactive and dynamic web pages.
It is a client-side scripting language, which means it runs directly in
the user's web browser.
JavaScript can also be used on the server side using environments like
Node.js.
History of JavaScript
 In the year 1994, Netscape was founded by Marc Andreessen.
 He realized that the web needed to become more dynamic.
 Thus, a 'glue language' was believed to be provided to HTML to make web
designing easy for designers and part-time programmers.
 But, before Brendan could start, the company merged with Sun Microsystems for
adding Java into its Navigator so that it could compete with Microsoft over the web
technologies and platforms.
 Now, two languages were there: Java and the scripting language.
 Further, Netscape decided to give a similar name to the scripting language as
Java's. It led to 'Javascript’.
 Finally, in May 1995, Marc Andreessen coined the first code of Javascript named
'Mocha’.
 Later, the marketing team replaced the name with 'LiveScript’.
 But, due to trademark reasons and certain other reasons, in December 1995, the
language was finally renamed to 'JavaScript’.
 From then, JavaScript came into existence.
Applicaton of JS
Interactive Websites: Enhances user experience by adding
interactivity.
Client-Side Validation: Validates form inputs before submitting
to the server.
Dynamic Drop-Down Menus: Creates responsive and
interactive navigation.
Date and Time Display: Dynamically updates or displays
current date and time.
Pop-Up Windows and Dialog Boxes:
- Alert, confirm, and prompt dialog boxes for user
interaction.
Web Applications: Powers single-page
applications (SPAs) with frameworks like React and
Angular.
Game Development: Creates browser-based
games with libraries like Phaser.
Real-Time Applications: Supports chat systems,
live updates, and notifications using WebSockets.
Data Visualization: Generates charts and graphs
using libraries like D3.js.
Mobile and Desktop Apps: Develops cross-
platform apps using React Native or Electron.js.
Key Features of JavaScript (JS):
Lightweight: A simple and efficient scripting language.
Interpreted: Does not require compilation; executed directly in
the browser.
Dynamic Typing: Variables can hold different types of data at
runtime.
Object-Oriented: Supports object-oriented programming
concepts like objects, inheritance, and encapsulation.
Event-Driven: Handles events like clicks, form submissions,
and mouse movements.
Platform Independent: Runs on any platform with a
compatible browser.
Client-Side Execution: Executes directly in the user’s
browser for faster interactions.
Cross-Browser Support: Works across all major browsers.
Extensibility: Easily integrates with other web technologies
like HTML, CSS, and third-party libraries or frameworks.
Functional Programming: Supports functional concepts like
higher-order functions and closures.
DOM Manipulation: Dynamically updates and interacts with
web page elements.
Methods of displaying output in JS
1. alert
Purpose: Displays a message in a browser alert
dialog box.
Example:
alert("This is an alert message!");

2. console.log
Purpose: Outputs a message to the browser's
developer console.
console.log("This message is displayed in the
console.");
3. document.write
Purpose: Writes directly to the HTML document (not
recommended for modern web development).
Example:
document.write("This message is displayed on the web
page.");
4. innerHTML or textContent (DOM Manipulation)
Purpose: Displays a message on the webpage by modifying
the HTML or text content of an element.
Example:
document.getElementById("message").innerHTML = "This is
displayed on the webpage!";
5. prompt
Purpose: Displays a message with a text input field to collect user
input.
Example:
const name = prompt("What is your name?");
alert(`Hello, ${name}!`);
6. confirm
Purpose: Displays a message with OK/Cancel buttons to confirm an
action.
if (confirm("Do you want to proceed?")) {
alert("You chose OK.");
} else {
alert("You chose Cancel.");
}
Where we can write the JavaScript
code?
1.Between the body tag of html
2.Between the head tag of html
3.In .js file (external javaScript)
Between the body tag of html

<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document. Write("Hello class from javascript");
</script>
</body>
</html>
Between the head tag of html
<!DOCTYPE html>
<html>
<head>
<script>
alert(5 + 6);
</script>
</head>
<body>
<p> This is example of writing the script in between head</p>
</body>
</html>
In .Js file (external javaScript)
index.html
message.js
<html>
function msg(){
<head>
alert("Hello class");
<script type="text/javascript" src="message.js"></s
cript>
}
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()
"/>
</form>
</body>
</html>
JavaScript Comment
The JavaScript comments are meaningful way to deliver
message.
It is used to add information about the code, warnings or
suggestions so that end user can easily interpret the code.
The JavaScript comment is ignored by the JavaScript engine i.e.
embedded in the browser.
Types of JavaScript Comments
There are two types of
comments in JavaScript.
1.Single-line Comment
2.Multi-line Comment
JavaScript Single line Comment
It is represented by double forward slashes (//). It can be used before and after the
statement.
<script>
// It is single line comment
document. write("hello class");
</script>
JavaScript Multi line Comment
It can be used to add single as well as multi line comments.
It is represented by forward slash with asterisk then asterisk with forward slash. For
example:
1./* your code here */
It can be used before, after and middle of the statement.
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
JavaScript Variable
A JavaScript variable is simply a name given to storage location or we
can also define variables are containers for storing data of different
datatypes.
There are some rules while declaring a JavaScript variable (also
known as identifiers).
1. Variable names are case sensitive: “a” & “A” is different.
2. Only letters, digits, underscore(_) and $ sign is allowed (not even
space).
3. Only a letter, underscore(_) or $ should be 1st character.
4. Reserved words cannot be variable names.
JavaScript variable declaration and initialization
1) Var : variable can be re-declared and updated. A global scope variable.
Example: var x, var name, var first_name, var x = 10; var
name=“Hari” ;
2) Let : variable cannot be re-declared but can be updated. A block scope
variable.
Example : let _value; let x; let name; let x=10; let first_name=“Hari”
3) Const : variable cannot be re-declared or updated. A block scope variable.
Example : const x; const pie; const price; const x=10; const pie=3.24;
const price=5000; etc
JavaScript variable scope
-The scope of a variable is the region of your program in which it is defined.
-There are two types of variable scope in JavaScript : local variable and
global variable.

a) JavaScript local variable


A JavaScript local variable is declared inside block or function and It is
accessible within the function or block only.
For example:
<script>
function abc()
{
let x=10; //here x is a local variable and its scope is only within function
}
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable
i.e. declared outside the function or declared with window object is
known as global variable. For example:
<script>
let data=200; //gloabal variable
function a(){
document.write(data);
}
function b(){
document.write(data);
}
a(); //calling JavaScript function
b();
</script>
Javascript Data Types
Data types in PL define the type of data that a variable can hold.
JavaScript provides different data types to hold different types of
values. There are two types of data types in JavaScript.
1.Primitive data type
2.Non-primitive (reference) data type

JavaScript primitive data types


Primitive data types serves as the fundamental building blocks
from which all other data types are constructed.
There are five types of primitive data types in JavaScript. They
are as follows:
Data Type Description

String represents sequence of characters e.g. name=


“Hari"
Number represents numeric values e.g. x= 100, y=30.5

Boolean represents boolean value either false or true e.g.


let bool=true
Undefined represents undefined value. e.g. let z;
Null represents null i.e. no value at all e.g. let
x=null,
JavaScript non-primitive data types
Non primitive data types which are also known as composite or reference
data type.
These non primitive data types allows you to group and organize multiple
values into a single variable. The non-primitive data types in JS are as
follows:

Data Type Description


Object A collection of key value pair. It represents instance
through which we can access members of an object.
Array represents group of similar values.
RegExp It represent regular expression
Example of object
let person = { // Using Dot Notation
console.log(person.name); //Alice
name: "Alice", console.log(person. email);
age: 30, //Alice33@gmail.com
isStudent: false, console.log(person.name, person.age);
email: “Alice33@gmail.com” //Alice 30
};
// Using Square Bracket Notation
In JS you can access members of and console.log(person["name"]); //Alice
object by using dot operator( ‘.’ ) or Console.log(person["age"]); //30
square bracket ( ‘[]’ ). Here is example..
Suppose if you want to access members
of the above object
Example of an array // Adding a new element to the end of the
let fruits = ['Apple', 'Banana', 'Orange', array
'Mango']; fruits.push('Strawberry');
console.log(fruits); // Output: ['Apple',
// Accessing array members using index 'Grapes', 'Orange', 'Mango', 'Strawberry']
console.log(fruits[0]); // Output: 'Apple'
console.log(fruits[3]); // Output: 'Mango' // Removing the last element from the
array
// Modifying array members using index fruits.pop();
fruits[1] = 'Grapes'; console.log(fruits); // Output: ['Apple',
'Grapes', 'Orange', 'Mango']
console.log(fruits); // Output: ['Apple',
'Grapes', 'Orange', 'Mango']

// Finding the length of the array


console.log(fruits.length); // Output: 4
JavaScript Operators
JavaScript operators are symbols that are used to perform
operations on operands. For example:- var sum=10+20;
Here, + is the arithmetic operator and = is the assignment
operator.

There are following types of operators in JavaScript.


1.Arithmetic Operators
2.Comparison (Relational) Operators
3.Bitwise Operators
4.Logical Operators
5.Assignment Operators
6.Special Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands.
The following operators are known as JavaScript arithmetic operators.

Operator Description Example


+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9


JavaScript Comparison Operators
The JavaScript comparison operator are used to compares the two operands. The comparison operators are as follows:

Operator Description Example

== Is equal to 10==20 = false


=== Identical (equal and of same data type) 10===20 = false

!= Not equal to 10!=20 = true


!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false


<= Less than or equal to 20<=10 = false
JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands.
The bitwise operators are as follows:
Operator Description Example
& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2
Script Logical Operators
ollowing operators are known as JavaScript logical operators.

Operator Description Example


&& Logical AND (10==20 && 20==33) =
false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true
JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.

Operator Description Example


= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a =
30
-= Subtract and assign var a=20; a-=10; Now a =
10
*= Multiply and assign var a=10; a*=20; Now a =
200
/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0


JavaScript Special Operators
The following operators are known as JavaScript special operators.

Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.

, Comma Operator allows multiple expressions to be evaluated as single


statement.
delete Delete Operator deletes a property from the object.
in In Operator checks if object has the given property
instanceof checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
JavaScript Control Structure
Control structures are just a way to specify the flow of control in a
program. It basically analyze and chose the direction of program flow
based on the certain condition or parameter.
JavaScript If statement
The JavaScript if-else statement is used to execute the code whether
condition is true or false.
There are three forms of if statement in JavaScript.
1.If Statement
2.If else statement
3.if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of
JavaScript if statement is given below.
Example:
<script>
let a=20;
if(a>10)
{
document.write("value of a is
greater than 10");
}
</script>
JavaScript If...else Statement
It evaluates the content whether condition is true of false.
The syntax of JavaScript if-else statement is given below.

if(expression)
{
//content to be evaluated if condition is true
}
else
{
//content to be evaluated if condition is false
}
Example:
<script>
let a=20;
if(a%2==0)
{
document.write("a is even number");
}
else
{
document.write("a is odd number");
}
</script>
Example.
JavaScript If...else if statement <script>
It evaluates the content only if expression is true let a=20;
from several expressions. if(a==10)
{
synatx document.write("a is equal to 10");
if(expression1){ }
//content to be evaluated if expression1 is true else if(a==15)
} {
else if(expression2){ document.write("a is equal to 15");
}
//content to be evaluated if expression2 is true else if(a==20)
} {
else if(expression3){ document.write("a is equal to 20");
//content to be evaluated if expression3 is true }
} else
{
else{ document.write("a is not equal to 10, 15 or 20");
//content to be evaluated if no expression is true }
} </script>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions.
It is just like else if statement that we have learned in previous page.
But it is convenient than if..else..if because it can be used with numbers, characters etc.

syntax
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example. case 'C':
<script> result="C Grade";
let grade='B'; break;
let result; default:
switch(grade) result="No Grade";
{ }
case 'A': document.write(result);
result="A Grade"; </script>
break;
case 'B':
result="B Grade";
break;
JavaScript Loops
 The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops.
 It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.

1.for loop
2.while loop
3.do-while loop
4.for-in loop
1) JavaScript For loop
The JavaScript for loop iterates the
elements for the fixed number of Example
times. It should be used if number of <script>
iteration is known. for (i=1; i<=5; i++)
The syntax of for loop is given below. {
document.write(i + "<br>")
for (initialization; condition; updation) }
</script>
{
code to be executed
}
JavaScript while loop
Control flow statement that allows you to repeatedly
execute a block of code as long as the specified
condition is true.
syntax
while (condition)
{
//code to be executed
updation
}
Example
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br>");
i++;
JavaScript do while loop
It is similar to while loop but the body of the while loop is
executed once then only the condition is checked.
The syntax of do while loop is given below.

do{
//code to be executed
}
while (condition);

Example
<script>
var i=21;
do{
document.write(i + "<br>");
i++;
}
while (i<=25);
The “for in” Loop
The JavaScript for in loop is used for iterating through the properties of an object:

Syntax
for (variable in object)
{
// code block to be executed
}
Example
<script>
let person= {
fname:"John",
lname:"Doe",
age:25};

for (let key in person)


{
document.write(key + ”:” +person[key]);
}
</script>
The “for of” loop:-
The JavaScript for of statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings etc...

Syntax
for (variable of iterable) {
// code block to be executed
}
Example
const iterable = [10, 20, 30];
for (let value of iterable) {
value =value+ 1;
console.log(value);
}
// Output: 11, 21, 31
Practice session
1. WAP in JavaScript to calculate the factorial of a number.
let userInput = prompt("Enter a number"); // Take input from the user
let number = parseInt(userInput); // Convert the input to an integer

if (isNaN(number)) {
document.write("Please enter a valid number.");
} else if (number < 0) {
document.write("Factorial is not defined for negative numbers.");
} else {
let factorial = 1; // Initialize factorial to 1

for (let i = 2; i <= number; i++) {


factorial *= i; // Multiply factorial by the current number
}

document.write("Factorial of " + number + " is: " + factorial);


}
<!DOCTYPE html> if (isNaN(number)) {
<html lang="en"> document.write("Please enter a valid
<head> number.");
<meta charset="UTF-8"> } else if (number < 0) {
<meta name="viewport" initial-scale=1.0"> document.write("Factorial is not defined
<title>Factorial Calculator</title> for negative numbers.");
</head> } else {
<body> let factorial = 1; // Initialize factorial to 1
<h1>Factorial Calculator</h1>
<script> for (let i = 2; i <= number; i++) {
// Program to calculate the factorial of a factorial *= i; // Multiply factorial by
number the current number
let userInput = prompt("Enter a number"); }
// Take input from the user
let number = parseInt(userInput); // document.write("Factorial of " + number
Convert the input to an integer + " is: " + factorial);
}
</script>
2.WAP to find the greatest number from three numbers.
let num1 = prompt("Enter the first number:"); // Take input from the user
let num2 = prompt("Enter the second number:");
let num3 = prompt("Enter the third number:");

num1 = parseFloat(num1); // Convert the user input to numbers


num2 = parseFloat(num2);
num3 = parseFloat(num3);

if (num1 >= num2 && num1 >= num3) // Compare the numbers to find the greatest
{
console.log(num1 + " is the greatest number.");
} else if (num2 >= num1 && num2 >= num3) {
console.log(num2 + " is the greatest number.");
} else {
console.log(num3 + " is the greatest number.");
}
3.A simple JavaScript to print the Fibonacci series upto 10’th term.
let a = 0, b = 1; // Initialize the first two terms of the Fibonacci series

console.log(a); // Print the first two terms


console.log(b);

for (let i = 2; i < 10; i++) { // Generate and print the next 8 terms of the Fibonacci
series
const nextTerm = a + b;
console.log(nextTerm);

a = b; // Update values for the next iteration


b = nextTerm;
}
4. WAP in JS to check the given number is palindrome or not?
const userInput = prompt("Enter a number:"); // Take input from the user
const number = parseInt(userInput); // Convert the input to a number

if (isNaN(number)) { // Check if the input is a valid number


console.log("Invalid input. Please enter a valid number.");
} else {
const numberString = number.toString(); // Convert the number to a string

const reversedString = numberString.split('').reverse().join(‘’); // Reverse the string

if (numberString === reversedString) { // Check if the original string is equal to the reversed string
console.log(`${number} is a palindrome.`);
} else {
console.log(`${number} is not a palindrome.`);
}
}
• let userInput = prompt("Enter a number"); // Take input from the user

• let number = parseInt(userInput); // Convert the input to an integer

• if (isNaN(number)) {

• document.write("Please enter a valid number.");

• } else {

• let originalNumber = number; // Store the original number

• let reversedNumber = 0;

• // Reverse the number

• while (number > 0) {

• let digit = number % 10; // Get the last digit

• reversedNumber = reversedNumber * 10 + digit; // Add it to the reversed number

• number = Math.floor(number / 10); // Remove the last digit from the number

• }

• // Check if the original number is equal to the reversed number

• if (originalNumber === reversedNumber) {

• document.write(originalNumber + " is a palindrome.");

• } else {

• document.write(originalNumber + " is not a palindrome.");

• }

• }
1. Sum of n natural number
2. Product of n-natural number
Functions in JavaScript.
 A function is a group of reusable code which can be called anywhere in your program.
 JavaScript functions are used to perform specific operations. We can call JavaScript function many times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
1.Code reusability: We can call a function several times so it save coding time.
2.Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common
task
3.Modularity:-Function allows us to breakdown the large complex program into small manageable module.
A JavaScript function can be defined using function keyword.
Syntax:
//defining a function
function <function-name>()
{
// code to be executed
};
//calling a function <function-name>();
The following example shows how to define and call a function in JavaScript.
Example: Define and Call a Function
function ShowMessage() {
alert("Hello World!");
}
ShowMessage();
Parameter Passing and Return in Functions
 Parameter passing is the mechanism used to pass parameters(values) to a function.
 These passed parameters can be captured inside the function and any manipulation can be done over those parameters.
 A function can take multiple parameters separated by comma.
<script>
function demo(a)
{
document.write("The value of a is“ +a);
}
demo(10);
</script>
Example
<script>
The return Statement function demo(a,b)
 A JavaScript function can have an optional return statement. {
 We can call function that returns a value and use it in our program s=a+b;
 This is required if you want to return a value from a function. return s;
}
var c=demo(20,30); //=50
document.write("this is from return statement " +c);
</script>
1. A simple JavaScript function that takes two numbers as input, calculates
their sum, and returns the result:-
// Example usage:
let num1 = parseFloat(prompt("Enter the first number:"));
let num2 = parseFloat(prompt("Enter the second number:"));

let result = findSum(num1, num2);


document.write(result);

function findSum(num1, num2) {


let sum = num1 + num2;
return ("The sum of " + num1 + " and " + num2 + " is: " + sum);
}
2. WAP in JS to check the given number is palindrome or not by using function.
// Example usage:
const exampleNumber = 12321;
if (isPalindrome(exampleNumber)) {
console.log(`${exampleNumber} is a palindrome.`);
} else {
console.log(`${exampleNumber} is not a palindrome.`);
}

function isPalindrome(number) {
// Convert the number to a string to easily check palindrome
const numberString = number.toString();

// Reverse the string


const reversedString = numberString.split('').reverse().join('');

// Check if the original string is equal to the reversed string


return numberString === reversedString;
}
JavaScript Events
JavaScript events are actions or occurrences that happen in the browser, such as a user clicking a button, pressing
a key, resizing the window, or an element finishing loading. Handling events is a crucial aspect of web development,
as it allows you to create interactive and dynamic user interfaces. Here are some common JavaScript events and
how you can use them:-

Mouse events:
Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the
element
mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.


Keyboard events:
Event Performed Event Handler Description

Keydown & onkeydown & onkeyup When the user press and then release
Keyup the key

Form events: Event Performed Event Handler Description


focus onfocus When the user focuses on an element
submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element
change onchange When the user modifies or changes the value of a
form element
Window/Document events

Event Performed Event Handler Description


load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
Code Demo of all events clickevent
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
//create a function which is called when click on button
function clickevent() {
document.write("This is demo");
}
</script>
</head>
<body>
//create a button named as click me
<button onclick="clickevent()">Click me</button>
</body>
</html>
keydownrevent()

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<h1> key down event example <h1/>
<script type="text/javascript">
function onkeydownrevent() {
document.write("This is demo");
}
</script>
</head>
<body onkeydown="onkeydownrevent()">

</body>
</html>
submit()
<body>
<form id="myForm" onsubmit="submitForm(); return false;">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>

<script type="text/javascript">
function submitForm() {
// Display form values in the console
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;

console.log(`Name: ${name}, Email: ${email}`);

// You can perform additional actions or submit the form to a server


}
</script>

</body>
mouseoverevent()

<script type="text/javascript">

function onmouseoverevent()
{
document.write("This is demo");
}

</script>
<body>
<script>
<button onmouseover=" onmouseoverevent()">Click me</button>

</script>
</body>
Forms and its Validation using JavaScript

 Forms are the basics elements of HTML. We use HTML form element in order to create the JavaScript form.
 Form validation normally used to occur at the server, after the client had entered all the necessary data and then
pressed the Submit button.
 If the data entered by a client was incorrect or was simply missing, the server would have to send all the data
back to the client and request that the form be resubmitted with correct information.
 This was really a lengthy process which used to put a lot of burden on the server.
 JavaScript provides a way to validate form's data on the client's computer before sending it to the web server.

Form validation generally performs two functions.

•Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in.
It would require just a loop through each field in the form and check for data.
•Data Format Validation − Secondly, the data that is entered must be checked for correct form and value.
Your code must include appropriate logic to test correctness of data.
Simple example of form validation using JS.
<head>
<script>
function validateForm() {
// Get form input values
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
if (name === '' || email === '') {
document.write("Please fill both form");
}
}
</script>
</head>
<body>
<h1>Form Validation Example</h1>
<form onsubmit="validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<input type="submit" value="Submit">
</form>
</body>
Introduction to JQuery
jQuery is a powerful and widely used JavaScript library designed to simplify client-side
scripting of HTML.
jQuery is a fast, small, cross-platform, and feature-rich JavaScript library.
It simplifies common tasks related to HTML document traversal, manipulation, animation,
event handling, and AJAX(Asynchronous JavaScript and XML).
It's main motto is write less and do more which means jQuery condenses complex
JavaScript tasks into concise methods.
Features of jQuery:-
Some of important feature of jQuery are listed below-
1. The jQuery is very small, fast, lightweight JavaScript library
2. It has a lot of built-in animation effects which can use directly in websites.
3. It is used to improve the performance of an application.
4. It is platform-independent.
5. It is used to develop a responsive web application.
Introduction to PHP
-PHP stands for Hypertext Preprocessor. It is a server-side scripting language designed for
web development. PHP is embedded in HTML code and interpreted by a web server with a
PHP processor module, which generates dynamic web pages.

-It is an open-source, cross platform scripting language and is widely used for web
development purpose.

-It performs the different tasks such as handling forms, interacting with databases, and
creating dynamic and interactive websites.

- It is called server-side scripting language because, when a user makes a request to a web
server, the server processes the request, executes the server-side script, interacts with
databases if needed, and then sends the result (usually HTML, CSS, or other client-readable
content) back to the client's browser.
Features/Advantages
1.Open Source:- PHP is freely available and can be used, modified, and distributed without
any cost
2.Server-Side Scripting:- PHP is primarily designed for server-side scripting, allowing
developers to create dynamic web pages by executing code on the server before sending
the HTML to the client's browser.
3.Cross-Platform:- PHP is platform-independent, meaning it can run on various operating
systems such as Windows, Linux, macOS etc.
4.Integration:- PHP can easily integrate with various databases, including MySQL,
PostgreSQL, SQLite, and more, making it well-suited for building database-driven web
applications.
5.Extensive Library Support:- PHP has a rich set of libraries and extensions that provide
additional functionalities, simplifying common tasks such as handling sessions, working
with XML, parsing JSON, and more.
6.Community Support:- The PHP community is large and active, offering differing
resources, forums, and documentation.
Weaknesses of PHP/Disadvantages

1. PHP's main strength flexibility is also its weakness. It can be a little too forgiving of errors.
2. With no strict rules, inexperienced programmers have the freedom to create some very bad
solutions to simple problems.
3. PHP is an interpreted language, which can reduce speed.
4. While PHP has improved its security features over time, improper use of the language can still lead to
security vulnerabilities. like SQL injection, cross-site scripting (XSS), and other common web
application security threats.
5. Object-oriented patterns may not be as polished as in some other programming languages.

Despite of these weaknesses, PHP remains a popular and widely used language for web development,
especially for building dynamic websites and web applications. Many successful websites and
applications are built using PHP, and ongoing improvements are made to address its limitations.
Basics of PHP:-

Setting up the environment:-To run PHP a web development is needed. This needs a PHP compatible web server and
interpreter. Package like WAMP ,XAMP etc. can be used which includes a web server.

Writing the code and running the script:-PHP scripts are plain text. A PHP script begins with . The PHP code is saved with
extension. PHP and is saved in the root directory of web server.
PHP BASIC SYNTAX

<?php
// PHP code goes here
?>
EXAMPLE
- The default file extension for PHP files is ".php". <html>
- A PHP file normally contains HTML tags, and some PHP scripting code. <body>
- Here, we have an example of a simple PHP file, with a PHP script that <h1>My first PHP page</h1>
uses a built-in PHP function "echo" to output the text "Hello World!" on <?php
a web page: echo "Hello Class 12";
-PHP statements end with a semicolon (;). ?>
</body>
</html>
<h1>Hello from HTML Page</h1>
<p>
<?php
echo "Hi there.\n";
$answer = 6 * 7;
echo "The answer is $answer, what ";
echo "was the question again?\n";
?>
</p>
<p>Yes another paragraph.</p>

You might also like