UNIT-4: Java Script
___________________________________________________________________________
JavaScript: Introduction, Documents, Forms, Statements, Functions, Objects,
Events, and Event Handling, Introduction to AJAX, VB Script, and CGI.
__________________________________________________________________
1. JavaScript
● Introduction:
JavaScript is a dynamic, interpreted scripting language used to create interactive effects
within web browsers. It allows for client-side interactivity and manipulation of HTML
elements, that’s why it is also known as Client-side scripting language. It is embedded in
HTML using <script> tag.
But JavaScript's flexibility extends to both the client-side and server-side, allowing
developers to create complete web applications.
Client-Side:
● Involves controlling the browser and its DOM (Document Object Model).
● Handles user events like clicks and form inputs.
● Common libraries include AngularJS, ReactJS, and VueJS.
Server-Side:
● Involves interacting with databases, manipulating files, and generating responses.
● [Link] and frameworks like [Link] are widely used for server-side
JavaScript, enabling full-stack development.
Some of the key features of JavaScript are:
● Lightweight and Fast: JavaScript is a lightweight programming language that runs
quickly in web browsers.
● Single-Threaded: It processes tasks one at a time, making it simple to manage, though
asynchronous features like Promises help handle multiple tasks simultaneously.
● Event-Driven: JavaScript is designed to handle events (like clicks or key presses) in web
applications.
● Client-Side Scripting: JavaScript runs on the user's browser, so has a faster response
time without needing to communicate with the server.
● Versatile: Can be used for a wide range of tasks, from simple calculations to complex
server-side applications.
● Asynchronous: It can handle tasks like fetching data from servers without freezing the
user interface.
● Rich Ecosystem: There are numerous libraries and frameworks built on JavaScript, such
as React, Angular, and [Link], which make development faster and more efficient.
Comments in JavaScript:
Single-line comment: Starts with //
// This is a single-line comment
Multi-line comment: Enclosed in /* */
/* This is a multi-line comment
spanning multiple lines */
Variables: JavaScript uses variables to store data.
var x = 5; //reassigning is allowed
let y = "Hello"; //y = 20; can be updated but not redeclared in the same scope (let y = 15;)
const z = true; // n = 200; This will throw an error ( It's block-scoped as well.)
Data Types: JavaScript supports various datatypes, which can be broadly categorized into
primitive and non-primitive types.
Primitive Datatypes
Primitive datatypes represent single values and are immutable.
1. Number: Represents numeric values (integers and decimals).
let n = 42;
let pi = 3.14;
2. String: Represents text enclosed in single or double quotes.
let s = "Hello, World!";
3. Boolean: Represents a logical value (true or false).
let bool= true;
4. Undefined: A variable that has been declared but not assigned a value.
let notAssigned;
[Link](notAssigned);
Output
undefined
5. Null: Represents an intentional absence of any value.
let empty = null;
6. Symbol: Represents unique and immutable values, often used as object keys.
let sym = Symbol('unique');
7. BigInt: Represents integers larger than Number.MAX_SAFE_INTEGER.
let bigNumber = 123456789012345678901234567890n;
Non-Primitive Datatypes
Non-primitive types are objects and can store collections of data or more complex entities.
1. Object: Represents key-value pairs.
let obj = {
name: "Amit",
age: 25
};
2. Array: Represents an ordered list of values.
let a = ["red", "green", "blue"];
3. Function: Represents reusable blocks of code.
function fun() {
[Link]("GeeksforGeeks");
}
Operators: JavaScript includes a wide range of operators for arithmetic, comparison,
and logical operations.
○ Arithmetic: +, -, *, /, %
○ Comparison: ==, ===, !=, >, <
○ Logical: &&, ||, !
● Documents & Forms:
○ Accessing elements via [Link](), [Link][]
○ Form validation using JavaScript.
● Statements:
○ Conditional: if, else, switch
○ Loops: for, while, do...while
● Functions:
○ Declaring: function myFunc() {}
○ Parameters, return values, scope
● Objects:
○ Built-in: Date, Math, Array, String
○ Custom objects using constructor functions
● Events & Event Handling:
○ Events: onclick, onmouseover, onchange, onsubmit
○ Event listeners: addEventListener()
Functions: Functions are blocks of reusable code. They can be defined with or without parameters.
function greet(name) {
return "Hello, " + name;
}
let greeting = greet("Alice");
DOM Manipulation: JavaScript interacts with the DOM (Document Object Model) to modify the
structure, style, or content of a webpage.
[Link]("demo").innerHTML = "Hello World!";
Event Handling: JavaScript can respond to user interactions, like clicks, key presses, etc.
[Link]("button").onclick = function() {
alert("Button clicked!");
};
JavaScript Frameworks: Libraries and frameworks like React, Angular, and [Link] are built using
JavaScript to help developers build complex user interfaces more easily.
2. AJAX (Asynchronous JavaScript and XML)
● Allows asynchronous data exchange with servers.
● Uses XMLHttpRequest or fetch() API.
● Improves user experience by updating parts of a page without reloading.
AJAX allows for asynchronous data loading, enabling dynamic updates on web pages without
requiring a full page reload. It is particularly useful in creating smooth, interactive web applications.
Key Concepts of AJAX:
Asynchronous Operation: AJAX allows web pages to communicate with servers in the background
and update parts of the page without reloading it entirely.
Example:
var xhr = new XMLHttpRequest();
[Link]("GET", "[Link]", true);
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
[Link]("result").innerHTML = [Link];
}
};
[Link]();
● AJAX Components:
○ XMLHttpRequest: A JavaScript object that facilitates HTTP requests to a web
server.
○ Callback Function: A function that is executed after the request is completed. This
function usually handles the response data.
○ Response Data: The server’s response can be in multiple formats such as plain text,
HTML, or JSON.
Using Fetch API: A modern alternative to XMLHttpRequest, the Fetch API allows easier handling
of asynchronous requests and responses.
Example with Fetch:
fetch("[Link]")
.then(response => [Link]())
.then(data => {
[Link]("result").innerHTML = [Link];
})
.catch(error => [Link]("Error:", error));
● Use Cases of AJAX:
○ Form submission without page reload (like login forms or comment sections).
○ Live search that shows results as you type.
○ Auto-updating content (such as displaying live stock prices or news feeds).
AJAX, which stands for Asynchronous JavaScript And XML, is a set of web
development techniques used on the client-side to create asynchronous web
applications. It is not a new programming language but rather a way to use existing
web technologies together to enable dynamic and interactive user experiences
without requiring full page reloads.
Here's a breakdown of key aspects:
● Asynchronous Communication: The core principle of
AJAX is its ability to exchange data with a server in the
background, without interrupting the user's interaction with
the web page. This means parts of a page can be updated
without reloading the entire page.
● Key Technologies: AJAX leverages a combination of
standard web technologies:
● JavaScript: Used to initiate requests to the server,
handle responses, and dynamically update the web
page's content (DOM).
● XMLHttpRequest (XHR) Object: This object is central
to AJAX, enabling the asynchronous exchange of data
between the client and server.
● HTML/CSS: Used for structuring and styling the web
page.
● Data Formats: While the "XML" in AJAX originally
referred to XML as the primary data format, modern
AJAX applications commonly use JSON (JavaScript
Object Notation) due to its lightweight nature and ease
of parsing with JavaScript. Other formats like plain text
or preformatted HTML can also be used.
● How it Works (Simplified):
● A user action or an event triggers a JavaScript
function.
● This function creates and configures an
XMLHttpRequest object.
● The XMLHttpRequest object sends an asynchronous
request to the server.
●
● The server processes the request and sends a
response (e.g., JSON data, HTML snippets).
● JavaScript receives the response and uses it to update
specific parts of the web page's DOM, creating a
seamless user experience.
● Benefits:
● Improved User Experience: Eliminates full page
reloads, making web applications feel faster and more
responsive.
● Reduced Bandwidth Usage: Only necessary data is
exchanged with the server, reducing the amount of
data downloaded.
● Dynamic Content Updates: Allows for real-time
updates of specific page elements without affecting
others.
● Examples: Common examples of AJAX in action include
auto-completion in search bars, dynamic content loading
(e.g., infinite scrolling), real-time form validation, and
updating shopping cart totals without a full page refresh.
3. VBScript (Visual Basic Script)
🔹 VBScript
● Microsoft’s scripting language for Internet Explorer.
● Similar to Visual Basic.
● Used for form validation and automation (now largely obsolete).
VBScript is a lightweight scripting language developed by Microsoft, mainly used in web pages for
client-side scripting in Internet Explorer. It’s a precursor to JavaScript but is now largely deprecated
for web use due to limited browser support.
Key Concepts of VBScript:
Variables: Declared using the Dim keyword.
Dim x
x=5
●
Data Types: VBScript is loosely typed, meaning variables do not have a defined type. It is usually
treated as a variant type.
Dim str
str = "Hello, World!"
●
Control Structures: VBScript supports common control structures like If, For, Do While, and Select
Case.
If x > 10 Then
MsgBox "Greater than 10"
Else
MsgBox "Less than or equal to 10"
End If
●
Functions: Functions are defined with the Function keyword.
Function greet(name)
greet = "Hello, " & name
End Function
●
Event Handling: VBScript can handle events in Internet Explorer, such as button clicks or page load.
Sub buttonClick()
MsgBox "Button clicked!"
End Sub
● Use Cases: VBScript was once used for:
○ Validating forms.
○ Adding interactivity to web pages in older versions of Internet Explorer.
● Note: Modern browsers no longer support VBScript, and it is considered obsolete in favor of
JavaScript.
4. CGI (Common Gateway Interface)
Protocol for web servers to execute scripts.
● Typically written in Perl, Python, or C.
● Used for dynamic content generation.
CGI is a standard for running external programs (scripts) on a web server to generate dynamic
content. CGI scripts can be written in various programming languages like Perl, Python, C, or Bash.
Key Concepts of CGI:
● CGI Scripts: These are executable programs that process data sent to the web server (such as
form data) and return output to the client (e.g., a dynamic HTML page).
● How CGI Works:
○ The client sends a request to the web server (e.g., submitting a form).
○ The server executes a CGI script on the server-side.
○ The CGI script processes the request (e.g., retrieves data from a database).
○ The server sends the output of the script back to the client.
Example of a simple CGI script (written in Perl):
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<html><body><h1>Hello, CGI!</h1></body></html>";
●
● CGI Environment Variables:
○ QUERY_STRING: Holds data sent via the query string (GET method).
○ REQUEST_METHOD: Holds the HTTP method used (GET, POST).
○ CONTENT_TYPE: Contains the type of data (e.g.,
application/x-www-form-urlencoded).
● Common Uses of CGI:
○ Form Handling: CGI scripts process form submissions and return dynamic
responses.
○ Data Retrieval: CGI scripts can query databases and return data to the user.
○ File Handling: Uploading and managing files via forms.
● Disadvantages of CGI:
○ Performance: Each request results in a new process, which can be
resource-intensive.
○ Modern Alternatives: CGI is largely replaced by technologies like PHP, [Link],
[Link], and Python due to better performance and easier integration with modern
web frameworks.
Summary
This unit covers essential client-side and server-side scripting technologies:
● JavaScript: A versatile language for client-side interactivity, DOM manipulation, and
handling events.
● AJAX: A technique that enables asynchronous communication with the server, allowing for
dynamic page updates without reloading.
● VBScript: A scripting language primarily used in older versions of Internet Explorer for
client-side scripting. It is now largely obsolete.
● CGI: A standard for creating dynamic content on the server side. Although powerful, CGI is
less efficient than newer server-side technologies.
These technologies serve complementary roles in modern web development, helping to create
dynamic, interactive, and responsive web applications.