You are on page 1of 45

Web Technology and its Applications

Unit - III

JavaScript is a very powerful client-side scripting language. JavaScript is used mainly


for enhancing the interaction of a user with the webpage. In other words, you can make
your webpage more lively and interactive, with the help of JavaScript. JavaScript is also
being used widely in game development and Mobile application development.

JavaScript was developed by Brendan Eich in 1995

JavaScript Vs Java

Java is a very complex programming language whereas JavaScript is only a scripting


language. The syntax of JavaScript is mostly influenced by the programming language C.

JavaScript is an object oriented and dynamically typed programming language having


similar syntactic structures of Java ( but different from it ) interpreted by a common
browser in existence without need for JVM

It is called strange object oriented programming language as it does not contain the class
and inheritance

Global Accessibility

● Being a scripting language, JavaScript cannot run on its own. In fact, the
browser is responsible for running JavaScript code.
● When a user requests an HTML page with JavaScript in it, the script is sent to the
browser and it is up to the browser to execute it.
● The main advantage of JavaScript is that all modern web browsers support
JavaScript.
● So, you do not have to worry whether your site visitor uses Internet Explorer,
Google Chrome, Firefox or any other browser. JavaScript will be supported.
● Also, JavaScript runs on any operating system including Windows, Linux or Mac.
Thus, JavaScript overcomes the main disadvantages of VBScript (Now deprecated)
which is limited to just IE and Windows.

What Is JavaScript and What Can It Do?

● Java, JavaScript and Java are vastly different programming languages with different
uses.

● Java is a full-fledged compiled, object-oriented language, popular for its ability to


run on any platform with a Java Virtual Machine installed.
● Conversely, JavaScript is one of the world’s most popular languages, with fewer of
the object-oriented features of Java, and runs directly inside the browser,
without the need for the JVM.

● JavaScript is object oriented in that almost everything in the language is an object.


For instance, variables are objects in that they have constructors, properties, and
methods .

● JavaScript is dynamically typed (also called weakly typed) in that variables can
be easily (or implicitly) converted from one data type to another.

● In a programming language such as Java, variables are statically typed, in that the
data type of a variable is defined by the programmer (e.g., int abc ) and enforced by
the compiler.

● With JavaScript, the type of data a variable can hold is assigned at runtime and
can change during run time as well.

Client-Side Scripting

The idea of client-side scripting is an important one in web development. It refers to the
client machine (i.e., the browser) running code locally rather than relying on the server to
execute code and return the result.

There are many client-side languages that have come into use over the past decade
including Flash, VBScript, Java, and JavaScript. Some of these technologies only work in
certain browsers, while others require plug-ins to function. We will focus on JavaScript due
to its browser interoperability (that is, its ability to work/operate on most browsers). Figure
6.1 illustrates how a client machine downloads and executes JavaScript code.
Refer to 6.2,6.3 and 6.4 also in text book

There are many advantages of client-side scripting:

● Processing can be offloaded from the server to client machines, thereby reducing
the load on the server.

● The browser can respond more rapidly to user events than a request to a
remote server ever could, which improves the user experience.

To run JavaScript using browser


