Unit 3
Unit 3
Unit 3
What is JavaScript?
HTML and CSS concentrate on a static rendering of a page; things do not change on the
page overtime, or because of events.
To do these things, we use scripting languages, which allow content to change dynamically.
Not only this, but it is possible to interact with the user beyond what is possible with HTML.
Scripts are programs just like any other programming language; they can execute on the
client side or the server.
Embedded JavaScript
JavaScript can be embedded in an HTML document.
To embed it in HTML you must write:
<script type=”text/javascript”>
</script>
The script tag has effect of the stopping the JavaScript being printed out as well as
indentifying the code enclosed.
The JavaScript can be placed in the head section of your HTML or the body.
<html>
<body>
<script type=”text/javascript”>
document.write("<h1>This is a
heading</h1>");
</script>
</body>
</html>
The Scripts placed in the body section are executed as the page loads and can be used to
generatethe content of the page.
As well as the body section, JavaScript can also be placed in the head part.
The advantages of putting a script in there are that it loads before the main body.
External JavaScript
If you want to use the same script on several pages it could be a good idea to place the code
in aseparate file, rather than writing it on each.
That way if you want to update the code, or change it, you only need to do it once.
Simply take the code you want in a separate file out of your program and save it with the
extension
.js.
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
JavaScript Variables
Variables in JavaScript behave the same as variables in most popular programming
languages (C,C++, etc) do, but in JavaScript you don't have to declare variables before you
use them.
A variable's purpose is to store information so that it can be used later. A variable is a
symbolic name that represents some data that you set.
When using a variable for the first time it is not necessary to use "var" before the variable
name.
Variable names must begin with a letter.
Variable names are case sensitive (y and Y are different variables).
var x=5;
var y=6;
var
z=x+y;
You can declare many variables in one statement. Just start the statement with var and
separate thevariables by comma:
var name="Doe", age=30,
job="carpenter";var name="Doe",
age=30,
job="carpenter";
Variable declared without a value will have the value undefined.
If you re-declare a JavaScript variable, it will not lose its value.
The value of the variable carname will still have the value "Volvo" after the execution of
thefollowing two statements.
varcarname="Volvo
";varcarname;
JavaScript Operators
Operators in JavaScript are very similar to operators that appear in other programming
languages.
The definition of an operator is a symbol that is used to perform an operation.
Most often these operations are arithmetic (addition, subtraction, etc), but not always.
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called
the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then
the condition becomes true.
Ex: (A != B) is true.
3
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
Ex: (A > B) is not true.
Logical Operators
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20, then −
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Ex: ! (A && B) is false.
Bitwise Operators
JavaScript supports the following bitwise operators −
Assume variable A holds 2 and variable B holds 3, then −
1
& (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
2
| (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments.
Exclusive OR means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
Assignment Operators
JavaScript supports the following assignment operators −
2
+= (Add and Assignment) Ex: C += A is equivalent to C = C + A
1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
Example
Try the following code to understand how the Conditional Operator works in JavaScript.
Live Demo
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
if...else if... statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part
of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
Live Demo
<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Output
Maths Book
Set the variable to different value and then try...
JavaScript - Switch Case
You can use multiple if...else…if statements, as in the previous chapter, to perform a
multiway branch. However, this is not always the best solution, especially when all of the
branches depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this
situation, and it does so more efficiently than repeated if...else if statements.
The objective of a switch statement is to give an expression to evaluate and several
different statements to execute based on the value of the expression. The interpreter
checks each case against the value of the expression until a match is found. If nothing
matches, a default condition will be used.
switch (expression) {
case condition 1: statement(s)
break;
default: statement(s) }
JavaScript - While Loops
While writing a program, you may encounter a situation where you need to perform an
action over and over again. In such situations, you would need to write loop statements to
reduce the number of lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The
purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates.
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.
Live Demo
<html>
<body>
document.write("Loop stopped!");
//-->
</script>
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 of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters −
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of
that function as shown in the following code.
Live Demo
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the function
and any manipulation can be done over those parameters. A function can take multiple parameters
separated by comma.
Example
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.
Live Demo
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons
to close windows, messages to be displayed to users, data to be validated, and virtually any other
type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains
a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we
will see a few examples to understand a relation between Event and JavaScript −
Example
Try the following example.
Live Demo
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Syntax
Use the following syntax to create an Array object −
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers. When you specify a single numeric parameter
with the Array constructor, you specify the initial length of the array. The maximum length allowed
for an array is 4,294,967,295.
You can create array by simply assigning values as follows −
var fruits = [ "apple", "orange", "mango" ];
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
JavaScript - Objects Overview
JavaScript is an Object Oriented Programming (OOP) language. A programming language can be
called object-oriented if it provides four basic capabilities to developers −
Encapsulation − the capability to store related information, whether data or methods,
together in an object.
Aggregation − the capability to store one object inside another object.
Inheritance − the capability of a class to rely upon another class (or number of classes) for
some of its properties and methods.
Polymorphism − the capability to write one function or method that works in a variety of
different ways.
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise the attribute is considered a property.
Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data types,
such as another object. Object properties are usually variables that are used internally in the
object's methods, but can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
For example − The following code gets the document title using the "title" property of
the document object.
var str = document.title;
Object Methods
Methods are the functions that let the object do something or let something be done to it. There is
a small difference between a function and a method – at a function is a standalone unit of
statements and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to
performing complex mathematical operations on a group of local properties and parameters.
For example − Following is a simple example to show how to use the write() method of document
object to write any content on the document.
document.write("This is test");
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called Object.
Example 1
Try the following example; it demonstrates how to create an Object.
Live Demo
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Output
Book name is : Perl
Book author is : Mohtashim
Example 2
This example demonstrates how to create an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function.
Live Demo
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
Defining Methods for an Object
The previous examples demonstrate how the constructor creates the object and assigns
properties. But we need to complete the definition of an object by assigning methods to it.
Example
Try the following example; it shows how to add a function along with an object.
Live Demo
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
this.price = amount;
}
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
As you can see in the above image, full page is refreshed at request time and user is blocked until
request completes.
Let's understand it another way.
As you can see in the above image, full page is not refreshed at request time and user gets
response from the ajax engine.
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and
more interactive web applications with the help of XML, HTML, CSS, and Java Script.
Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and
JavaScript for dynamic content display.
Conventional web applications transmit information to and from the sever using synchronous
requests. It means you fill out a form, hit submit, and get directed to a new page with new
information from the server.
With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results,
and update the current screen. In the purest sense, the user would never know that anything was
even transmitted to the server.
XML is commonly used as the format for receiving server data, although any format, including plain
text, can be used.
AJAX is a web browser technology independent of web server software.
A user can continue to use the application while the client program requests information from the
server in the background.
Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event
trigger.
Data-driven as opposed to page-driven.
AJAX cannot work independently. It is used in combination with other technologies to create interactive
webpages.
AJAX Technologies
As describe earlier, ajax is not a technology but group of inter-related
technologies. AJAX technologies includes:
o HTML/XHTML and CSS
o DOM
o XML or JSON
o XMLHttpRequest
o JavaScript
DOM
It is used for dynamic display and interaction with data.
XML or JSON
For carrying data to and from server. JSON (Javascript Object Notation) is like XML but short and
faster than XML.
XMLHttpRequest
For asynchronous communication between client and server. For more visit next page.
JavaScript
It is used to bring above technologies together.
1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
Network Addressing
What is an IP Address?
An IP (Internet Protocol) address is a numerical label assigned to the devices connected to a computer
network that uses the IP for communication.
IP address act as an identifier for a specific machine on a particular network. It also helps you to develop a
virtual connection between a destination and a source. The IP address is also called IP number or internet
address. It helps you to specify the technical format of the addressing and packets scheme. Most networks
combine TCP with IP.
An IP address consists of four numbers, each number contains one to three digits, with a single dot (.)
separates each number or set of digits.
Parts of IP address
IP Address is divided into two parts:
Prefix: The prefix part of IP address identifies the physical network to which the computer is
attached. . Prefix is also known as a network address.
Suffix: The suffix part identifies the individual computer on the network. The suffix is also called
the host address.
IP
192 to 223 255.255.255.0 192.1.11. 24 2097157 Used for local area network.
Class C
IP
Class 224 to 239 NA NA NA NA Reserve for multi-tasking.
D
This class is reserved for
IP
240 to 254 NA NA NA NA research and Development
Class E
Purposes.
Class A Network
This IP address class is used when there are a large number of hosts. In a Class A type of network,
the first 8 bits (also called the first octet) identify the network, and the remaining have 24 bits for
the host into that network.
An example of a Class A address is 102.168.212.226. Here, “102” helps you identify the network
and 168.212.226 identify the host.
Class A addresses 127.0.0.0 to 127.255.255.255 cannot be used and is reserved for loopback and
diagnostic functions.
Class B Network
In a B class IP address, the binary addresses start with 10. In this IP address, the class decimal number that
can be between 128 to 191. The number 127 is reserved for loopback, which is used for internal testing on
the local machine. The first 16 bits (known as two octets) help you identify the network. The other
remaining 16 bits indicate the host within the network.
An example of Class B IP address is 168.212.226.204, where *168 212* identifies the network and
*226.204* helps you identify the Hut network host.
Class C Network
Class C is a type of IP address that is used for the small network. In this class, three octets are used to
indent the network. This IP ranges between 192 to 223.
In this type of network addressing method, the first two bits are set to be 1, and the third bit is set to 0,
which makes the first 24 bits of the address them and the remaining bit as the host address. Mostly local
area network used Class C IP address to connect with the network.
Class D Network
Class D addresses are only used for multicasting applications. Class D is never used for regular
networking operations. This class addresses the first three bits set to “1” and their fourth bit set to use for
“0”. Class D addresses are 32-bit network addresses. All the values within the range are used to identify
multicast groups uniquely.
Therefore, there is no requirement to extract the host address from the IP address, so Class D does not
have any subnet mask.
Class E Network
Class E IP address is defined by including the starting four network address bits as 1, which allows you
two to incorporate addresses from 240.0.0.0 to 255.255.255.255. However, E class is reserved, and its
usage is never defined. Therefore, many network implementations discard these addresses as undefined or
illegal.
The network ID cannot start with 127 because 127 belongs to class A address and is reserved for
internal loopback functions.
All bits of network ID set to 1 are reserved for use as an IP broadcast address and cannot be used.
All bits of network ID are set to 0. They are used to denote a particular host on the local network
and should not be routed.
Java – URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a
resource on the World Wide Web. For example:
1. https://www.javatpoint.com/java-tutorial
URL(String spec)
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.
Creates an instance of a URL from the given protocol name, host name, and file name.
The java.net.URL class provides many methods. The important methods of URL class are given below.
Method Description
⚫ Client-Server Computing
At a basic level, network-based systems consist of a server , client , and a media for
communication as shown in next slide figure.
A computer running a program that makes a request for services is called client machine.
A computer running a program that offers requested services from one or more clients is
called server machine.
The media for communication can be wired or wireless Network\
Hosts Identification
Every computer on the Internet is identified by a unique, 4-byte IP address . This is typically
written in dotted octet format like 128.250.25.158 where each byte is an unsigned value
between 0 and 255.
This representation is clearly not user-friendly because it does not tell us anything about
the content and then it is difficult toremember. Hence, IP addresses are mapped to names
like www.yahoo.com or www.google.com, which are easier to remember.
Internet supports name servers that translate these names to IPaddresses. Domain Naming
Service (DNS) maps names to numbers.
public String getHostName() : Return the host name (e.g.: “www.sun.com”) of IP address.
String getHostAddress() :Returns string format of the address (e.g.: “192.18.97.241”)
InetAddress[] getAllByName(String hostName)
boolean equals(Object obj)
byte[] getByAddress() returns the IP address in byte format (as opposed to dotted decimal notation)
InetAddress getByName(String hostName)
InetAddress getLocalHost() returns the instance of InetAddresscontaining local host name and
address.
Output:
y Naol G.(MSc.)
Service Ports
A) Stream sockets enable a process to establish a connection with another process. While
the connection is in place, data flows between the processes in continuous streams.
Stream sockets provide a connection-oriented service. The protocol used for transmission is
the popular TCP (Transmission Control Protocol). Provides reliable , in-order byte-stream
service
This is typically not appropriate for use by everyday programmers because the transmission
protocol is UDP (User Datagram Protocol).UDP provides a connectionless service. A connectionless
service does not guarantee that packets arrive at the destination in any particular order.
The java.net package provides support for the two commonnetwork protocols:
TCP communication:
Socket
ServerSocket
UDP communication:
DatagramPacket
DatagramSocket
MulticastSocket
A socket is bound to a port number so that the TCP layer canidentify the application that data
destined to be sent.
Socket Communication
A server (program) runs on a specific computer and has asocket that is bound to a
specific port.
The server waits and listens to the socket for a client to make a connection request.
Client
server
server
Client
Server process must first be running (must have created a socket). Recall thatTCP is not
connectionless.
Client contacts the server by creating client-local socket specifying IP address and port
number of server process. ClientTCP establishes connection to server TCP.
When contacted by client, server TCP creates a new socketfor server process to
communicate with client.
From application viewpoint: TCP provides reliable, in-order transfer of bytes (“pipe”)
between client and server.
1. Open the Server Socket: Each client connection handled with a Socket
object. Server blocks until client connects.
This is typically not appropriate for use by everyday programmers because the transmission
protocol is UDP (User Datagram Protocol).
UDP provides a connectionless service. A connectionless service does not guarantee that
packets arrive at the destination in any particular order.
With UDP, packets can be lost or duplicated. Significant extra programming is required
on the programmer’s part to deal with these problems.
UDP is most appropriate for network applications that do not require the error checking
and reliability of TCP.
Under UDP there is no “connection” between the server and the client.
There is no “handshaking”.
The sender explicitly attaches the IP address and port of the destination toeach packet.
The server must extract the IP address and port of the sender from thereceived
packet.
From an application viewpoint, UDP provides unreliable transfer of groups ofbytes
(“datagrams”) between client and server.
DatagramPacket
Create an array of bytes large enough to hold the data of the packet to be sent, and fill the
array with the data.
A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for
creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are
responsible to create the instance of the class.