0% found this document useful (0 votes)
21 views222 pages

Chapter 3

Uploaded by

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

Chapter 3

Uploaded by

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

Chapter 3: Web technology II

By
Er. Raj Kiran chhatkuli
Introduction to Web technology
• Web technology refers to the various tools, languages, protocols, and
standards used to create, communicate, and interact with content on
the World Wide Web.
• It encompasses a wide range of concepts that enable the functioning of
websites and web applications.
• Here are some key components and details about web technology:
HTML (Hypertext Markup Language): HTML is the fundamental
building block of web pages. It is used to structure content on the web
by defining elements like headings, paragraphs, images, links, forms,
and more. HTML provides the basic structure and layout of a webpage.

CSS (Cascading Style Sheets): CSS is used to control the visual


presentation of HTML elements. It defines how content is styled,
including aspects like fonts, colors, layout, and responsive design. CSS
separates the content from its presentation, allowing for consistent
styling across multiple pages.
JavaScript: JavaScript is a versatile programming language that adds
interactivity, dynamic behavior, and client-side scripting to web pages.
It enables features like form validation, animations, and real-time
updates without the need to reload the entire page.
HTTP (Hypertext Transfer Protocol): HTTP is the protocol used for
transferring data over the web. It defines how requests and responses
should be formatted and processed between a client (such as a web
browser) and a server. HTTPS (HTTP Secure) is an encrypted version of
HTTP, ensuring secure data transmission.
Web Servers: Web servers are software applications that handle client
requests and serve web content. They process requests for resources like
HTML files, images, and videos, and send back the appropriate
responses. Popular web server software includes Apache, Nginx, and
Microsoft IIS.
Web Browsers: Web browsers are software applications that allow
users to access and view web pages. They interpret HTML, CSS, and
JavaScript to render web content visually. Popular browsers include
Google Chrome, Mozilla Firefox, Apple Safari, and Microsoft Edge.
Web Development Frameworks: Frameworks like React, Angular, and
Vue.js (for front-end development) and Node.js (for server-side
development) provide structured environments and tools to streamline
web development processes.
APIs (Application Programming Interfaces): APIs allow different
software applications to communicate and interact with each other. Web
APIs enable developers to access services and data from external
sources, like social media platforms or payment gateways, to enhance
their web applications.
Responsive Web Design: With the increasing variety of devices and
screen sizes, responsive web design ensures that websites adapt and
display appropriately on different devices, such as desktops, tablets, and
smartphones.
Web Security: Web security involves implementing measures to protect
websites and users from threats like hacking, data breaches, and malware.
This includes practices like encryption, secure authentication, and regular
software updates.
Content Management Systems (CMS): CMS platforms like WordPress,
Joomla, and Drupal provide tools for creating, managing, and publishing
web content without requiring extensive technical knowledge.
Web Hosting: Web hosting services provide the infrastructure and
technologies needed to make websites accessible on the internet. Hosting
involves storing website files on servers and making them available to
users.
Web development
• It is the process of designing and developing website which are hosted
through internet or intranet.
• The process of developing web can range from developing static page
to a complex such as web based application social media sites, E-
commerce.
• Web development includes web design, web content development,
client side scripting, server side scripting, web engineering etc.
• Since, web development consists of several inter-related task which
can be accomplish by different types of developer who focuses on
different aspect of web creation.
What is scripting language?
• A scripting language is a programming language that is interpreted. It is translated
into machine code when the code is run, rather than beforehand.
• Scripting languages are often used for short scripts over full computer programs.
• Eg: JavaScript, Python, and Ruby
• All scripting languages are programming languages, but not all programming
languages are scripting languages.
• Scripting languages in essence, are a series of commands that are able to be
executed without the need for compiling.
• They use a program known as an interpreter to translate commands and are directly
interpreted from source code, not requiring a compilation step.
• Other programming languages might need a compiler for the purpose of translating
commands into machine code before they are able to execute those commands.
Scripting language
• A scripting language is a type of programming language that is
designed for writing scripts or programs that automate tasks, control
software applications, and manipulate data.
• Unlike compiled languages, scripting languages are usually
interpreted, meaning the code is executed directly by an interpreter
without the need for a separate compilation step.
• Scripting languages are typically used for web page scripting, server-
side scripting, and data parsing.
• They are also used for creating small, simple programs that only
require a little memory or processing power.
Advantages of Scripting Languages
1.Rapid Development: Scripting languages offer a quicker development cycle
compared to compiled languages. They allow developers to write and test code
more efficiently, making them well-suited for prototyping and iterative
development.
2.Ease of Learning: Scripting languages often have simpler syntax and require
less boilerplate code, making them easier for beginners to learn and use.
3.High-Level Abstractions: Scripting languages provide built-in abstractions and
libraries that simplify complex tasks, such as string manipulation, file I/O, and
networking.
4.Flexibility: Dynamic typing allows for greater flexibility in variable types,
making it easier to work with different data types without explicit type
declarations.
Advantages of Scripting Languages
5. Automation: Scripting languages are commonly used for automating
repetitive tasks, system administration, and batch processing.
6. Interactivity: Many scripting languages are well-suited for creating
interactive and dynamic applications, particularly in web development.
7. Portability: Scripting languages are often platform-independent,
allowing scripts to run on different operating systems without major
modifications.
8. Community and Resources: Scripting languages typically have
active communities, resulting in a wealth of resources, libraries, and
frameworks that can expedite development.
Limitations of Scripting Languages
1.Execution Speed: Interpreted execution can result in slower performance
compared to compiled languages, which may be a limitation for computationally
intensive tasks.
2.Memory Consumption: Some scripting languages might use more memory
compared to compiled languages, potentially affecting the scalability of
applications.
3.Security Concerns: Due to their nature, scripting languages can be susceptible to
certain security vulnerabilities, such as code injection.
4.Limited Low-Level Control: Scripting languages might lack low-level control
over system resources, which can be important for certain applications.
5.Scaling Challenges: Scaling large and complex applications built with scripting
languages might present challenges due to performance and memory limitations.
Application Areas of Scripting Languages
1.Web Development: Scripting languages like JavaScript, Python (Django,
Flask), Ruby (Ruby on Rails), and PHP are commonly used for building
dynamic web applications and websites.
2.Automation and Scripting: Scripting languages such as Python, Bash,
and PowerShell are used for automating system administration tasks, data
processing, and repetitive operations.
3.Data Analysis and Manipulation: Python, along with libraries like
NumPy and Pandas, is frequently used for data analysis, manipulation,
and visualization.
4.Game Development: Some scripting languages, like Lua, are used for
scripting game logic and behavior in video game development.
Application Areas of Scripting Languages
1.Embedded Systems: Scripting languages are employed in embedded systems
for tasks such as configuring and controlling hardware devices.
2.Networking and Systems: Scripting languages like Python and Perl are used
for network programming, server administration, and network automation.
3.Testing and Quality Assurance: Scripting languages are often used to
automate testing processes and ensure software quality.
4.Scientific Computing: Python and MATLAB are used in scientific computing
for simulations, data analysis, and research.
5.Education and Learning: Scripting languages are frequently used as
introductory languages in programming courses due to their ease of learning
and quick feedback loop.
Server-Side Programming
• Server-side programming refers to the code that runs on the web
server, processing requests from clients (usually web browsers) and
generating dynamic content that is then sent to the client.
• It involves handling business logic, data processing, and database
interactions.
• Common server-side programming languages include Python, Ruby,
PHP, Java, and Node.js.
Advantages of Server-Side Programming
1.Security: Sensitive operations and data processing can be securely
handled on the server, reducing the exposure of critical logic and data to
the client.
2.Data Integrity: Server-side code can ensure consistent and accurate data
processing, reducing the risk of inconsistent or erroneous information
reaching the client.
3.Scalability: Server-side code can be optimized and scaled independently
from the client, allowing for better control over performance and resource
management.
4.Complex Operations: Server-side programming is well-suited for
complex calculations, data transformations, and database interactions.
Disadvantages of Server-Side Programming
1.Response Time: Server-side processing can introduce latency, as the
client has to wait for the server to generate and send the response.
2.Server Load: High traffic can put a strain on the server's resources,
potentially leading to slower response times or server crashes.
3.Limited Interactivity: Server-side interactions might not provide the
same level of interactivity as client-side interactions.
Client-Side Programming
• Client-side programming refers to the code that runs in the user's web
browser.
• It's responsible for rendering and interacting with the user interface,
enhancing user experience, and performing tasks without requiring
round-trips to the server.
• Common client-side programming languages include HTML, CSS,
and JavaScript.
Advantages of Client-Side Programming
1.Responsiveness: Client-side programming allows for instant feedback
and real-time interactions without waiting for server responses.
2.User Experience: Client-side code enables dynamic and visually
appealing user interfaces, resulting in a smoother and more engaging
experience.
3.Reduced Server Load: Lighter server-side processing can lead to
reduced server load, as some tasks are offloaded to the client.
4.Offline Functionality: Modern client-side technologies like Service
Workers enable web applications to function partially or fully offline.
Disadvantages of Client-Side Programming
1.Security Risks: Sensitive logic and data handling on the client side
can expose vulnerabilities, as code is more accessible to malicious
actors.
2.Browser Compatibility: Different browsers may interpret client-side
code differently, leading to compatibility issues.
3.Limited Processing Power: Client-side devices may have limited
processing power, affecting performance and complex operations.
4.SEO Challenges: Search engine optimization (SEO) can be
challenging for client-side-rendered content, as search engines may
have difficulty crawling dynamic content.
Choosing Between Server-Side and Client-
Side Programming
• The choice between server-side and client-side programming depends
on the specific requirements of the application. In many cases, a
combination of both approaches (known as a full-stack approach) is
used to leverage the strengths of each.
• Use server-side programming for: data processing, authentication,
authorization, database management, and complex business logic.
• Use client-side programming for: enhancing user interface,
interactivity, real-time updates, and immediate user feedback.
• It's important to strike a balance between the two approaches to create
a web application that is responsive, secure, and efficient.
Internet Technology
• The Internet is the global system of interconnected computer networks
that uses the Internet protocol suite to communicate between networks
and devices.
• It is a network of networks that consists of private, public, academic,
business, and government networks of local to global scope, linked by
a broad array of electronic, wireless, and optical networking
technologies.
• The Internet carries a vast range of information resources and services,
such as the inter-linked hypertext documents and applications of the
World Wide Web, electronic mail, telephony, and file sharing.
Static Website
• Static Web pages are very simple. It is written in languages such as HTML,
JavaScript, CSS, etc.
• Static websites are the websites that doesn’t change the content or layout
dynamically with every request to the web server.
• Static websites display exactly the same information whenever anyone visits
it.
• User sees the updated content of Static Website only when a web author
manually updates them with a text editor or any web editing tool used for
creating websites.
• Static webpages do not have to be simple plain text. They can feature
multiple design and even videos.
Static Website
Content: The content of a static website is predetermined and remains constant until
someone manually edits the HTML files.
Performance: Static websites are generally faster to load since they only need to serve
static files. This can lead to a better user experience and improved search engine
optimization (SEO).
Security: Since there is no interaction with a database or server-side scripting, static
websites are generally considered more secure because there are fewer attack vectors.
Hosting: Static websites can be hosted on simple web servers, content delivery networks
(CDNs), or even on cloud storage services.
Development Complexity: Creating and maintaining static websites is often simpler and
requires less technical knowledge compared to dynamic websites.
Scalability: Scaling static websites is straightforward since they don't rely on complex
server-side processes.
Advantages of Static websites
• Static websites are highly cost-effective for publishing.
• They require less coding and technical knowledge.
• Static websites are easier to make.
• Static websites are quick to develop.
• Static websites are cheap to host.
• A static website contains data which is immutable.
• Static websites are beginner level. A programmer with knowledge of HTML,
CSS, and JavaScript can build static websites.
• It’s easy to create and host online.
• Static websites provide security.
Disadvantages of Static Websites
• Requires web development expertise to update site.
• Site not as useful for the user.
• Content can get stagnant(dull i.e showing no activity).
• Send the same response for every request.
• Dynamic functionality works only on the client side.
Dynamic website
Dynamic website
• Dynamic websites are those websites that changes the content or layout with
every request to the webserver.
• These websites have the capability of producing different content for different
visitors from the same source code file.
• There are two kinds of dynamic web pages i.e. client side scripting and server
side scripting.
• The client-side web pages changes according to your activity on the web
page.
• On the server-side, web pages are changed whenever a web page is loaded.
• Example: login & signup pages, application & submission forms, inquiry and
shopping cart pages. A Typical Architecture of dynamic website
Advantages of dynamic webpage
• It provides more functional websites.
• It is very easy to update.
• It helps in the search engines because new content brings people back to the site.
• These are interactive websites because these can be customized.
• These websites can work as a system to allow staff or users to collaborate.
• It’s easy to modify or update data.
• It provides a user-friendly interactive interface for users.
• Proves smooth navigation, provide interactive user interface
• It provides a better user experience.
• It provides real-time data.
Disadvantages of dynamic webpages
• These types of websites are complex.
• These are more expensive to develop.
• Hosting of these websites is also costlier.
• It requires a rapid, high-end web server.
• High production costs.
• Slow to load content.
• Client will require a skilled programmer to build a dynamic website.
• Hosting a website is costly as compared to a dynamic website.
• Low speed compared to a static website
Application of Dynamic Website
• Online booking system:
• E-commerce website.
• Voting or polls,
• Forums
• E-newsletter.
JavaScript
• JavaScript is a lightweight, interpreted programming language.
• It is designed for creating network-centric applications.
• It is complimentary to and integrated with Java. JavaScript is very
easy to implement because it is integrated with HTML.
• It is open (anyone can implement the JavaScript language
specification without needing permission from a specific entity, and
developers are free to create their own tools, libraries, and frameworks
that use JavaScript) and cross-platform (it can be executed on a wide
range of platforms and devices. It is not tied to a specific operating
system or architecture).
JavaScript
<script>
document.write("Hello JavaScript by JavaScript");
</script>
Features
• JavaScript is a lightweight, interpreted programming language.
• Designed for creating network-centric applications.
• Complementary to and integrated with Java.
• Complementary to and integrated with HTML.
• It is case sensitive language.
• JavaScript is supportable in operating system.
• It provides good control to the users over the web browsers.
Advantages of JavaScript
• Less server interaction: You can validate user input before sending the
page off to the server. This saves server traffic, which means fewer
loads on your server.
• Easy to learn: By learning few commands and simple rules of syntax,
you can easily build applications using JavaScript.
• Immediate feedback to the visitors: They don't have to wait for a page
reload to see if they have forgotten to enter something.
• Increased interactivity: You can create interfaces that react when the
user hovers over them with a mouse or activates them via the keyboard.
• Quick Development: Scripts can be developed in short period of time
Advantages of JavaScript
• Richer interfaces: You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.
• Transmitting information: About the users' reading habits and browsing
activities to various websites. Web pages frequently do this for web
analytics, ad tracking personalization or other purposes.
• Easy Debugging and Testing: As JavaScript is interpreted line by line, it is
easy to find error and make changes.
• Interactive content, for example games, and playing audio and video.
• Validating input values of a Web form to make sure that they are acceptable
before being submitted to the server.
Uses of JavaScript
• Client side validation
• Dynamic drop down menus.
• Displaying date and time.
• Displaying pop-up windows and dialog boxes
• Displaying clocks.
• Event handling.
• Developing Mobile applications
• Creating web browser based games.
• Building web servers
• Adding interactivity to website.
Adding JavaScript to HTML
• JavaScript, also known as JS, is one of the scripting (client-side
scripting) languages, that is usually used in web development to create
modern and interactive web-pages.
• The term "script" is used to refer to the languages that are not
standalone in nature and here it refers to JavaScript which run on the
client machine.
• In other words, we can say that the term scripting is used for
languages that require the support of another language to get executed.
Adding JavaScript to HTML
• For example, JavaScript programs cannot get executed without the
help of HTML or without integrated into HTML code.
1. Embedding code
2. Inline code
3. External file
Embedding code
• To add the JavaScript code into the HTML pages, we can use the tag
of the HTML that wrap around JavaScript code inside the HTML
program.
• Users can also define JavaScript code in the <body> tag or we can say
body section) or <head> tag because it completely depends on the
structure of the web page that the users use.
<html>
<head>
<title> page title</title>
<script>
document.write("Welcome to Java Script Programming");
</script>
</head>
<body>
<p>In this example we saw how to add JavaScript in the head section
</p>
</body>
</html>
<html>
<head>
<title> Body Section Example</title> </head>
<body>
<script>
document.write("Welcome to Balmandir");
</script>
<p> In this example we saw how to add JavaScript in the body section
</p>
</body>
</html>
Inline code
• Generally, this method is used when we have to call a function in the
HTML event attributes.
• There are many cases (or events) in which we have to add JavaScript
code directly eg., OnMover event, OnClick, etc.
• Let's see with the help of an example, how we can add JavaScript
directly in the html without using the tag.
<html>
<head>
<title> Inline code example</title> </head>
<body>
<p>
<a href="#" onClick="alert('Welcome !');">Click Me</a>
<button onclick="alert('Hello Class 12')">Click Here</button>
</p>
<p> In this example we saw how to use inline JavaScript or directly in
an HTML tag.
</p> </body> </html>
External file
• We can also create a separate file to hold the code of JavaScript with
the (.js) extension and later incorporate/include it into our HTML
document using the src attribute of the <script> tag.
• It becomes very helpful if we want to use the same code in multiple
HTML documents.
• It also saves us from the task of writing the same code over and over
again and makes it easier to maintain web pages.
• In this example, we will see how we can include an external
JavaScript file in an HTML document. Let's understand through a
simple example.
<html>
<head>
<title>Including a External JavaScript File</title>
</head>
<body>
<form>
<input type="button" value="Result" onclick="display()"/>
</form>
<script src="hello.js">
</script>
</body>
</html>
• Now let's create separate JavaScript file = Hello.js
function display()
{
alert("Hello Class 12 Friends!");
}
JavaScript Fundamentals
Script
• JavaScript statements are written within <script> ….</script>.
• The <script> tag alerts the browser program to start interpreting all the
statements between these tags as a script.
• A simple syntax of your JavaScript will appear as follows:
Syntax:
<script>
block of Statements
</script>
Statements
• JavaScript statements are composed of Values, Operators, Expressions,
Keywords, and Comments.
• The program consists of many statements.
• The statements are executed, one by one, in the same order as they are
written.
• It is often called JavaScript code.
var area = l*b;
JavaScript comments
• 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.
• There are two types of comments in JavaScript.
1. Single-line Comment
2. Multi-line Comment
Single line Comment
• It is represented by double forward slashes (//).
• It can be used before and after the statement.
• Let’s see the example of single-line comment i.e. added before the
statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>
Single line Comment
• Let’s see the example of single-line comment i.e. added after the
statement.
<script>
var a=10;
var b=20;
var c=a+b; //It adds values of a and b variable
document.write(c); //prints sum of 10 and 20
</script>
Multi line Comment
• It can be used to add single as well as multi line comments. So, it is more
convenient. It is represented by forward slash with asterisk then asterisk
with forward slash. For example:
/* your comment 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>
• Whitespace and Line Breaks: JavaScript ignores spaces, tabs, and
newlines that appear in JavaScript programs. To make a code readable
and understandable, formatting and indenting the code by using
several spaces, tabs, and newlines can be used freely in the program.
• Case Sensitivity: JavaScript is a case-sensitive language. The
keywords, variables, functions names, and any other identifiers must
always be typed with a consistent capitalization of letters. So the
identifiers Time and TIME will convey different meanings in
JavaScript.
• Output: Java Script can "display" data in different ways: It defines the
ways to display the output of a given code. The output can be display
by using four different ways which are listed below:
1. Document.write
• Using document.write( ), the output can be displayed in browser page.
<html>
<head> <title> Display functions in Javascript </title>
</head>
<body>
<h1> Output with document.write</h1> <br>
Hello Class 12 <br>
<script>
document.write(7+5)
</script>
<input type="button" value="Click Me" onclick="document.write(7+5)">
</body>
</html>
2. Inner HTML
• Using inner HTML, the output can be displayed into the HTML
element.
• The innerHTML property sets or returns the HTML content (inner
HTML) of an element.
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
3. Window. Alert
• Using window.alert( ), the output can be displayed into an alert box.
window.confirm() and window.prompt() are also other method to output into an
alert box.
<html>
<head> <title> Display functions in Javascript </title>
</head>
<body>
<h1> Output Message with window alert</h1> <br>
<script>
alert(7+5);
</script>
</body></html>
4. Console.log
• Using console.log( ), the output can be displayed into the browser console.
• To use console of web browser, right click in web browser and select inspect. The console will
display.
<!DOCTYPE html>
<html>
<body>
<h1>The Console Object</h1>
<h2>The log() Method</h2>
<p>Remember to open the console (Press F12) before you click "Run".</p>
<script>
console.log(“Welcome to MajorToli!");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>The Console Object</h1>
<h2>The log() Method</h2>
<p>Remember to open the console (Press F12) before you click "Run".</p>
<p>How to display an object in the console.</p>
<script>
const myObj = {firsname:"John", lastname:"Doe"};
console.log(myObj);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>The Console Object</h1>
<h2>The log() Method</h2>
<p>Remember to open the console (Press F12) before you click "Run".</p>
<p>How to display an array in the console.</p>
<script>
const myArr = ["Orange", "Banana", "Mango", "Kiwi"];
console.log(myArr);
</script>
</body>
</html>
Reserved Words
• Lists of all the reserved words in JavaScript are given in the following
table. They cannot be used as Java Script variables, functions,
methods, loop labels, or any object names.
JavaScript Data Types
• 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 is a dynamic type language, means you don't need to specify
type of the variable because it is dynamically used by JavaScript engine.
You need to use var here to specify the data type.
• It can hold any type of values such as numbers, strings etc. For example:
var a=40; //holding number
var b="Rahul"; //holding string
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types
of variables in JavaScript:
local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as
identifiers).
1. Name must start with a letter (a to z or A to Z), underscore ( _ ), or dollar( $ )
sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. Reserved words cannot be used as names.
4. JavaScript variables are case sensitive, for example x and X are different
variables.
JavaScript Variable
Correct JavaScript variables
1. var x = 10;
2. var _value="Hari";

Incorrect JavaScript variables


1. var 123=30;
2. var *aa=320;
Example of JavaScript variable
<html>
<head>
<title> Example of Variable </title>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
Eg: 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
7. Unary Operator
8. String Operator
9. Conditional Operator
JavaScript Arithmetic Operators
• Arithmetic operators are used to perform arithmetic operations on the
operands.
Example
<html>
<body>
<h2>Arithmetic Operations</h2>
<p>A typical arithmetic operation takes two numbers (or expressions) and produces a new
number.</p>
<p id="Hello"></p>
<script>
let a = 3;
let x = (100 + 50) * a;
document.getElementById("Hello").innerHTML=x; // document.write(x); OR window.alert(x);
</script>
</body>
</html>
Example
<html>
<body>
<h1>JavaScript Operators</h1>
<h2>The + Operator</h2>
<p>The + operator concatenates (adds) strings.</p>
<script>
let text1 = "Rajesh";
let text2 = "Hamal";
let text3 = text1 + " " + text2;
document.write(text3);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>To toUpperCase() Method</h2>
<p>toUpperCase() converts a string to uppercase letters:</p>
<p id="demo"></p>
<script>
let text = "Hello World!";
let result = text.toUpperCase();
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
JavaScript Comparison Operators
• The JavaScript comparison operator compares the two operands.
JavaScript Bitwise Operators
• The bitwise operators perform bitwise operations on operands.
JavaScript Logical Operators
• The following operators are known as JavaScript logical operators.
JavaScript Assignment Operators
• The following operators are known as JavaScript assignment
operators:
JavaScript Special Operators
Functions and Function Return
• A JavaScript function is a block of code designed to perform a
particular task.
• A function is a go of reusable code which can be called anywhere in
your program.
• This eliminates the need of writing the same code again and again.
• It helps programmers in writing modular codes.
• Function allow a programmer to divide a big program into a number
of small and manageable function.
Advantages of Using Function
• Functions increases code reusability.
• Function helps to structure the code properly.
• Functions make code less complex.
• Functions make code more readable and extendable.
• Functions can be called anywhere in the program.
• Functions helps program developers to write the modular codes.
• Function also allows a programmer to divide a big program into a
number of small and manageable functions.
Function Definition
• Before we use a function, we need to define it.
• The most common way to define a function in JavaScript is by using the
function keyword, followed by a unique function name, a list di parameters
(that might be empty), and a statement block surrounded by curly braces.
Syntax: <script type="text/javascript">
function function_name (parameter-list)
{
//statements
}
</script>
Calling a Function
• The code written inside a function does not execute unless it is called.
• To call a function somewhere later in the script, you would simply need to write the name of that
function as shown in the following code.
<html> <title> </title> <head>
<script type="text/javascript">
function Hello()
{
document.write ("Hello Class 12");
}
</script> </head> <body>
<p>Click the following button to call the function </p>
<form>
<input type="button" onclick="Hello()" value= "Click Here">
</form> </body>
</html>
Example 2
<html>
<body>
<script>
function showMessage()
{
document.write ("Hello Class 12");
document.write ("Good Morning");
}
showMessage()
</script>
</body>
</html>
Function Parameters
A function can take multiple parameters separated by comma. The function parameters can have
value of any data type.
<html> <body>
<h2> Function with Parameters </h2>
<script>
var a= 3
var b= 4
add(a,b);
function add(a,b)
{
var sum=a+b;
document.write("sum of two number is="+sum); // OR alert("sum of two number is="+sum);
}
</script> </body> <html>
Function Return
• The return statement is used to return a particular value from the function to the function caller.
• The function will stop executing when the return statement is called.
• The return statement should be the last statement in a function because the code after the return
statement will be unreachable.
<html>
<head>
<title> Example of Function Return</title> </head>
<body>
<h1> Example of the JavaScript's return statement </h1>
<script>
var a=12;
var b= 20;
var res = fun(a, b);
function fun(x, y)
{
var r= x*y;
return (r);
}
document.write(res);
</script>
</body>
</html>
Above program is a simple example of using the return statement. Here, returning
the result of the product of two numbers and returned the value to the function
caller. The variable res is the function caller; it calls the function fun() and passes
two parameters as the arguments of the function.
The result will be store in the res variable. Final output 240 is the product of
arguments 12 & 20.
Control Structures
1. If-else
2. switch case
3. for loop
4. while loop
5. do while loop
The JavaScript if-else 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.
Syntax:
if(expression)
{
//content to be evaluated
}

Eg:
<script>
var a=20;
if(a>10)
{
document.write("value of a is greater than 10");
}
</script>
<html>
<head>
<title> Number to check Positive or not </title>
</head>
<body>
<script type= "text/javascript">
var num= prompt("Enter Number");
if (num>0)
{
document.write("Given number is Positive");
}
</script>
</body>
</html>
JavaScript If...else Statement
It evaluates the content whether condition is true of false.
Syntax:
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
<html>
<body>
<script>
var num= prompt("Enter Number");
if (num>0){
document.write("Given number is Positive");
}
else{
document.write("Given number is Negative");
}
</script>
</body>
</html>
<script>
var a=17;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
<html>
<body>
<script>
var num= prompt("Enter Number");
var x=num%2;
if (x==0){
document.write("Given number is Even");
}
else{
document.write("Given number is Odd");
}
</script>
</body>
</html>
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions.
Syntax:
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
Write a Program to input a number and check that is positive, negative or not.
<html>
<body>
<script>
var a=prompt("Enter 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>
</body>
</html>
The JavaScript switch statement
It is used to execute one code from multiple expressions. It is just like else if statement that
allow us to choose only one option among the many given options. 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;
}
<html>
<head>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
</head>
</html>
<html>
<head>
<title> Switch Case Example For to find Name of the day.</title>
</head>
<body>
<script>
var n=prompt("Enter a number between 1 and 7");
switch(n){
case(n="1");
document.write("The day is Sunday");
break;
case(n="2");
document.write("The day is Monday");
case(n="3");
document.write("The day is Tuesday");
break;
case(n="4");
document.write("The day is Wednesday");
break;
case(n="5");
document.write("The day is Thursday");
break;
case(n="6");
document.write("The day is Friday");
break;
default:
document.write("Invalid day");
break;
</script>
</body>
</html>
JavaScript Loops / Iterations
• The processing of repeatedly executing the block of statements is called
iteration or looping.
• Loops are used to repeat the execution of a block of code. The JavaScript
loops are used to iterate the piece of code using for, while, do while.
• 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
JavaScript For loop
• For loop is used to execute a set of statements for given number of times.
• The JavaScript for loop iterates the elements for the fixed number of
times.
• It should be used if number of iteration is known. The syntax of for loop
is given below.
Syntax:
for (initialization; condition; increment)
{
code to be executed
}
<html>
<head>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>") // OR document.write(i);
}
</script>
</head>
</html>
JavaScript While loop
• The while loop is an entry controlled loop in which condition is
checked before the execution of loop.
• Syntax:
while (condition)
{
// code block to be executed
}
Example: WAP to display even number from 1 to 20.

<script>
var i=2;
while (i<=20)
{
document.write(i);
i=i+2;
}
</script>
JavaScript do while loop
• The JavaScript do while loop iterates the elements for the infinite
number of times like while loop. But, code is executed at least once
whether condition is true or false.
• Syntax:
do
{
code to be executed
}while (condition);
Example
<script>
var i=1;
do{
document.write(i + "<br/>");
i=i+2;
}while (i<=20);
</script>
<!doctype html>
<html>
<head>
<script>
function add()
{
var num1, num2, sum;
num1 = parseInt(document.getElementById("firstnumber").value);
num2 = parseInt(document.getElementById("secondnumber").value);
sum = num1 + num2;
document.getElementById("answer").value = sum;
}
</script>
</head>
<body>
<p>First Number: <input id="firstnumber"></p>
<p>Second Number: <input id="secondnumber"></p>
<button onclick="add()">Add Them</button>
<p>Sum = <input id="answer"></p>
</body>
</html>
Get user input one by one
<!doctype html>
<html>
<head>
<script>
var numOne, numTwo, sum;
function getFirNum()
{
numOne = parseInt(document.getElementById("first").value);
if(numOne)
{
temp = document.getElementById("paraOne");
temp.style.display = "none";
temp = document.getElementById("paraTwo");
temp.style.display = "block";
}
}
function getSecNum()
{
numTwo = parseInt(document.getElementById("second").value);
if(numOne && numTwo)
{
temp = document.getElementById("paraOne");
temp.style.display = "none";
temp = document.getElementById("paraTwo");
temp.style.display = "none";
sum = numOne + numTwo;
temp = document.getElementById("paraThree");
temp.style.display = "block";
document.getElementById("res").innerHTML = sum;
}
}
</script>
</head>
<body>

<p id="paraOne">Enter First Number: <input id="first">


<button onclick="getFirNum()">Enter</button></p>
<p id="paraTwo" style="display:none;">Enter Second Number: <input
id="second">
<button onclick="getSecNum()">Add</button></p>
<p id="paraThree" style="display:none;">Sum = <span id="res"></span></p>

</body>
</html>
• style="display:none;”
is a CSS code that hides an HTML element where it is included.
Because it is included in a p (paragraph) tag whose id is paraTwo, this
paragraph gets hidden initially.

• temp.style.display = "block";
states that, an HTML element whose id is stored in temp variable, gets
visible after executing this statement.

• document.getElementById("res").innerHTML = sum;
states that the content of an HTML element with id res gets replaced
with the value of sum.
Object based Programming with Java Script
and Event Handling Object
• Object is a non-primitive data type in JavaScript.
• Object is like any other variable but it is quite differ from variable.
• The variable can hold only one value but object can hold multiple
values.
• The object holds multiple values in terms of properties and methods.
Properties can hold values of primitive data types and methods are
functions.
• An object is defined simple way as like a variable.
• The object is defined with a unique object name and the curly brackets {
} is used to include properties and methods.
Object
• The variables within the object is known as properties and the function
within the object is known as methods.
• The properties or method are written as name: value pairs.
• The name and value separated by a colon. The period ‘.’ is used to
access value to object.
Syntax:
• var object_name = { name: value1, name2: value2, nameN: valueN };
Example
<html>
<body>
<script>
var emp={id:101,name:"Ram Prasad",salary:50000}
document.write(emp.id+" "+emp.name+" "+emp.salary + "<br/>");
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
In the above example, object name is defined as emp and it has three properties id, name and
salary. The value of object can be accessed easily using object name period and properties
name.
Creating Objects in JavaScript
• There are 3 ways to create objects:
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
JavaScript Object by object literal
• The syntax of creating object using object literal(key-value pair) is
given below:
• object={property1:value1,property2:value2.....propertyN:valueN}
• JavaScript Object Literal is a data type used to define objects in
JavaScript.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>
<p id="demo"></p>
<script>
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
<html>
<head>
<title> </title>
<script>
var vehicle = {
color:"green",
weight:50,
height:5,
move:function()
{
document.write("vehicle moves");
}
};
vehicle.move();
</script>
</head>
<body>
</body>
</html>
By creating instance of Object
• The syntax of creating object directly is given below:
• var objectname=new Object();
<html>
<body>
<script>
var study=new Object();
study.roll=10;
study.name="Rajesh Hamal";
study.class=12;
document.write(study.roll +"<br>");
document.write(study.name +"<br>");
document.write(study.class);
</script>
</body>
</html>
By using an Object constructor
• Here, you need to create function with arguments. Each argument
value can be assigned in the current object by using this keyword. The
this keyword refers to the current object.
• The example of creating object by object constructor is given below.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Object Constructors</h2>
<p id="demo"></p>
<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");
// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ".";
</script>
</body>
</html>
Document Object Model
• The document object represents the whole html document.
• When html document is loaded in the browser, it becomes a document
object.
• It is the root element that represents the html document. It has
properties and methods.
• By the help of document object, we can add dynamic content to our
web page.
Properties of document object
Anchor (<a>)
• An anchor element, represented by the <a> tag, is used to create
hyperlinks on a web page.
• It allows you to link to other web pages or resources.
• For example:
<a href="https://www.example.com">Visit Example.com</a>
• In this example, clicking the "Visit Example.com" link would take you
to the website specified in the href attribute.
Form
• A form is a fundamental HTML element used to collect user input on a
web page.
• It is defined using the <form> tag and contains various input fields
like text inputs, checkboxes, radio buttons, and buttons.
• Users can enter data into these fields and submit the form to send the
data to a server for processing.
• In below example, when the user clicks the "Submit" button, the data
from the form is sent to the server at the specified action URL using
the HTTP POST method.
Example
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<input type="submit" value="Submit">
</form>
Link (<link>)
• The <link> element is used in the <head> section of an HTML
document to define external resources, such as stylesheets (CSS) and
icon files.
• It does not create a visible element on the page but is crucial for
linking external files to your HTML document.
• Here's an example of linking a stylesheet:
<link rel="stylesheet" type="text/css" href="styles.css">
• In this example, the href attribute specifies the URL of the external
CSS file, which will be applied to the HTML document.
Accessing field value by document object
• In this example, we are going to get the value of input text by user.
Here, we are using document.form1.name.value to get the value of
name field.
• Here, document is the root element that represents the html document.
form1 is the name of the form. name is the attribute name of the input
text. value is the property, that returns the value of the input text.
<script type="text/javascript">
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" onclick="printvalue()" value="print name"/>
</form>
1. getElementById( )
• The document.getElementById() method returns the element of
specified id.
• We can use document.getElementById() method to get value of the
input text.
• But we need to define id for the input field.
<html>
<body>
<p id="demo"></p>
<p id="try"></p>
<script>
var x="How are you"
document.getElementById("demo").innerHTML = x;
document.getElementById("try").innerHTML= " I am fine and you"
</script>
getElementsByName()
• The document.getElementsByName() method returns all the element
of specified name. The syntax of
• the getElementsByName() method is given below:
• document.getElementsByName("name") Here, name is required.
<script>
function totalelements()
{
var g=document.getElementsByName("gender");
alert("Total Genders:"+g.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">


</form>
document.getElementsByTagName()
• The document.getElementsByTagName() method returns all the
element of specified tag name.
• The syntax of the getElementsByTagName() method is given below:
• document.getElementsByTagName("name") Here, name is required.
<script type="text/javascript">
function countpara()
{
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by
getElementByTagName() method.
</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
<script type="text/javascript">
function counth2()
{
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3()
{
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>
Javascript - innerHTML
• The innerHTML property can be used to write the dynamic html on
the html document. It is used mostly in the web pages to generate the
dynamic html such as registration form, comment form, links etc.
• Example of innerHTML property :
• In this example, we are going to create the html form when user clicks
on the button. In this example, we are dynamically writing the html
form inside the div name having the id mylocation. We are identifying
this position by calling the document.getElementById() method.
<html>
<body>
<script type="text/javascript" >
function showcommentform() {
var data="Name:<br><input type='text' name='name'><br>Comment:<br><textarea
rows='5' cols='50'></textarea><br><input type='submit' value='comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
</body>
</html>
JavaScript Events
• The change in the state of an object is known as an Event. In html,
there are various events which represents that some activity is
performed by the user or by the browser.
• When JavaScript code is included in HTML, JavaScript react over
these events and allow the execution. This process of reacting over the
events is called Event Handling.
• Thus, JavaScript handles the HTML events via Event Handlers.
• For example, when a user clicks over the browser, add js code, which
will execute the task to be performed on the event. Some of the HTML
events and their event handlers are:
Click Event
<html>
<head> Javascript Events </head>
<body>
<script>
function clickevent()
{
document.write("This is a Click Events");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Click To View"/>
</form>
</body>
</html>
Mouse Over Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script>
function mouseoverevent()
{
alert("This is a MouseOverEvent");
}
</script>
<p onmouseover="mouseoverevent()"> Keep Mouse's cursor over me</p>
</body>
</html>
Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
</script>
</body>
</html>
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
</script>
</body>
</html>
Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
document.write(“MajorToli is back");
</script>
</body>
</html>
Form Validation
• It is important to validate the form submitted by the user because it
can have inappropriate values. So, validation is must to authenticate
user. JavaScript provides facility to validate the form on the client-side
so data processing will be faster than server-side validation. Most of
the web developers prefer JavaScript form validation. Through
JavaScript, we can validate name, password, email, date, mobile
numbers and more fields. In this example, we are going to validate the
name and password. The name can’t be empty and password can’t be
less than 6 characters long. Here, we are validating the form on form
submit. The user will not be forwarded to the next page until given
values are correct.
Form Validation
<html>
<body>
<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;
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
JavaScript Retype Password Validation
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
<form name="f1" action="register.jsp" 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
<script>
function validate()
{
var num=document.myform.num.value;
if (isNaN(num))
{
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}
Else
{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
File Type Validation while Uploading it using JavaScript

<!DOCTYPE html>
<html>
<head>
<title>
File Type Validation while
Uploading it using JavaScript
</title>
<style>
h1 {
color: green;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>
MajorToli
</h1>
<h3>
Validation of file type while
uploading using JavaScript?
</h3>
<!-- File input field -->
<p>Upload an Image</p>
<input type="file" id="file"
onchange="return fileValidation()" />
<!-- Image preview -->
<div id="imagePreview"></div>
<script>
function fileValidation() {
var fileInput =
document.getElementById('file');

var filePath = fileInput.value;

// Allowing file type


var allowedExtensions =
/(\.jpg|\.jpeg|\.png|\.gif)$/i;
if (!allowedExtensions.exec(filePath)) {
alert('Invalid file type');
fileInput.value = '';
return false;
}
else
{
// Image preview
if (fileInput.files && fileInput.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById(
'imagePreview').innerHTML =
'<img src="' + e.target.result
+ '"/>';
};
reader.readAsDataURL(fileInput.files[0]);
}
}
}
</script>
</body>
</html>
JavaScript email validation
• We can validate the email by the help of JavaScript.
• There are many criteria that need to be follow to validate the email id
such as:
• Email id must contain the @ and . character
• There must be at least one character before and after the @.
• There must be at least two characters after. (Dot).
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
• HTML - HTML is used to design static webpage.
• CSS - CSS helps to make the webpage content more effective and
attractive.
• JavaScript - JavaScript is used to design an interactive website.
JQuery
• JQuery is a fast, small, lightweight, "write less, do more", and feature-rich
JavaScript library.
• It makes things like HTML document traversal and manipulation, event handling
animation, and Ajax much simpler with an easy-to-use API (Application
Programming Interface) that works across browsers. With a combination of
versatility and extensibility, jQuery has changed the way that millions of people
write JavaScript.
• JQuery is a JavaScript library.
• The purpose of jQuery is to make it much easier to use JavaScript on your
website. JQuery simplifies a lot of the complicated things from JavaScript like
AJAX (Asynchronous JavaScript and XML) calls and DOM (Document Object
Model) manipulation.
• Some of the biggest companies which uses jQuery on the Web are 1. Google 2.
Microsoft 3. IBM
Features of jQuery
1. The jQuery is very small, fast, lightweight JavaScript library
2. It is very fast and extensible.
3. It has a lot of built-in animation effects which can use directly in
websites.
4. It is used to improve the performance of an application.
5. It is used to develop browser's compatible web applications effectively.
6. It uses mostly new features of new browsers.
7. It is platform-independent.
8. It is used to develop a responsive web application.
Server Side Scripting Using PHP
• Server side script are discrete blocks of program code that execute on a
web server (as opposed to a web client) computer.
• They are generally used to create Dynamic web pages.
• This means that the page displayed to the user does not exist as a
document on the server in its own right, and is only brought into existence
in response to a user request.
• Often, a server-side script provides the interface between a web-based
user interface and a database that resides on a web server.
• PHP is a server side scripting language used to create dynamic web pages.
• PHP is well suited for web development.
Features of PHP
1. Simple
2. Interpreted
3. Faster
4. Open Source
5. Platform Independent
6. Case Sensitive
7. Error Reporting
8. Real-Time Access Monitoring
9. Loosely Typed Language
Characteristics of PHP
1. Simplicity
2. Efficiency
3. Security
4. Flexibility
5. Familiarity
Advantages of PHP
1. PHP is Free
2. PHP is Cross Platform
3. PHP is widely used
4. PHP hides its complexity
5. PHP is built for Web Programming
Weaknesses of PHP
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. Bad packages that got popular in the community are still reused when
developers are trying something new or rushed for time. Some of these
mistakes lead to security risks.
4. As a mature tool PHP has some legacy baggage. There are lots of internal
consistencies, especially surrounding references and values.
This is mostly due to updates, which add features that clash with earlier
features,
Weaknesses of PHP
5. PHP is an interpreted language, which can reduce speed.
6. PHP 7 increased performance over previous versions by a significant
amount while maintaining most language compatibility.
7. The changes didn't affect the learning curve or existing applications
much while improving performance. Still, it executes more slowly than
compiled languages.
8. Scaling and maintaining PHP is a complicated endeavor.
9. Context matters a great deal in dynamically typed languages, so
tracking down errors gets harder the larger an application grows.
Object Oriented Programming with Server
Side Scripting
Object Oriented is an approach to software development that models
application around real world objects such as employees, cars, bank
accounts, etc.
A class defines the properties and methods of a real world object. An
object is an occurrence of a class.
There are three major principles of OOP are:
1. Encapsulation: This is concerned with hiding the implementation
details and only exposing the methods. It used to reduce software
development complexity.
• The Encapsulation is achieved using "get" and "set" methods.
2. Inheritance: This is concerned with the relationship between classes.
The main purpose of inheritance is the re-usability.
The Inheritance is achieved - using extends keyword.

3. Polymorphism: This is concerned with having a single form but


many different implementation ways.
• The main purpose of polymorphism is to simplify maintaining
applications and making them more extendable.
• The Polymorphism is achieved - using implements keyword
Hardware and Software Requirements
Hardware
• Hardware requirement are not much, we just need a laptop or desktop
computer. PHP 5.5+ require a computer with at least window
2008/vista. The computer with Pentium IV processor, RAM 2GB, hard
disk 256 GB, color monitor or above is more than enough.
Software
• To run PHP code, we need the following software on our local
machine. 1. Browser 2. Web server (eg. Apache) 3. PHP (interpreter)
4. MySQL Database (it is optional)
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, LAMP,
and 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.
Basic PHP Syntax
• A PHP script can be placed anywhere in the document. A PHP script starts
with <?php and ends with ?>

<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP scripting code.
• Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:
Example
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello Class 12";
?>
</body>
</html>
Note: PHP statements end with a semicolon (;).
PHP Case Sensitivity
• In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive.
• In the example below, all three echo statements below are equal and legal:
<html>
<body>
<?php
ECHO "Hello Class 12<br>";
echo "Hello Class 12<br>";
EcHo "Hello Class 12<br>";
?>
</body>
</html>
Comments in PHP
• Comments are used to make code more readable. There are two types of comments
–single line and multiline comments. A single line comments starts with // while
multi-line comment begins with /* and end with */.
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
?>
</body>
</html>
Multi-line comment
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
• Loosely typed language: PHP is a loosely typed language, it means
PHP automatically converts the variable to its correct data type.
• PHP Variables: A variable can have a short name (like x and y) or a
more descriptive name (age, carname, total_volume).
Rules for PHP variables
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different
variables)
PHP Variable: Declaring string, integer, and
float
• Let's see the example to store string, integer, and float values in PHP
variables.
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
PHP Variable Scope
• The scope of a variable is defined as its range in the program under
which it can be accessed. In other words, "The scope of a variable is
the portion of the program within which it is defined and can be
accessed."
• PHP has three types of variable scopes:
1. Local variable
2. Global variable
3. Static variable
Local variable
• The variables that are declared within a function are called local
variables for that function.
• These local variables have their scope only in that particular function
in which they are declared. This means that these variables cannot be
accessed outside the function, as they have local scope.
• A variable declaration outside the function with the same name is
completely different from the variable declared inside the function.
• Let's understand the local variables with the help of an example:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Global variable
• The global variables are the variables that are declared outside the
function.
• These variables can be accessed anywhere in the program. To access
the global variable within a function, use the GLOBAL keyword
before the variable.
• However, these variables can be directly accessed or used outside the
function without any keyword. Therefore there is no need to use any
keyword to access a global variable outside the function.
• Let's understand the global variables with the help of an example:
<?php
$name = "Sanaya Sharma"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Basic Programming in PHP
PHP echo and print Statements
• We frequently use the echo statement to display the output. There are
two basic ways to get the output in PHP:
• echo
• print
• echo and print are language constructs, and they never behave like a
function.
• Therefore, there is no requirement for parentheses. However, both the
statements can be used with or without parentheses. We can use these
statements to output variables or strings.
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
print "<h2>PHP is Case Sensitive!</h2>";
print "Hello Class 12!<br>";
print "I'm about to learn PHP!";
?>
Difference between echo and print
echo
• echo is a statement, which is used to display the output.
• echo can be used with or without parentheses.
• echo does not return any value.
• We can pass multiple strings separated by comma (,) in echo.
• echo is faster than print statement.
print
• print is also a statement, used as an alternative to echo at many times to display the
output.
• print can be used with or without parentheses.
• print always returns an integer value, which is 1.
• Using print, we cannot pass multiple arguments.
• print is slower than echo statement.
PHP Data Types
• Variables can store data of different types, and different data types can do
different things.
• PHP supports the following data types:
1. String
2. Integer
3. Float (floating point numbers - also called double)
4. Boolean
5. Array
6. Object
7. NULL
8. Resource
PHP Data Types: Compound Types
• It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
PHP Data Types: Special Types
• There are 2 special data types in PHP.
1. resource
2. NULL
PHP Boolean
• Booleans are the simplest data type works like switch. It holds only
two values: TRUE (1) or FALSE (0). It is
• often used with conditional statements. If the condition is correct, it
returns TRUE otherwise FALSE.
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
PHP Integer
• Integer means numeric data with a negative or positive sign. It holds only
whole numbers, i.e., numbers
• without fractional part or decimal points.
Rules for integer:
• An integer can be either positive or negative.
• An integer must not contain decimal point.
• Integer can be decimal (base 10), octal (base 8), or hexadecimal (base
16).
• The range of an integer must be lie between 2,147,483,648 and
2,147,483,647 i.e., -2^31 to 2^31.
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
PHP Float
• A floating-point number is a number with a decimal point. Unlike
integer, it can hold numbers with a fractional or decimal point,
including a negative or positive sign.
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
PHP String
• A string is a non-numeric data type.
• It holds letters or any alphabets, numbers, and even special characters.
• String values must be enclosed either within single quotes or in double quotes.
• But both are treated differently. To clarify this, see the example below:
<?php
$company = “MajorToli";
//both single and double quote statements will treat different
echo “Jay $company";
echo "</br>";
echo ‘Hello $company';
?>
PHP Array
• An array is a compound data type.
• It can store multiple values of same data type in a single variable.
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
PHP object
• Objects are the instances of user-defined classes that can store both values and functions.
They must be explicitly declared.
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
PHP Resource
• Resources are not the exact data type in PHP.
• Basically, these are used to store some function calls or references to
external PHP resources.
• For example - a database call. It is an external resource. This is an
advanced topic of PHP, so we will discuss it later in detail with examples.
<?php
$n = NULL;
echo $n; //it will not give any output
?>
PHP Operators
• PHP Operator is a symbol i.e used to perform operations on operands.
• In simple words, operators are used to perform operations on variables
or values.
• For example: $num=10+20; //+ is the operator and 10,20 are operands
• In the above example, + is the binary + operator, 10 and 20 are
operands and $num is variable.
• PHP Operators can be categorized in following forms:
1. Arithmetic Operators
2. Assignment Operators
3. Bitwise Operators
4. Comparison Operators
5. Incrementing/Decrementing Operators
6. Logical Operators
7. String Operators
8. Array Operators
9. Type Operators
10. Execution Operators
Arithmetic Operators
• The PHP arithmetic operators are used to perform common arithmetic
operations such as addition, subtraction, etc. with numeric values.
Assignment Operators
• The assignment operators are used to assign value to different
variables. The basic assignment operator is "=".
Bitwise Operators
• The bitwise operators are used to perform bit-level operations on
operands. These operators allow the evaluation and manipulation of
specific bits within the integer.
Comparison Operators
• Comparison operators allow comparing two values, such as number or
string. Below the list of comparison operators are given:
Incrementing/Decrementing Operators
• The increment and decrement operators are used to increase and
decrease the value of a variable.
Logical Operators
• The logical operators are used to perform bit-level operations on
operands.
• These operators allow the evaluation and manipulation of specific bits
within the integer.
PHP Form Handling
• We can create and use forms in PHP. To get form data, we need to use
PHP super global $_GET and $_POST. The form request may be get
or post.
• To retrieve data from get request, we need to use $_GET, for post
request $_POST.
PHP Get Form
• Get request is the default form request. The data passed through get
request is visible on the URL browser so it is not secured.
• You can send limited amount of data through get request. Let's see a
simple example to receive data from get request in PHP.
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"];//receiving name field value in $name variable
echo "Welcome, $name";
?>
PHP Post Form
• Post request is widely used to submit form that have large amount of
data such as file upload, image upload, login form, registration form
etc.
• The data passed through post request is not visible on the URL
browser so it is secured. You can send large amount of data through
post request.
• Let's see a simple example to receive data from post request in PHP.
form1.html
<html>
<head> <title> Post Method </title>
</head>
<body>
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form> </body> </html>
File: login.php
<?php
$name=$_POST["name"];
$password=$_POST["password"];
echo "Welcome: $name, your password is: $password";
?>
Write a php code to enter your name and
display it.
<html>
<head>
<title> Your name </title>
</head>
<body>
<B> Enter your Name</B> <br/>
<form method="POST">
<input type="text" name="name"/> <br/>
<input type="submit" value="submit"/>
</form>
<?php
$name=$_POST['name'];
echo "Your Name=$name";
?>
</body> </html>
Write a php code to display the factorial of a
number given by user.
<html>
<head>
<title> Your name </title>
</head>
<body>
<B> Factorial Calculaiton</B> <br/>
<form method="POST">
Input a Number: <input type="Number" name="number"/> <br/>
<input type="submit" value="Calculate"/>
</form>
<?php
$n=$_POST['number'];
$fact=1;
for($i=1; $i<=$n;$i++){
$fact=$fact*$i;
}
echo "The factorial of $n=$fact";
?>
</body> </html>
Database Connectivity
• Database: To organize the data in systematic and manageable form, the database is
required. The database is the system where data and information are stored and organized
systematically.
• The stored data can be retrieved easily when required.
• Data are stored in tabular form.
• The number of columns and rows forms the table. The column of the table is known as a
field that has a unique field name and the row of the table is known as records which
represent individual information. Each table has a unique field known as a primary key.
Each of the records of the primary field is different which make distinct from other
records for identification.
• MySQL is the most popular database system used with PHP. With PHP, we can connect to
and manipulate MYSQL databases. It is a database system used on the web that runs on a
server. It can be used for organized databases for both small and large applications. It is
comparatively more fast, reliable, and easy to use than other databases. It uses standard
SQL and compiles on a number of platforms.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "abc"; //
// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Database connection failed: " . $conn->connect_error);
}

echo "Connected successfully";


?>

You might also like