<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
function first()
{
alert("Welcome!!! You are now learning JavaScript. I am
waiting");
}
</script>
</head>
<body>

<h1> I am html code<h1>


<input type=button onclick="first()" value="press me to execute JS"/>
</body>
</html>
Note: type="text/javascript" is not necessary in HTML5

Where Does JavaScript Go? (Types of JavaScript)

● JavaScript can be linked to an HTML page in a number of ways. Just as CSS styles
can be inline, embedded, or external, JavaScript can be included in a number of
ways.
● Just as with CSS these can be combined, but external is the preferred method for
cleanliness and ease of maintenance.

Inline JavaScript
Inline JavaScript refers to the practice of including JavaScript code directly within
certain HTML attributes as
<html>
<body>

<!-- inline javascript coding -->


<a href="#" onclick="alert('It is executed through inline javascript coding which is to be
avoided always')">Click Me</a>

</body>
</html>

o/p

Embedded JavaScript
<html>
<head>

<script>
function msg() {
alert("I am executed through embedded javascript. I am a formal way ");
}
</script>
</head>
<body>

<!-- embedded javascript coding -->

<input type="button" value="Click me" onclick="msg()">

</body>
</html>

o/p

External JavaScript
It is often advantageous to separate the two into different files.

<!DOCTYPE html>
<html>
<head>
<script src="myscript.js"></script>
</head>
<body>
<h2>External JavaScript</h2>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>

myscript.js file content

function myFunction()
{
alert("Hi!, I am exectuted from external file.");
}

o/p

Syntax in JavaScript

(variables, assignment, conditionals, loops, and arrays)

Using Variables in Javascript


Variables are used to store values (name = "John") or expressions (sum = x + y).
Before using a variable, you first need to declare it. You have to use the keyword
var to declare a variable like this:

var name;

<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br
/>");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>

o/p

for loop
<html>
<head>
<script type="text/javascript">
function looping()
{
document.write("<h1>I am javascript</h1>");
var students = new Array("John", "Ann", "Aaron", "Edwin",
"Elizabeth");
document.write("<b>Using for loops </b><br />");
for (i=0;i<students.length;i++)
{
document.write((i+1)+" "+students[i] + "<br />");
}
}
</script>
</head>
<body>
<h1>I am html body</h1>
<input type=button onclick=looping() value="press me to show arrays">
</body>
</html>

o/p
Conditionals

if... else if

<html>
<head>
<script type="text/javascript">
function great2()
{
var one = prompt("Enter the first number");
var two = prompt("Enter the second number");
one = parseInt(one);
two = parseInt(two);
if (one == two)
document.write(one + " is equal to " + two + ".");
else if (one<two)
document.write(one+ " is less than " + two + ".");
else
document.write(one + " is greater than " + two + ".");

}
</script>
</head>
<body>
<h1>Finding greater of two numbers using javascript</h1>
<input type=button onclick=great2() value="press me to find the greater of two numbers">
</body>
</html>

o/p
if inputs are 5 and 3, output is

5 is greater than 3

vowel.html

<<html>
<head>
<script>
function vowel()
{
var count = 0;
function countVowels(name)
{
for (var i=0;i<name.length;i++)
{
if(name[i].toLowerCase() == "a" || name[i].toLowerCase() == "e" ||
name[i].toLowerCase() == "i" || name[i].toLowerCase() == "o" || name[i].toLowerCase() ==
"u")
count = count + 1;
}
document.write("Hello," + name + "!!! Your name has " + count + " vowels.");
}
var myName = prompt("Please enter your name");
countVowels(myName);
}
</script>
</head>
<body>

<h1>Finding the number of vowels in a sentence using javascript</h1>


<input type=button onclick=vowel() value="press me to find the number of vowels in a
sentence">
</body>
</html>

Variables :
● Variables in JavaScript are dynamically typed, meaning a variable can be an
integer, float, and a string or an object. The data type of the variables is decided
during the execution time.

● This simplifies variable declarations, so that we do not require the familiar type
fields like int, char, and String.

● Assignment can happen at declaration-time by appending the value to the


declaration, or at run time with a simple right-to-left assignment

● This syntax should be familiar to those who have programmed in languages like C
and Java.

Comparison Operators

Logical Operators

JavaScript includes Boolean operators, which allow us to build complicated expres-


sions. The Boolean operators and , or , and not and their truth tables are listed in
Table 6.2. Syntactically they are represented with && (and), || (or), and ! (not).
Conditionals
JavaScript’s syntax is almost identical to that of PHP, Java, or C when it comes to
conditional structures such as if and if else statements.

Write an example javascript here using if and if...else

<body>

<p>Click the button to get a time-based greeting:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var greeting;
var time = new Date().getHours();
if (time < 10) {
greeting = "Good morning";
} else if (time < 15) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
}
</script>

