JavaScript and Networking Basics
JavaScript and Networking Basics
Unit-3
JAVASCRIPT,
AJAX,NETWORKING
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<h1 id="demo">Hello world!</h1>
<script>
// Change text when page loads
[Link]("demo").innerHTML = "Hello from JavaScript!";
</script>
</body>
</html>
Modern JavaScript
•Using let
•Using const
🔹 1. var
•Can be re-declared and updated in the same scope.
•It is function-scoped (or globally scoped if not inside a function).
<script>
var x = 10;
var x = 20; // ✅ re-declaration allowed
x = 30; // ✅ update allowed
[Link](x); // 30
</script>
⚠ This can cause bugs, so var is rarely used in modern JavaScript.
🔹 2. let
•Can be updated, but NOT re-declared in the same scope.
•It is block-scoped (works only inside {} block).
<script>
let y = 10;
y = 20; // ✅ update allowed
// let y = 30; ❌ Error: Identifier 'y' has already been declared
[Link](y);
<script>
But in a different block, you can declare it again:
<script>
let z = 5;
{
let z = 100; // ✅ new variable (different scope)
[Link](z); // 100
}
[Link](z); // 5
</script>
🔹 3. const
Cannot be re-declared or updated.
Must be initialized at the time of declaration.
Also block-scoped.
<script>
const PI = 3.14;
// PI = 3.1415; ❌ Error: Assignment to constant variable
// const PI = 3.1415; ❌ Error: Already declared
[Link](PI);
</script>
<script>
x = 10; // no var, let, or const
[Link](x); // 10
<script>
✅ It works — but behind the scenes, JavaScript adds x to the global scope
<script>
function test() {
y = 100; // forgot let
}
test();
[Link](y); // 100 😱 becomes global!
</script>
✅ Best Practice
Always use let (if value changes) or const (if fixed).
Avoid declaring variables without a keyword.
// Example: variable declarations in JavaScript
<script>
[Link]("=== Using var ===");
var a = 10;
var a = 20; // ✅ re-declared
a = 30; // ✅ updated
[Link]("a =", a); // 30
⚠ Not recommended after the page has loaded because it overwrites the entire page.
4. Using innerHTML (Inject into HTML element)
<div id="output"></div>
<script>
[Link]("output").innerHTML = “Welcome to javascript!";
</script>
b) String
•Text enclosed in single quotes ' ', double quotes " ", or backticks ` ` (for templates).
Example:
<script>
let name = "Anil";
let greeting = 'Hello World';
let message = `Welcome ${name}!`; // Template literal
[Link](name, greeting, message);
</script>
c) Boolean
•Represents true or false.
Example: <script>
let isStudent = true;
let hasGraduated = false;
[Link](isStudent, hasGraduated);
</script>
d) Undefined
•A variable that has been declared but hasn't been given a value
yet.
•It's like an empty container.
Example: A new volunteer signs up but we haven't assigned them a job
yet.
let volunteerJob;
[Link](volunteerJob); // Output: undefined
e) Null:
It explicitly means "nothing" or "empty." It's not undefined; we are choosing to
say there's no value here.
Example: The popcorn machine is broken and is out of service until further
let popcornMachine = null;
[Link](popcornMachine); // Output: null
Array
functions
Object in Javascript:
🔹 Creating Objects in JavaScript
1. Using Object Literal {} (most common)
<script>
let car = {
brand: "Toyota",
model: "Fortuner",
color: "Black",
start: function() {
return "Car started!";
}
};
//[Link]([Link]); // Toyota
//[Link](car["color"]); // Black
for(let c in car){
[Link](car[c]);
}
[Link]([Link]()); // Car started!
</script>
2. Using new Object()
[Link]([Link]); // John
class Student {
constructor(name, roll) {
[Link] = name;
[Link] = roll;
}
}
🔹 Creating Arrays
1. for loop
for (let i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}
2. for...of
for (let fruit of fruits) {
[Link](fruit);
}
Using new Array() constructor:
Function
🔹 Syntax of a Function
function functionName(parameters) {
// code to execute
return result; // optional
}
🔹 Types of Functions in JavaScript
[Link] Declaration (Named Function)
function display(name) {
return "Hello, " + name;
}
Let d=Display("Anil")
[Link](d); // Hello, Anil
2. Function Expression
(Function stored in a variable.)
let display = function(name) {
return "Hello, " + name;
};
Let d=Display("Anil")
[Link](d); // Hello, Anil
3. Arrow Function (ES6+) (Mostly used )
let display = (name) => "Hello, " + name;
[Link](greet("Student")); // Hello, Student
4. Anonymous Function (Function without a name – often used in
setTimeout, forEach.)
setTimeout(function() {
[Link]("This runs after 2 seconds");
}, 2000);
Math Object
JavaScript has a built-in Math object that provides properties and methods for
mathematical calculations.
It is not a constructor, so you cannot do new Math().
You just use it directly → [Link]()
🔹 Common Math Properties
[Link](4.6); // 5
[Link](4.4); // 4
[Link](4.1); // 5 (round UP)
[Link](4.9); // 4 (round DOWN)
[Link](4.9); // 4 (just remove decimals)
[Link](3, 7, 1, 9); // 1
[Link](3, 7, 1, 9); // 9
5. Random Numbers
[Link](getRandom(50, 100));
// Example output: 73 (integer between 50 and 100)
Example: make a simple interactive Random Number Generator to generate
number between 1 & 100 with a button.
<!DOCTYPE html>
<html>
<head>
<title>Random Number Generator</title>
</head>
<body>
<h2> Random Number Generator</h2>
<p>Click the button to generate a random number between 1 and 100:</p>
<button onclick="generateRandom()">Generate Number</button>
<h3 id="result"></h3>
<script>
function generateRandom() {
let num = [Link]([Link]() * 100) + 1;
[Link]("result").innerText = "Your Number: " + num;
}
</script>
</body>
</html>
Date Object in JavaScript
The Date object in JavaScript is used to work with dates and times.
It allows you to create, format, and manipulate dates.
1. Creating a Date Object
There are 4 main ways to create a date:
// Current date and time
let now = new Date();
[Link](now);
Output:
Tue Sep 30 2025 15:59:42 GMT+0530 (India Standard Time)
// Specific date and time
let d1 = new Date("2025-09-22");
[Link](d1);
Output:
Tue Sep 22 2015 05:30:00 GMT+0530 (India Standard Time)
// Year, Month, Day (Month starts from 0 → Jan=0, Feb=1, ... Dec=11)
let d2 = new Date(2025, 8, 30); // 30 Sep 2025
[Link](d2);
Output
Tue Sep 30 2025 00:00:00 GMT+0530 (India Standard Time)
// Date and time with hours, minutes, seconds
let d3 = new Date(2025, 8, 30, 15, 45, 20);
[Link](d3);
Output:
Tue Sep 30 2025 15:45:20 GMT+0530 (India Standard Time)
2. Important Methods of Date Object
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<h1 id=“demo">Hello DOM</h1>
<p class="text">This is a paragraph.</p>
</body>
</html>
⚡ Accessing DOM Elements in JavaScript
JavaScript can select and manipulate DOM elements in many ways:
1. By ID
[Link](“demo").innerHTML = "Welcome to DOM!";
2. By Class
[Link]("text")[0].[Link] = "blue";
3. By Tag
[Link]("h1")[0].[Link] = "yellow";
[Link] content
[Link](“demo").innerText = "DOM Updated!";
[Link] style
[Link](".text").[Link] = "red";
[Link] element
let para = [Link](".text");
[Link]();
Example: Adding an element in a web document using JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Adding an Element Example</title>
</head>
<body>
<h2>Student List</h2>
<ul id="studentList">
<li>Rohit</li>
<li>Prakash</li>
</ul>
<button onclick="addStudent()">Add New Student</button>
<script>
function addStudent() {
let newItem = [Link]("li");
[Link] = "Anil";
[Link]("studentList").appendChild(newItem);
}
</script>
</body>
</html>
📘 Example: Change Text with a Button (DOM Manipulation)
[Link]
<!DOCTYPE html> // Change text of h1
<head> function changeText() {
<title>DOM Example</title> [Link]("title")
<style> .innerText = "Text Changed with DOM!";
#title { }
color: blue; // Change color of h1
font-size: 24px; function changeColor()
} [Link]("title").[Link]
button { = "green";
margin-top: 10px; }
padding: 8px 15px; // Add new paragraph
font-size: 16px; function addParagraph() {
cursor: pointer; let newPara = [Link]("p");
} [Link] = "This is a new paragraph
</style> added using DOM.";
</head> [Link](newPara);
<body> }
<h1 id="title">Hello DOM!</h1>
<button onclick="changeText()">Change Text</button>
<button onclick="changeColor()">Change Color</button>
<button onclick="addParagraph()">Add Paragraph</button>
<script src=“[Link]”>
</body>
</html>
Events
•An event is any action or occurrence that happens in the browser and can be
detected by JavaScript.
•Events are usually triggered by the user or the browser.
Examples of events:
•A user clicks a button.
•A user moves the mouse over an element.
•A user presses a key on the keyboard.
•A form gets submitted.
Event Handling
•Event Handling means writing JavaScript code that responds to events.
<!DOCTYPE html>
<html>
<body>
<script>
function showMessage() {
alert("Hello! You clicked the button.");
}
</script>
</body>
</html>
Method 3: Using addEventListener() (Best Practice)
<!DOCTYPE html>
<html>
<body>
<script>
[Link]("myBtn").addEventListener("click", function() {
alert("Button was clicked!");
});
</script>
</body>
</html>
Advantages of addEventListener():
<!DOCTYPE html>
<html>
<head>
<title>onmouseover and onmouseout Example</title>
</head>
<body>
<h2 onmouseover="[Link]='red'" onmouseout="[Link]='black'">
Hover over this text!
</h2>
</body>
</html>
Form Validation Example
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Validation</title>
<style>
.error { color: red; font-size: 14px; }
</style>
</head>
<body>
<h2>Simple Registration Form</h2>
<form onsubmit="return validateForm()">
Name: <input type="text" id="name">
<span class="error" id="nameError"></span><br><br>
Email: <input type="text" id="email">
<span class="error" id="emailError"></span><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
function validateForm() {
// Get values from inputs
let name = [Link]("name").[Link]();
let email = [Link]("email").[Link]();
[Link] a HTML form with name, address, pincode and password. Outline a JavaScript
code that can validate on following constraints: a. No fields must be left blank b. Pincode
must be numeric and contain 6 digits c. Password field (i) At least contains 1 Capital letter.
(ii) Minimum length 8 characters
[Link] the various event handlers in JavaScript with an example of each. Create a
JavaScript program to make arithmetic calculator
🌐 What is AJAX?
AJAX stands for Asynchronous JavaScript And XML.
Example :
In [Link] results appear instantly — that’s AJAX at work!
[Link]
XMLHttpRequest
Request
Client Response Server
(Browser)
Example
[Link]
Hello this is changed by AJAX!
modern way of doing AJAX using fetch() function
The fetch() function is a built-in JavaScript method used to make HTTP
requests (like GET, POST, PUT, DELETE) to a web server
It helps you get or send data from a server without reloading the webpage.
<!DOCTYPE html>
<html>
<body>
<p id="demo">Here we load data.</p>
<button onclick="loadData()">Click</button>
<script>
function loadData(){
fetch("[Link]")
.then((response)=>[Link]())
.then((data)=>[Link](data));
}
</script>
</body>
</html>
🌐 What is AJAX?
AJAX stands for Asynchronous JavaScript And XML.
Example :
In [Link] results appear instantly — that’s AJAX at work!
[Link]
XMLHttpRequest
Request
Client Response Server
(Browser)
Example
[Link]
Hello this is changed by AJAX!
modern way of doing AJAX using fetch() function
The fetch() function is a built-in JavaScript method used to make HTTP
requests (like GET, POST, PUT, DELETE) to a web server
It helps you get or send data from a server without reloading the webpage.
<!DOCTYPE html>
<html>
<body>
<p id="demo">Here we load data.</p>
<button onclick="loadData()">Click</button>
<script>
function loadData(){
fetch("[Link]")
.then((response)=>[Link]())
.then((data)=>[Link](data));
}
</script>
</body>
</html>
Advance java Programming (AJP)
GTU # 3160707
Networking
A Factory Method is a method that creates and returns an object, usually of an interface or
abstract class type.
Method Description
public static InetAddress getByName(String Determines the IP address of a given host's
host) throws UnknownHostException name.
public static InetAddress getAllByName It returns an array of IP Addresses that a
(String host) throws UnknownHostException particular host name.
public static InetAddress getLocalHost()
Returns the address of the local host.
throws UnknownHostException
Instance Methods
Write a program to accept a website name and return its IPAddress, after checking it on
Internet
import [Link].*; //required for InetAddress Class
public class Address{
public static void main(String[] args){
try {
InetAddress ip = [Link]("[Link]");
[Link]("Host Name: "+[Link]());
[Link]("IP Address:"+ [Link]());
}catch(UnknownHostException e) {
[Link](e);
} Output
}
}
URL
[Link]
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the port number of the URL.
public String getFile() it returns the file name of the URL.
public String getQuery() it returns the query string of the URL.
public String getDefaultPort() it returns the default port of the URL.
public URLConnection it returns the instance of URLConnection i.e. associated with this
openConnection() URL.
Program
Write a program to get the Protocol, Host Name, Port Number, and Default File Name from
given URL.
import [Link].*; //required for InetAddress Class
public class URLDemo{
public static void main(String[] args){
try {
URL url=new
URL("[Link] /");
[Link]("Protocol: "+[Link]());
[Link]("Host : "+[Link]());
[Link]("Port : "+[Link]());
[Link]("File : "+[Link]()); Output
}catch(MalformedURLException e) {
[Link](e);
}
}
}
URLConnection
URLConnection class is useful to actually connect to a website or resource on a network and
get all the details of the website.
For example, to know the details of [Link] we should pass its URL
to the object of URL class.
Then using openConnection() method, we should establish a connection with the site on
internet.
openConnection() method returns URLConnection object.
Method Description
public int getContentLength() it returns the size in bytes of the content as a int.
public String getContentType() it returns the content-type of the resource.
public long getDate() it returns the time and date of the response in
milliseconds.
public InputStream getInputStream() throws Returns an input stream that reads from open
IOException connection.
public OutputStream getOutputStream() throws Returns an output stream that writes into open
IOException connection.
Program
Write a program to display the details and page contents of your website.
import [Link].*; //required for InetAddress Class
import [Link].*;
import [Link].*;
public class URLConnectionDemo{
public static void main(String[] args){
try {
URL url=new URL("[Link]
URLConnection con = [Link]();
[Link]("Date: " + new Date([Link]()));
[Link]("Content-type: " + [Link]());
[Link]("Expiry: " + [Link]());
[Link]("Length of content: " + [Link]());
if([Link]()>0){
int ch;
InputStream in=[Link](); Output
while ((ch=[Link]())!=-1) {
[Link]((char)ch);
}
}
}catch(MalformedURLException e) {
[Link](e);
}
}
}
Socket
“A socket is one endpoint of a two-way communication link between two programs running
on the network.”
A Socket is combination of an IP address and a port number.
A socket is bound to a port number so that the TCP layer can identify the destination
application where data is to be sent.
Ports
ServerSocket ss = new ServerSocket(80) Computer where
5566 E server is running
A TCP/IP ServerSocket in Java is used to: 1080
R
[Link] a port on the server V
2010 E
[Link] for a TCP client to connect R
[Link] the connection 3040
class:client sends data to the server and receives a response over a reliable TCP
The
The Java code for creating socket at client side.
connection.
Socket sock = new Socket(“[Link]”,80);
A TCP/IP client socket in Java:
[Link] to a server using IP + port
[Link] data to the server
[Link] data from the server
[Link] TCP protocol (reliable,
connection-oriented)
[Link]
import [Link].*;
import [Link].*;
public class TCPServer {
public static void main(String[] args) {
try {
// Step 1: Create server socket on port 5000
ServerSocket server = new ServerSocket(5000);
[Link]("Server started... Waiting for client...");
// Step 2: Accept client connection
Socket socket = [Link]();
[Link]("Client connected.");
// Step 3: Create input & output streams
BufferedReader br = new BufferedReader(new InputStreamReader([Link]()));
PrintWriter pw = new PrintWriter([Link](), true);
A Datagram is a packet of information sent over a network using UDP (User Datagram
Protocol).
Features of Datagram / UDP: