UNIT 3 Web Technology II
UNIT 3 Web Technology II
com
Computer Science
Grade: XII
Web technology II
Reference Note
NEB Important Questions for Computer Science XII
Unit 3- Web Technology II
1. What is web technology? Explain different data types used in JavaScript.
2. Differentiate between client side scripting and Server-side scripting.
3. What is event handling in JavaScript? Give one example.
4. What is JQuery? Write its features and Write a program to displaying a message "Hello Class 12" using JQuery.
5. What is JavaScript? How can you add JavaScript to an HTML page? Describe with example.
6. What is jQuery? Write its features.
7. What is Java Script function? Explain with calling function examples.
8. What is PHP? Write the advantages of PHP.
9. Explain the different operators used in PHP.
10. What are the features of PHP? Write a PHP program to display the largest among three numbers.
11. Define SQL? Write down the SQL queries to create a database, create a table in the database, insert data in the table,
and query the data to display it.
12. Write down the server side script to create a database, connect with it, create a table and insert data in it.
Practical Programs
1. Write a java Script to display 1 to 10 using for loop, while loop and do while loop.
2. Create a Page with a button with value "Computer" on clicking the button your page should" Computer Science".
3. Write a JavaScript program to display "Welcome Class-12" using onload event.
4. Design a form with username, address, e-mail, password and submit button. Validated the form using jQuery.
5. Design a form with username and password and submit button. Write a PHP code to get value of username and
password using a) $_POST variable and b) $_GET variable.
6. Write a PHP program to check if a string is a palindrome or not.
7. Write a Java Script program to calculate the factorial of a given number.
8. Write a java script program to input three number and find largest one using java and PHP.
Web technology
Introduction
Web Technology is the tools and techniques which enables two or more computing devices to
communicate over a network i.e. Internet.
Web Technology consist of two words, the web refers to the World Wide Web generally known as World
Wide Web.
WWW is the cyber space containing webpages, documents, and any other resources which are identified
and located with the help of their URLs.
Technology refers to the tools and techniques that makes these resources available on the Web such as,
web browsers to view content of web, Programming languages and frameworks for the development of
websites, Database to store data at back end, protocols for communicating on the web, multimedia
elements etc.
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.
Frontend Backend
Client Side Server Side
Website Design Database
HTML PHP
CSS Java
JavaScript Python
AJAX Ruby
UI/UX Servers
Some UI technologies Some Backend technologies
Ruby .NET
Scripting Language:
JavaScript is a scripting language. A scripting language is a lightweight programming language.
JavaScript code can be inserted into any HTML page, and it can be executed by all types of web
browsers.
JavaScript is used to make web pages interactive. It runs on your visitor's computer and doesn't
require constant downloads from your website. JavaScript and Java are completely different
language, both in concept and design.
Unlike HTML, JavaScript is case sensitive-therefore watch your capitalization closely when you write
JavaScript statements, create or call variables, objects and functions.
A scripting language is a programming language designed for integrating and communicating with other
programming language. It is used in server side as well as client side. Some of the most widely used
scripting language are JavaScript, VBScript, PHP, Perl, Python, Ruby etc.
Website: www.bkbhusal.com.np 2 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
1. Python: Python is a very popular and demanding programming language now because it is suitable
for developing very simple to complex applications. It is also used to connect database systems.
Python has simple English like syntax.
2. Perl: Practical Extraction and Reporting Language, first released in 1987 is a powerful language
with advance features. Perl is a stable, cross platform programming language. It is a general-
purpose programming language originally developed for text manipulation and now used for a
wide range of tasks including system administration, web development, network programming,
GUI development, and more.
3. Ruby: Ruby is a dynamic, open source programming language with a focus on simplicity and
productivity. It has an elegant syntax that is natural to read and easy to write.
4. Bash: A Bash script is a plain text file which contains a series of commands. It is widely available on
various operating systems and is a default command interpreter on most GNU/Linux systems.
5. Node.js: Node.js is used to create dynamic page contents. It can create, open, read, write, delete,
and close file on the server.
6. ASP.net: It is used to develop dynamic websites, web applications, and web services. ASP.NET is a
web application framework developed and marketed by Microsoft to allow programmers to build
dynamic web sites.
7. VBScript: Visual Basic Script (VBScript) is an open source web programming language developed
by Microsoft. It is superset of JavaScript and adds optional static typing class based object oriented
programming VBScript is lightweight scripting language. As VBScript is only used by IE browsers
JavaScript is preferred over VBScript.
8. JavaScript: JavaScript is most well-known and widely used scripting language for web pages. All
java script files are stored in file having is extension. JavaScript and Java programming language
are two different things: JavaScript is generally used for making websites interactive and dynamic.
Website: www.bkbhusal.com.np 3 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
9. jQuery: JQuery is a JavaScript library that simplifies writing code and enables rapid web
development. JQuery simplifies HTML document traversing and manipulation, and browser event
handling. The main concept of jQuery is "write less, do more".
10. PHP: Hypertext Preprocessor (PHP) is widely used scripting language. PHP scripts are executed on
the server. It is used to manage dynamic content, databases, session tracking and building e-
commerce sites. It is integrated with a popular database MySQL.
Client-side scripting is performed to generate a code that can run on the client side i.e (front end) browser
without needing the server-side (back end) processing. Basically, client-side scripts are placed inside an
HTML document.
The client-side scripting can be used to layout the content of the web. For example, when a user makes a
request through web browser for a webpage to the server, it just sent the HTML and CSS as plain text, and
the browser interprets and renders the content of web in the client end (user).
Client-side scripting is designed to run as a scripting language which can be executed by web browser.
Front end developer is someone who design and develop client side of a website. Generally he or she
works in user interface (UI) of a website. Front end developer must be at least fluent in three different
languages i.e. HTML, CSS, JavaScript whereas, there are several other libraries which can be used for front
end development.
Server-side scripting also known as back-end runs on the server where the application is hosted. Server-
side is used to serve content depending upon the user request. Back end helps to create dynamic web
based application that allows user to interact and communicate with the application. Back end language
also helps to connect front end with data base. So that, User can store and retrieve data as per the
requirement. Back-end developer is responsible for server-side programming. Some of the popular
server-side (back-end) scripting language are ASP, JavaScript (using SSJS (Server-side JavaScript e.g.
node.js), Perl, PHP, Ruby, Python etc.
The client-side scripting emphasizes making the interface of the web application or website (UI) more
appealing and functional. Whereas, server-side scripting emphasizes on data accessing methods, error
handling and fast processing etc.
Advantages
1) You can create dynamic pages.
2) Can connect to database that resides on the web server.
3) Can access files from the server to client browser Users are not able to block the contents from
server
4) The actual code is not visible to the client
5) Authentication and verification of user is possible
6) It supports many databases like MySQL Oracle,
7) Efficient storage and delivery of information
8) Customized user experience.
9) Controlled access to content
10) Notification and communication
11) Users do not need to download plug-in like java or flash
12) The content management system (CMS) makes editing simpler
Note: Full-stack developer understand both Front end and back end development process. They can
accomplish entire project. Full stack developer must have expertise in client site and server site Scripting
language. Moreover, he/she has a great knowledge of integrating database with the application.
<html>
<head>
<title> Inline javascript Example</title>
<body>
<form>
<center><input type="button" value="ClickMe" onclick="alert('Button Clicked: ')">
</center></form>
</body>
</html>
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.
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
There are different languages used to create dynamic web pages like PHP, ASP, .NET and JSP.
Whenever a dynamic page loads in browser, it requests the database to give information depending
upon user’s input. On receiving information from the database, the resulting web page is applied to
the user after applying the styling codes.
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 and cross-platform.
This tutorial has been prepared for JavaScript beginners to help them understand the basic functionality
of JavaScript to build dynamic web pages and web applications.
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.
<script>
document.write("Hello JavaScript by JavaScript");
</script>
Advantages of JavaScript
1. 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.
2. Easy to learn: By learning few commands and simple rules of syntax, you can easily build
applications using JavaScript.
3. Immediate feedback to the visitors: They don't have to wait for a page reload to see if they have
forgotten to enter something.
4. Increased interactivity: You can create interfaces that react when the user hovers over them with
a mouse or activates them via the keyboard.
5. Quick Development: Scripts can be developed in short period of time
6. 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.
7. 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.
8. Easy Debugging and Testing: As JavaScript is interpreted line by line, it is easy to find error and
make changes.
9. Interactive content, for example games, and playing audio and video.
10. 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.
1. Embedding code:-
To add the JavaScript code into the HTML pages, we can use the <script>.....</script> tag of the HTML that
wrap around JavaScript code inside the HTML program. Users can also define JavaScript code in
the <body> 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>
We can also define the JavaScript code in the <body> tags or body section.
Let's understand through an example.
<html>
<head>
<title> Body Section Example</title> </head>
<body>
<script>
document.write("Welcome to Javatpoint");
</script>
<p> In this example we saw how to add JavaScript in the body section </p>
</body>
</html>
2. 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 <script>.... </script> tag.
Let's look at the example.
<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>
Website: www.bkbhusal.com.np 11 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
3. 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>
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
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>
2. 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>
3. 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.
<html>
<head> <title>Display functions in Javascript </title>
</head>
<body>
<h1> Demo of console.log</h1> <br>
<script>
Console.log("Gurukul College");
Console.log("7+5");
</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.
Abstract Else instance of Switch
boolean enum int synchronized
break export interface this
byte extends long throw
Case False Native Throws
Catch Final New transient
Char Finally Null True
Class Float Package Try
Const For Private Type of
Continue Function Protected Var
Debugger Go to Public Void
Default If Return Volatile
Delete Implements Short While
Do Import Static With
Double In Super
JavaScript Variable
1. JavaScript Local variable
2. JavaScript Global 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.
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
Let’s see a simple 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. 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
7. Unary Operator
8. String Operator
9. Conditional Operator
Examples
<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>
<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>
<html>
<body>
<h1>JavaScript Arithmetic</h1>
<h2>The += Operator</h2>
<script>
var x = 10;
x += 5;
document.write(x);
</script>
</body>
</html>
Operator Description
1) (?:) Conditional Operator returns value based on the condition. It is like if-else.
2) , Comma Operator allows multiple expressions to be evaluated as single
statement.
3) Delete Delete Operator deletes a property from the object.
4) In In Operator checks if object has the given property
5) Instanceof checks if the object is an instance of given type
6) new creates an instance (object)
7) typeof checks the type of object.
8) Void it discards the expression's return value.
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 and 20.
Control Structures
1. If-else
2. switch case
3. for loop
4. while loop
5. do while loop
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.
if(expression)
{
//content to be evaluated
}
<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>
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
}
<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>
Let’s see the example of if-else statement in JavaScript to find out the even or odd number.
<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>
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
}
Let’s see the simple example of if else if statement in JavaScript.
<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>
Website: www.bkbhusal.com.np 25 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
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>
JavaScript Switch
The JavaScript switch statement 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.
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");
break;
case(n="3");
document.write("The day is Tuesday");
Website: www.bkbhusal.com.np 27 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
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>
</script>
</head>
</html>
Output: 12345
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>
Or
<html>
<head>
<title> To find out sum of Given two numbers </title>
<script type="text/JavaScript">
function add()
{
var a,b,c;
a=Number(document.getElementaryById("first").value);
b=Number(document.getElementaryById("second").value);
c=a+b;
document.getElementaryById("answer").value=c;
}
</script>
</head>
<body>
Enter the First Numebr: <input id="first"> <br>
Enter the Second Number: <input id="second"> <br> <hr>
<button onclick="add()"> Addition </button>
<input id="answer">
</body>
</html>
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
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.
object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon). Let’s see the simple example of creating object
in JavaScript.
<html>
<body>
<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>
<p id="demo"></p>
<script>
const person = {firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"};
</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>
In the above example, method is defined as move. The method can be accessed easily using
object name period and method name.
Let's see the simple example of document object that prints name with welcome message.
<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.
Example
<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>
In the example above, getElementById is a method, while innerHTML is a property.
Let's see the simple example of document.getElementById() method that prints cube of the given
number.
<script>
function getcube()
{
var n=document.getElementById("number").value;
alert(n*n*n);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Website: www.bkbhusal.com.np 35 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
2. 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.
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using getElementsByName()
method to get all the genders.
<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">
<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>
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.
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:
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 & Keyup onkeydown & onkeyup When the user press and then release 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
Let's discuss some examples over events and their handlers.
Click Event
<html>
<head> Javascript Events </head>
<body>
<script>
function clickevent()
{
document.write("This is Java Click Events");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Click To View"/>
</form>
Website: www.bkbhusal.com.np 38 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
</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>
Website: www.bkbhusal.com.np 39 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
document.write("The page is loaded successfully");
</script>
</body>
</html>
Image Object
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.
<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>
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
Number Validation
Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<script>
function validate()
{
var num=document.myform.num.value;
if (isNaN(num))
{
document.getElementById("numloc").innerHTML="Enter Numeric value only";
Website: www.bkbhusal.com.np 41 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
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>
JavaScript validation with image
Let’s see an interactive JavaScript form validation example that displays correct and incorrect
image if input is correct or incorrect.
<script>
function validate()
{
var name=document.f1.name.value;
var password=document.f1.password.value;
var status=false;
if(name.length<1)
{
document.getElementById("nameloc").innerHTML=
" <img src='unchecked.gif'/> Please enter your name";
status=false;
}
Else
{
document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
status=true;
}
if(password.length<6)
{
document.getElementById("passwordloc").innerHTML=
" <img src='unchecked.gif'/> Password must be at least 6 char long";
status=false;
}
Else
{
document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";
}
return status;
}
</script>
<form name="f1" action="#" onsubmit="return validate()">
<table>
<tr><td>Enter Name:</td><td><input type="text" name="name"/>
<span id="nameloc"></span></td></tr>
<tr><td>Enter Password:</td><td><input type="password" name="password"
/>
<span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>
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:
<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>
JavaScript Programs
1. This program adds 5 numbers and writes the answer as an HTML output.
<!doctype html>
<html> <body>
<script>
var i, n=5, sum=0; arr = new Array(1, 2, 3, 5, 9);
for(i=0; i<5; i++)
sum = sum + arr[i]; document.write(sum);
</script></body></html>
2. JavaScript program to check whether a number is a prime number or not. This program does
not take input from user.
<!doctype html>
<html>
<body> <script>
var num, i, c=0;
num=9;
for(i=2; i<num; i++)
{
if(num%2==0)
{
C++;
break;
}
}
if(c==0)
document.write(num+" is a Prime Number");
else
document.write(num+" is not a Prime Number");
</script> </body>
</html>
<html>
<body>
<script>
function myFormValidate ( )
{
var name = document.myform.name.value; var password =
document.myform.password.value;
if (name==null || name=="")
{
alert("Please, Enter Name");
return false;
}
else if (password.length < 5)
{
alert ("Password must be at least 5 characters long.");
return false;
}
}
</script>
<body>
<form name = "myform" method = "post" action = "abc.php" onsubmit = "return myFormValidate ( )" >
Name: <input type = "text" name = "name"><br/>
Password: <input type = "password" name = "password"><br/>
<input type = "submit" value = "Login">
</form>
</body>
</html>
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:
Some of important feature of jQuery are listed as follows:
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.
Website: www.bkbhusal.com.np 45 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
1. Simple 1. Simplicity
2. Interpreted 2. Efficiency
3. Faster 3. Security
4. Open Source 4. Flexibility
5. Platform Independent 5. Familiarity
6. Case Sensitive
7. Error Reporting Advantages of PHP / what problem does it
8. Real-Time Access Monitoring solve.
9. Loosely Typed Language 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
Introduction to PHP:
PHP is an open-source, interpreted, and object-oriented scripting language that can be executed at the
server-side. PHP is well suited for web development. Therefore, it is used to develop web applications (an
application that executes on the server and generates the dynamic page.).
Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript. So, learn these
technologies for better implementation of PHP.
CSS - CSS helps to make the webpage content more effective and attractive.
PHP is widely used in web development nowadays. PHP can develop dynamic websites easily. But you
must have the basic the knowledge of following technologies for web development as well.
1. HTML
2. CSS
3. JavaScript
4. Ajax
5. XML and JSON
6. jQuery
PHP is a server-side scripting language, which is used to design the dynamic web applications with MySQL
database.
1. It handles dynamic content, database as well as session tracking for the website.
2. You can create sessions in PHP.
3. It can access cookies variable and also set cookies.
4. It helps to encrypt the data and apply validation.
5. PHP supports several protocols such as HTTP (Hypertext Transfer Protocol), POP3 (Post office
Protocol-3), SNMP (Simple Network Management Protocol), LDAP (Lightweight Directory Access
Protocol), IMAP (Internet Message Access Protocol), and many more.
6. Using PHP language, you can control the user to access some pages of your website.
7. As PHP is easy to install and set up, this is the main reason why PHP is the best language to learn.
8. PHP can handle the forms, such as - collect the data from users using forms, save it into the
database, and return useful information to the user. For example - Registration form.
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.
5. This is mostly due to updates, which add features that clash with earlier features,
6. PHP is an interpreted language, which can reduce speed.
7. PHP 7 increased performance over previous versions by a significant amount while maintaining
most language compatibility.
8. The changes didn't affect the learning curve or existing applications much while improving
performance. Still, it executes more slowly than compiled languages.
9. Scaling and maintaining PHP is a complicated endeavor.
10. Context matters a great deal in dynamically typed languages, so tracking down errors gets harder
the larger an application grows.
11. Experienced PHP developers can mitigate this problem y planning for scalability, but there's only
so much they can do to reduce maintenance issues down the road.
1. Encapsulation: This is concerned with hiding the implementation details and only exposing the
methods. It used to reduce software development complexity.
2. Inheritance: This is concerned with the relationship between classes. The main purpose of inheritance
is the re-usability.
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.
PHP in Object oriented programming PHP is an object oriented scripting language. It supports all of the
above principles. The above principles are achieved via:
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.
<?php
echo "Hello Class 12";
?>
</body>
</html>
<?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 multi-
line 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
</body>
</html>
<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).
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
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
<?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;
?>
o echo
o 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."; <br> <hr>
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:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o 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.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Output:
Decimal number: 34
Octal number: 163
Hexadecimal number: 69
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.
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 73.812
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:
Example:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
Output:
Hello Javatpoint
Hello $company
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
<?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>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be
explicitly declared.
Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
Bike Model: Royal Enfield
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 Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters
as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
<?php
$n = NULL;
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.
Operator Name Example Explanation
+ Addition $a + $b Sum of operands
- Subtraction $a - $b Difference of operands
* Multiplication $a * $b Product of operands
/ Division $a / $b Quotient of operands
% Modulus $a % $b Remainder of operands
** Exponentiation $a ** $b $a raised to the power $b
Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator
is "=".
Operator Name Example Explanation
= Assign $a = $b The value of right operand is
assigned to the left operand.
+= Add then Assign $a += $b Addition same as $a = $a + $b
-= Subtract then Assign $a -= $b Subtraction same as $a = $a - $b
*= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b
/= Divide then Assign $a /= $b Find quotient same as $a = $a / $b
(quotient)
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.
Operator Name Example Explanation
& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.
| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1
^ Xor (Exclusive or) $a ^ $b Bits that are 1 in either $a or $b are set to 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:
Operator Name Example Explanation
== Equal $a == $b Return TRUE if $a is equal to $b
=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same
data type
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not
of same data type
!= Not equal $a != $b Return TRUE if $a is not equal to $b
<> Not equal $a <> $b Return TRUE if $a is not equal to $b
< Less than $a < $b Return TRUE if $a is less than $b
> Greater than $a > $b Return TRUE if $a is greater than $b
<= Less than or $a <= $b Return TRUE if $a is less than or equal $b
equal to
>= Greater than $a >= $b Return TRUE if $a is greater than or equal $b
or equal to
<=> Spaceship $a <=>$b Return -1 if $a is less than $b
Return 0 if $a is equal $b
Return 1 if $a is greater than $b
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.
Operator Name Example Explanation
++ Increment ++$a Increment the value of $a by one, then return $a
$a++ Return $a, then increment the value of $a by one
-- Decrement --$a Decrement the value of $a by one, then return $a
$a-- Return $a, then decrement the value of $a by one
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.
Operator Name Example Explanation
And And $a and $b Return TRUE if both $a and $b are true
Or Or $a or $b Return TRUE if either $a or $b is true
Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
! Not ! $a Return TRUE if $a is not true
&& And $a && $b Return TRUE if either $a and $b are true
|| Or $a || $b Return TRUE if either $a or $b is true
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.
File: 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";
?>
PHP Programs
1. 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>
Website: www.bkbhusal.com.np 59 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
<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 = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Web References:
https://www.javatpoint.com
https://www.w3schools.com
https://www.tutorialspoint.com
https://www.google.com
https://www.wikipedia.org