</body>
</html>

o/p

Loops

While Loops
The most basic loop is the while loop, which loops until the condition is not met.

var i=0;
while(i < 10){
//do something with i
i++;
}

For Loops
A for loop combines the common components of a loop: initialization, condition,
and post-loop operation into one statement.

for (var i = 0; i < 10; i++){


//do something with i
}

Functions

Functions are the building block for modular code in JavaScript,

They are defined by using the reserved word function and then the function name and
(optional) parameters.

Since JavaScript is dynamically typed, functions do not require a return type, nor do the
parameters require type.
Therefore a function to raise x to the yth power might be defined as:

function power(x,y){
var pow=1;
for (var i=0;i<y;i++){
pow = pow*x;
}
return pow;
}

And it can be called as


power(2,10);

Alert

The alert() function makes the browser show a pop-up to the user, with whatever
is passed being the message displayed. The following JavaScript code displays a
simple hello world message in a pop-up:
alert ( "Good Morning" );

What is a DOM ?

JavaScript is almost always used to interact with the HTML document in which it is
contained. As such, there needs to be some way of programmatically accessing the
elements and attributes within the HTML. This is accomplished through a programming
interface (API) called the Document Object Model(DOM).
Document Object Model (DOM)
According to the W3C, the DOM is a:

Platform-and language-neutral interface that will allow programs and scripts to


dynamically access and update the content, structure and style of documents.

JavaScript can access all the elements in a webpage making use of Document Object
Model (DOM). In fact, the web browser creates a DOM of the webpage when the page is
loaded. The DOM model is created as a tree of objects like this:

DOM tree
Nodes

In the DOM, each element within the HTML document is called a node. If the DOM is a
tree, then each node is an individual branch. There are element nodes, text nodes, and
attribute nodes, as shown in Figure 6.18

Common Methods and Properties

1 getElementById( ) : To access elements and attributes whose id is set.

2 innerHTML: To access the content of an element.

3 getElementsByTagName: To access elements and attributes using tag name. This


method will return an array of all the items with the same tag name.

4 CreateElement: To create new element

5. removeChild: Remove an element

DOM1-(Identifying text through getElementById())

<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1 id="one">Welcome</h1>

<p>This is the example of getElementById() .</p>


<h2>Technology</h2>
<p id="second">This is the technology section.</p>

<script type="text/javascript">

var text = document.getElementById("one").innerHTML;


alert("The first heading is " + text);

var text1 = document.getElementById("second").innerHTML;


alert("The second heading is " + text1);
</script>
</body>
</html>

