Client-Side Scripting Server-Side Scripting
Client-Side Scripting Server-Side Scripting
Web browsers execute client-side scripting. It is used when browsers have all
code. Source code is used to transfer from webserver to user’s computer over
the internet and run directly on browsers. It is also used for validations and
functionality for user events.
It allows for more interactivity. It usually performs several actions without going to
the user. It cannot be basically used to connect to databases on a web server.
These scripts cannot access the file system that resides in the web browser. Pages
are altered on basis of the user’s choice. It can also be used to create “cookies”
that store data on the user’s computer.
Server-side scripting
Web servers are used to execute server-side scripting. They are basically used to
create dynamic pages. It can also access the file system residing at the webserver.
A server-side environment that runs on a scripting language is a web server.
Scripts can be written in any of a number of server-side scripting languages
available. It is used to retrieve and generate content for dynamic pages. It is used
to require to download plugins. In this load times are generally faster than client-
side scripting. When you need to store and retrieve information a database will be
used to contain data. It can use huge resources of the server. It reduces client-side
computation overhead. The server sends pages to the request of the user/client.
Difference between client-side scripting and server-side scripting :
Client-side scripting Server-side scripting
There are many advantages linked The primary advantage is its ability to highly
with this like faster. customize, response
response times, a more interactive requirements, access rights based on user.
Client-side scripting Server-side scripting
application.
It does not provide security for data. It provides more security for data.
HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.
Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In
addition to web browsers, databases such as CouchDB and MongoDB uses JavaScript as their
scripting and query language.
Features of JavaScript
There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is
a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
8. It provides good control to the users over the web browsers.
History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In the year
1994, Netscape was founded by Marc Andreessen. He realized that the web needed to
become more dynamic. Thus, a 'glue language' was believed to be provided to HTML to
make web designing easy for designers and part-time programmers. Consequently, in 1995,
the company recruited Brendan Eich intending to implement and embed Scheme
programming language to the browser. But, before Brendan could start, the company
merged with Sun Microsystems for adding Java into its Navigator so that it could compete
with Microsoft over the web technologies and platforms. Now, two languages were there:
Java and the scripting language. Further, Netscape decided to give a similar name to the
scripting language as Java's. It led to 'Javascript'. Finally, in May 1995, Marc Andreessen
coined the first code of Javascript named 'Mocha'. Later, the marketing team replaced the
name with 'LiveScript'. But, due to trademark reasons and certain other reasons, in
December 1995, the language was finally renamed to 'JavaScript'. From then, JavaScript
came into existence.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
o Displaying clocks etc.
JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>
JavaScript Example
1. JavaScript Example
2. Within body tag
3. Within head tag
Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript code:
within body tag, within head tag and external JavaScript file.
1. <script type="text/javascript">
2. document.write("JavaScript is a simple language for javatpoint learners");
3. </script>
The text/javascript is the content type that provides information to the browser about the
data.
<script type="text/javascript">
alert("Hello WD");
</script>
In this example, we are creating a function msg(). To create function in JavaScript, you need
to write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to call msg()
function.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello WD");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
It provides code re usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension. It is recommended to embed all
JavaScript files into a single file. It increases the speed of the webpage.
Let's create an external JavaScript file that prints Hello WD in an alert dialog box.
message.js
function msg(){
alert("Hello WD");
}
Let's include the JavaScript file into html page. It calls the JavaScript function on button click.
index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect the
execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5. We need to check each file that depends on the commonly created external
javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.
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).
var x = 10;
var _value="sonoo";
var 123=30;
var *aa=320;
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
JavaScript Global Variable
A JavaScript global variable is declared outside the function or declared with window
object. It can be accessed from any function.
<script>
var value=50;//global variable
function a(){
alert(value);
}
function b(){
alert(value);
}
</script>
window.value=90;
Now it can be declared inside any function and can be accessed from any function. For
example:
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
var value=50;
function a(){
alert(window.value);//accessing global variable }
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:
var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
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
}
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Let’s see the example of if-else statement in JavaScript to find out the even or odd number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
1. document.write("a is not equal to 10, 15 or 20");
2. }
3. </script>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is
just like else if statement that we have learned in previous page. But it is convenient
than if..else..if because it can be used with numbers, characters etc.
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;
}
<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>
The switch statement is fall-through i.e. all the cases will be evaluated if you don't use break
statement.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
1. for loop
2. while loop
3. do-while loop
4. for-in loop
1) JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used
if number of iteration is known. The syntax of for loop is given below.
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Output:
1
2
3
4
5
while (condition)
{
code to be executed
}
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Output:
11
12
13
14
15
1. do{
2. code to be executed
3. }while (condition);
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:
21
22
23
24
25
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.
Method Description
apply() It is used to call a function contains this value and a single array of arguments.
call() It is used to call a function contains this value and an argument list.
<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>
Output:
Example 2
<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>
Output:
8
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the object.
But, we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. object={property1:value1,property2:value2.....propertyN:valueN}
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
Sonoo
Vimal
Ratan
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Jai
Vijay
Smith
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns the
modified array.
entries() It creates an iterator object and a loop that iterates over each key/value pair.
every() It determines whether all the elements of an array are satisfying the provided
function conditions.
flat() It creates a new array carrying sub-array elements concatenated recursively till
the specified depth.
flatMap() It maps all array elements via mapping function, then flattens the result into a
new array.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided
function conditions.
find() It returns the value of the first element in the given array that satisfies the
specified condition.
findIndex() It returns the index value of the first element in the given array that satisfies the
specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index of the
first match.
keys() It creates an iterator object that contains only the keys of the array, then loops
through these keys.
lastIndexOf() It searches the specified element in the given array and returns the index of the
last match.
map() It calls the specified function for every array element and returns the new array
of() It creates a new array from a variable number of arguments, holding any type
of argument.
reduce(function, It executes a provided function for each value from left to right and reduces the
initial) array to a single value.
reduceRight() It executes a provided function for each value from right to left and reduces the
array to a single value.
some() It determines if any element of the array passes the test of the implemented
function.
slice() It returns a new array containing the copy of the part of the given array.
toString() It converts the elements of a specified array into string form, without affecting
the original array.
unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the array.
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.
Here, we are validating the form on form submit. The user will not be forwarded to the next
page until given values are correct.
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()"
>
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
<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>
Output:
Enter Name:
Enter Password:
register
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/>
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, js react over these events and allow the execution.
This process of reacting over the events is called Event Handling. Thus, js 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.
Mouse events:
Mouseover onmouseover When the cursor of the mouse comes over the element
Mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Change onchange When the user modifies or changes the value of a form element
Window/Document events
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
Click Event
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
Alert Box
An alert box is often used if you want to make sure information comes through to
the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");
Example
alert("I am an alert box!");
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax
window.confirm("sometext");
Example
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
Prompt Box
A prompt box is often used if you want the user to input a value before entering a
page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the
box returns null.
Syntax
window.prompt("sometext","defaultText");
Example
let person = prompt("Please enter your name", "Harry Potter");
let text;
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the
character n.
Example
alert("Hello\nHow are you?");