o/p
DOM2-[(Identifying paragraphs through getElementsByTagName(“p”)]

<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1>This is getElementByTagName for accessing paragraphs</h1>
<p>Welcome to the first paragraph section</p>
<h2> This the second paragraph</h2>
<p id="second">This is the second paragraph section</p>

<script type="text/javascript">
var paragraphs = document.getElementsByTagName("p");
alert("Content in the FIRST paragraph is " + paragraphs[0].innerHTML);
alert("Content in the SECOND paragraph is " + paragraphs[1].innerHTML);
document.getElementById("second").innerHTML = "The orginal message of second
paragraph is changed.";
</script>

</body>
</html>

o/p
DOM3( program for addEventListener without using onclick in input tag)

<html>
<head>
<title>DOM3 !!!</title>
</head>
<body>
<h3> This is an example program for addEventListener without using onclick in input
tag</h3>
<input type="button" id="btnClick" value="Click Me!!" />
<script type="text/javascript">
document.getElementById("btnClick").addEventListener("click", clicked);
function clicked()
{
alert("You clicked me. I have activated through addEventListener method!!!");
}
</script>
</body>
</html>
o/p

Three events(mouseover, mouseout, doubleclick)

<!DOCTYPE html>
<html>

<body>
<button id="clickIt">Click here</button>

<p id="hoverPara">Hover over this Text !</p>

<b id="effect"></b>

<script>
const x = document.getElementById("clickIt");
const y = document.getElementById("hoverPara");

x.addEventListener("dblclick", RespondClick);
y.addEventListener("mouseover", RespondMouseOver);
y.addEventListener("mouseout", RespondMouseOut);

function RespondMouseOver() {
document.getElementById("effect").innerHTML +=
"MouseOver Event" + "<br>";
}

function RespondMouseOut() {
document.getElementById("effect").innerHTML +=
"MouseOut Event" + "<br>";
}

function RespondClick() {
document.getElementById("effect").innerHTML +=
"Click Event" + "<br>";
}
</script>
</body>

</html>

o/p

Four Events (onkeydown, ondblclick,


onmousedown, onmouseup)

<html>
<body>
<p>Click the button to display the date.</p>
<table>
<tr><td>Press a key in the keyboard </td><td><button onkeydown="displayDate()">The
time is?</button></td></tr>
<tr><td>Double Click the mouse button</td> <td><button ondblclick="displayDate()">The
time is?</button></td></tr>
<tr><td>Move mouse down button</td><td><button onmousedown="displayDate()">The
time is?</button></td></tr>
<tr><td>Move mouse up button</td><td><button onmouseup="displayDate()">The time
is?</button></td></tr>
</table>

<script>
function displayDate() {
document.getElementById("demo").innerHTML += Date()+"<br>";
}
</script>

<br>current date and time is <p id="demo"></p>


</body>
</html>

o/p
​JavaScript Forms
Validation of forms

Name validation

<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>

<form name="myForm" action="https://www.w3schools.com/action_page.php"


onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

o/p

Address validation

<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["add1"].value;
var z = document.forms["myForm"]["add2"].value;
var l = document.forms["myForm"]["city"].value;
if (x == "" || y=="" || z=="" || l=="") {
alert("All data must be filled out");
return false;
}
else
alert("Congratulations! you have entered all the data intact");

}
</script>
</head>
<body>

<form name="myForm" action="" onsubmit="return validateForm()" method="post">


<table>
</br><tr><td>Name :</td> <td><input type="text" name="fname"></td> </tr>
</br><tr><td>Address :</td><td> <input type="text" name="add1"></td></tr>
</br><tr><td>Locality:</td> <td><input type="text" name="add2"></td></tr>
</br><tr><td>City :</td> <td><input type="text" name="city"></td></tr>
</br>
</br>
</br><tr> <td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>

</body>
o/p

Manual validation using javascript

<html>
<body>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100" max="300" required>


<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 or greater than 300, an error message will be
displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
</body>

o/p

​Automatic HTML Form Validation


<form action="" method="post">

<h3> Automatic Form Validation using javascript </h3>


<table>
<tr><td>Name :</td> <td><input type="text" name="fname" required></td> </tr>
<tr><td>Address :</td><td> <input type="text" name="add1" required></td></tr>
<tr><td>Locality:</td> <td><input type="text" name="add2"></td></tr>
<tr><td>City :</td> <td><input type="text" name="city" required></td></tr>
<tr> <td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>

o/p
JavaScript design principles.

These principles increase the quality and reusability of the code while making it easier to
understand, and hence more maintainable.

Layers

● When designing software to solve a problem, it is often helpful to abstract the


solution a little bit to help build a cognitive model in your mind that you can then
implement.

● Perhaps the most common way of articulating such a cognitive model is via the
term layer. In object-oriented programming, a software layer is a way of
conceptually grouping programming classes that have similar functionality and
dependencies

Common software design layer names include:


Presentation Layer

● It focuses on the display of information.


● JavaScript can alter the HTML of a page, which results in a change, visible to the
user.
● These presentation layer applications include common things like creating, hiding,
and showing divs, using tabs to show multiple views, or having arrows to page
through result sets.
● This layer is most closely related to the user experience and the most visible to the
end user.

Validation Layer

JavaScript can be also used to validate logical aspects of the user’s experience.

This could include, for example, validating a form to make sure the email entered is valid
before sending it along. It is often used in conjunction with the presentation layer

Asynchronous Layers
Normally, JavaScript operates in a synchronous manner where a request sent to the
server requires a response before the next lines of code can be executed. During the wait
between request and response the browser sits in a loading state and only updates
upon receiving the response.

In contrast, an asynchronous layer can route requests to the server in the background. In
this model, as certain events are triggered, the JavaScript sends the HTTP requests to the
server, but while waiting for the response, the rest of the application functions normally,
and the browser isn’t in a loading state.

When the response arrives JavaScript will (perhaps) update a portion of the page.
Asynchronous layers are considered advanced versions of the presentation and validation
layers above.

Errors Using Try and Catch

When the browser’s JavaScript engine encounters an error, it will throw an exception.
These exceptions interrupt the regular, sequential execution of the program and can stop
the JavaScript engine altogether. However, you can optionally catch these errors
preventing disruption of the program using the try–catch block as

try {
nonexistantfunction("hello");
}
catch(err) {
alert("An exception was caught:" + err);
}

JavaScript Objects

JavaScript is not a full-fledged object-oriented programming language. it does not support


many of the patterns
The language does, however, support objects. Objects can have constructors, properties,
and methods associated with them, and are used very much like objects in other
object-oriented languages. There are
objects that are included in the JavaScript language; you can also define your own kind of
objects.

Objects Included in JavaScript : A number of useful objects are included with


JavaScript. These include Array ,Boolean, Date, Math and String

Array example
var greetings = new Array();

To initialize the array with values, the variable declaration would look like the
following:

var greetings = new Array("Good Morning", "Good Afternoon");

or, using the square bracket notation:

var greetings = ["Good Morning", "Good Afternoon"];

Math

The Math class allows one to access common mathematic functions and common values
quickly in one place. This static class contains methods such as max() , min() , pow() ,
sqrt() , and exp() , and trigonometric functions such as sin() , cos() , and arctan() .

Math.PI
Math.sqrt(4);
Math.random();
// 3.141592657
// square root of 4 is 2.
// random number between 0 and 1

String

While one can use the new syntax to create a String object , it can also be defined using
quotes as follows:

var greet = new String("Good"); // long form constructor


var greet = "Good"; // shortcut constructor

Date

To display today’s date as a string, we would simply create a new object and use the
toString() method.

var d = new Date();


// This outputs Today is Mon Oct 12 2018 15:40:19
alert ("Today is "+ d.toString());
getElementById, innerHTML Example

<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1 id="one">Welcome</h1>
<p>This is the welcome message.</p>

<script type="text/javascript">
var text = document.getElementById("one").innerHTML;
alert("The first heading is " + text);
</script>
</body>
</html>

o/p
5 Welcome
This is the welcome message

getElementsByTagName:  To access elements and attributes whose name is set.

innerHTML: To access the content of an element.

<html>.
<head>
<title>DOM!!!</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is the welcome message.</p>
<p >This is the technology section.</p>
<script type="text/javascript">
var paragraphs = document.getElementsByTagName("p");
alert("Content in the second paragraph is " + paragraphs[1].innerHTML);
document.getElementById("second").innerHTML = "The orginal message is changed.";
</script>
</body>
</html>

Welcome
This is the welcome message.

5.1 Technology
This is the technology section.

JavaScript Events
The core of all JavaScript programming is the concept of an event.
A JavaScript event is an action that can be detected by JavaScript.
Many of them are initiated by user actions but some are generated by the browser itself.

Inline Event Handler Approach


JavaScript events allow the programmer to react to user interactions.
For example, if you wanted an alert to pop-up when clicking a < div > you might program:

<div id="example1" onclick="alert('hello')">Click for pop-up</div>

Listener Approach
The problem with the inline handler approach is that it does not make use of layers; that
is, it does not separate content from behavior.

<html>
<body>
<p>This example uses the addEventListener() method to execute a function when a user
clicks anywhere in the document.</p>
<p id="demo">
<script>
document.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
o/p

This example uses the addEventListener() method to execute a function when a user
clicks anywhere in the document.
Hello World

Event Types (Mouse Events and Keyboard Events) in Javascript

Mouse Events
Mouse events are defined to capture a range of interactions driven by the mouse. These
can be further categorized as mouse click and mouse move events. Table 6.7 lists the
possible events one can listen for from the mouse.

Example animation program for onmouseout and onmouseover

<html>
<body>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0"
src="rose.jpeg" alt="bouquet" width="32" height="32">
<p>The function bigImg() is triggered when the user moves the mouse pointer over the
image.</p>
<p>The function normalImg() is triggered when the mouse pointer is moved out of the
image.</p>
<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
}
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}
</script>
</body>
</html>

o/p

Keyboard Events
Keyboard events are often overlooked by novice web developers, but are important
tools for power users. Table 6.8 lists the possible keyboard events.

Example program onkeypress


<html>
<body>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" onkeypress="myFunction()">
<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>
</body>
</html>

o/p
onkeyup
<html>
<body>
<p>A function is triggered when the user releases a key in the input field. The function
transforms the character to upper case.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>

o/p

Form Events
Forms are the main means by which user input is collected and transmitted to the
server. Table 6.9 lists the different form events.

The events triggered by forms allow us to do some timely processing in response


to user input. The most common JavaScript listener for forms is the onsubmit event.
Onblur example program

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" onblur="myFunction()">

<p>When you leave the input field, a function is triggered which transforms the input text
to upper case.</p>

</body>
</html>

o/p

Onchange example program

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text
to upper case.</p>
</body>
</html>

Onfocus example program

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which changes the
background-color.</p>
</body>
</html>

o/p

Onreset example program

<!DOCTYPE html>
<html>
<head>
<script>
function message() {
alert("This alert box was triggered by the onreset event handler");
}
</script>
</head>
<body>
<form onreset="message()">
Enter your name: <input type="text" size="20">
<input type="reset">
</form>
</body>
</html>

o/p

Onselect example program


<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "You selected the text";
}
</script>
</head>
<body>
Some text: <input type="text" value="Hello world!" onselect="myFunction()">
<p id="demo"></p>
</body>
</html>

o/p
Onsubmit example program

<!DOCTYPE html>
<html>
<head>
<script>
function confirmInput() {
fname = document.forms[0].fname.value;
alert("Hello " + fname + "! You will now be redirected to www.aiet.org.in");
}
</script>
</head>
<body>
<form onsubmit="confirmInput()" action="https://www.aiet.org.in/">
Enter your name: <input id="fname" type="text" size="20">
<input type="submit">
</form>
</body>
</html>
o/p

Validation form example in JavaScript

Validate.html

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

</script>
</head>
<body>
<form name="myForm" action="vForm.html"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
vForm.html
<html>
<head>
<body>
<h1> you have successfully entered your name and your name</h1>
</body>
</html>
o/p

Validate1.html

<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>

<form name="myForm" action="https://www.w3schools.com/action_page.php"


onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
o/p

Validate2.html
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["add1"].value;
var z = document.forms["myForm"]["add2"].value;
var l = document.forms["myForm"]["city"].value;
if (x == "" || y=="" || z=="" || l=="") {
alert("All data must be filled out");
return false;
}
else
alert("Congratulations! you have entered all the data intact");

}
</script>
</head>
<body>
<form name="myForm" action="" onsubmit="return validateForm()" method="post">
<table>
</br><tr><td>Name :</td> <td><input type="text" name="fname"></td> </tr>
</br><tr><td>Address :</td><td> <input type="text" name="add1"></td></tr>
</br><tr><td>Locality:</td> <td><input type="text" name="add2"></td></tr>
</br><tr><td>City :</td> <td><input type="text" name="city"></td></tr>
</br>
</br>
</br><tr> <td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>

</body>

Validate3.html
<html>
<body>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100" max="300" required>


<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 or greater than 300, an error message will be
displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
</body>

Server sided scripting

It is important to remember that when developing server-side scripts, you are writing
software, just like a C or Java programmer would do, with the major distinction that your
software runs on a web server and uses the HTTP request- response loop for most
interactions with the clients.

The fundamental difference between client and server scripts is that in a client-side script
the code is executed on the client browser, whereas in a server-side script, it is
executed on the web server.

In contrast, server-side source code remains


hidden from the client as it is processed on
the server. The clients never get to see the
code, just the HTML output from the script.
Figure 8.1 illustrates how client and server
scripts differ
Server-Side Script Resources

● A server-side script can access any resources made available to it by the


server.These resources can be categorized as data storage resources, web
services, and software applications.

● The most commonly used resource is data storage, often in the form of a
connection to a database management system. A database management system
(DBMS) is a software system for storing, retrieving and organizing large
amounts of data

Server-Side Technologies

ASP (Active Server Pages): This was Microsoft’s first server-side technology(also called
ASP Classic). Like PHP, ASP code (using the VBScript programminglanguage) can be
embedded within the HTML. ASP programming code is interpreted at run time, hence it
can be slow in comparison to other technologies.

ASP.NET: This replaced Microsoft’s older ASP technology. ASP.NET ispart of Microsoft’s
.NET Framework and can use any .NET programming language (though C# is the most
commonly used). ASP.NET uses an explicitly object-oriented approach and is often used
in larger corporate web application systems.

JSP (Java Server Pages) :JSP uses Java as its programming language and like
ASP.NET it uses an explicit object-oriented approach and is used in large enterprise web
systems and is integrated into the J2EE environment. Since JSP uses the Java Runtime
Engine, it also uses a JIT compiler for fast execution time and is cross-platform.
Node.js: This is a more recent server environment that uses JavaScript on the server
side, thus allowing developers already familiar with JavaScript to use just a single
language for both client-side and server-side development. Unlike the other development
technologies listed here, node.js is also its own web server software, thus eliminating the
need for Apache, IIS, or some other web server software.

Perl: Until the development and popularization of ASP, PHP, and JSP, Perl was the
language typically used for early server-side web development. As a language, it excels in
the manipulation of text. It was commonly used in conjunction with the Common Gateway
Interface (CGI), an early standard API for communication between applications and web
server software.

PHP: Like ASP, PHP is a dynamically typed language that can be embedded directly
within the HTML, though it now supports most common object-oriented features, such as
classes and inheritance. By default, PHP pages are compiled into an intermediary
representation called opcodes that are analogous to Java’s byte-code or the .NET
Framework’s MSIL. Originally, PHP stood for personal home pages, although it now is a
recursive acronym that means PHP: Hypertext Processor.
Python: This terse, object-oriented programming language has many uses, including
being used to create web applications. It is also used in a variety of web development
frameworks such as Django and Pyramid.

Ruby on Rails: This is a web development framework that uses the Ruby programming
language. Like ASP.NET and JSP, Ruby on Rails emphasizes the use of common software
development approaches, in particular the MVC design pattern.

A Web Server’s Responsibilities


A web server has many responsibilities beyond responding to requests for HTML files.
These include

● handling HTTP connections


● responding to requests for static and dynamic resources
● managing permissions and access for certain resources
● encrypting and compressing data
● managing multiple domains and URLs
● managing database connections, cookies, and state
● uploading and managing files

Apache and Linux


You can consider the Apache web. Apache runs in two possible modes: multi-process
(also called preforked) or multi-threaded (also called worker).

Apache runs as a daemon on the server. A daemon is an executing instance of a


program (also called a process) that runs in the background, waiting for a specific event
that will activate it. As a background process, the Apache daemon (also known by its OS
name, httpd) waits for incoming HTTP requests. When a request arrives, Apache then
uses modules to determine how to respond to the request.
Apache runs in two possible modes: multi-process (also called preforked) or
multi-threaded (also called worker), which are shown in Figure below

In the multi-threaded mode, a smaller number of Apache processes are forked. Each of
the processes runs multiple threads. A thread is like a light- weight process that is
contained within an operating system process. A thread uses less memory than a process,
and typically threads share memory and code; as a consequence, the multi-threaded
mode typically scales better to large loads.
When using this mode, all modules running within Apache have to be thread- safe.

Quick Tour of PHP


PHP, like JavaScript, is a dynamically typed language. Unlike JavaScript it uses classes
and functions in a way consistent with other object-oriented languages such as C++, C#,
and Java, though with some minor exceptions.

The syntax for loops, conditionals, and assignment is identical to JavaScript, only differing
when you getto functions, classes, and in how you define variables.

PHP Tags
The most important fact about PHP is that the code can be embedded directly within an
HTML file.

However, instead of having an .html extension, a PHP file will usually have the extension
.php.

Programming code must be contained within an opening <?php tag and a matching
closing ?> tag in order to differentiate it from the HTML.
The programming code within the <?php and the ?> tags is interpreted and executed,
while any code outside
the tags is echoed directly out to the client.

Php example program


<?php
$user = "Randy";
?>
<!DOCTYPE html>
<html>
<body>
<h1>Welcome <?php echo $user; ?></h1>
<p>
The server time is
<?php
echo "<strong>";
echo date("H:i:s");
echo "</strong>";
?>
</p>
</body>
</html>

o/p
Welcome Randy
The server time is 12:58:50

PHP Comments: single-line comment, multiline comment. end-of-line comment

<?php
# single-line comment
/*
This is a multiline comment.
They are a good way to document functions or complicated blocks of code
*/
$artist = readDatabase(); // end-of-line comment
?>

Variables, Data Types, and Constants : Variables in PHP are dynamically typed, which
means that you as a programmer do not have to declare the data type of a variable.

Instead the PHP engine makes a best guess as to the intended type based on what it is
being assigned. Variables are also loosely typed in that a variable can be assigned
different data types over time.

$count = 42;

Data types
<?php
$artist1="picasso";
$artist2="raphael";
$artist3="cezanne";
$artist4="rembrandt";
$artist5="giotto";

for ($i = 1; $i <= 5; $i++) {


echo ${"artist". $i};
echo "<br/>";
}
?>

Program Control
Write example programs with explanation for the following constructs
if . . . else , switch . . . case, while(), for()

Include file;
It is possible to insert the content of one PHP file into another PHP file (before the server
executes it), with the include or require statement.

include "somefile.php"; # With include , a warning is displayed if not found and then
execution continues
include_once "somefile.php";

require "somefile.php"; #With require , an error is displayed and execution stops.


require_once "somefile.php";

(include_once and require_once statements work just like include and require but if the
requested file has already been included once, then it will not be included again.)

menu.php
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
Main.php
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>

</body>
</html>
o/p
Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP Tutorial

Welcome to my home page!


Some text.

Some more text.

Functions : A set of self contained block of statements for executing some statements
repeatedly to improve the re usability in coding and save the memory space.

A function is a reusable piece or block of code that performs a specific action. Functions
can either return values when called or can simply perform an operation without returning
any value. PHP has over 700 functions built in that perform different tasks

In PHP there are two types of function: user-defined functions and built-in functions. A
user-defined function is one that you the programmer define. A built-in function is one of
the functions that come with the PHP environment

Function Syntax : definition

function functionName() {
code to be executed;
}
Function Syntax : calling
functionName()

<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg();
?>
</body>
</html>
O/P : Hello world!
5.2 PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters your like. These parameters work like variables inside your function.

Call by value and Call by reference

<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
// call by value
function addFive($num) {
$num += 5;
}
// call by reference
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "The Value after call by value is $orignum<br />";
addSix( $orignum );
echo " The Value after call by reference is $orignum<br />";
?>
</body>
</html>

o/p
The Value after call by value is 10
The Value after call by reference is 16

You might also like