0% found this document useful (0 votes)
7 views77 pages

JavaScript and Networking Basics

Unit-3 covers JavaScript, AJAX, and networking concepts. It introduces JavaScript as a high-level programming language for web interactivity, discusses variable declarations, data types, functions, and the Math and Date objects. Additionally, it explains the Document Object Model (DOM) as a programming interface for web documents.

Uploaded by

yuvika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views77 pages

JavaScript and Networking Basics

Unit-3 covers JavaScript, AJAX, and networking concepts. It introduces JavaScript as a high-level programming language for web interactivity, discusses variable declarations, data types, functions, and the Math and Date objects. Additionally, it explains the Document Object Model (DOM) as a programming interface for web documents.

Uploaded by

yuvika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Web Technology

Unit-3
JAVASCRIPT,
AJAX,NETWORKING

Prof. Anand Singh


Unit-3
• Scripting: Java script: Introduction, documents,
forms, statements, functions, objects, introduction
to AJAX.
• Networking: Internet Addressing, InetAddress,
Factory Methods, Instance Methods, TCP/IP Client
Sockets, URL, URL Connection, TCP/IP Server
Sockets, Datagram.
What is JavaScript?
JavaScript (JS) is a high-level, interpreted programming language that is mainly used
to make web pages interactive and dynamic.

•Without JavaScript → a webpage is just HTML (structure) + CSS (style).


•With JavaScript → you can add logic, interactivity, and behavior.

👉 That’s why we call JavaScript the “brain of the web page”.

•HTML = skeleton of a body (structure).


•CSS = clothes and makeup (appearance).
•JavaScript = brain (makes it move, think, and respond).
🔹 Example: A Simple JavaScript Program

<!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>

👉 This changes the heading text using JavaScript.


Variables in JavaScript variables are containers for data.
JavaScript variables can be declared in 4 ways:
Older JavaScript

•Using var (Not Recommended)


•Automatically (Not Recommended)

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>

🔹 [Link] a Variable Without var, let, or const


If you just assign a value to a name without using var, let, or const, JavaScript
will automatically create a global variable.

<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

🔹 Problems with This


Accidental Globals
If you forget let/const, you might create unwanted global variables:

<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

[Link]("\n=== Using let ===");


let b = 10;
// let b = 20; ❌ Error: Cannot re-declare in same scope
b = 20; // ✅ update allowed
[Link]("b =", b); // 20

[Link]("\n=== Using const ===");


const c = 10;
// const c = 20; ❌ Error: Cannot re-declare
// c = 30; ❌ Error: Cannot update
[Link]("c =", c); // 10
function test() {
[Link]("\n=== Without var/let/const ==="); e = 50; // ⚠ becomes global, even inside
d = 10; // ⚠ Implicit global function
d = 20; // ✅ update allowed }
[Link]("d =", d); // 20 test();
</script> [Link]("e =", e); // 50 (unexpected!)
Different ways to display output in Javascript
In JavaScript, there are several ways to display output depending on where you
want to show it—web page, console, or pop-up.
1. Using [Link]()
This is mostly used for debugging.
[Link]("Hello World"); // General output

✅ Output goes to the browser console.

2. Using alert() (Pop-up box)


Displays a popup alert box in the browser.
alert("Hello JavaScript!");
⚠ This interrupts the user experience; mostly used for simple testing.

3. Using [Link]() (Directly on page)

Writes content directly into the HTML page.


[Link]("Hello World!");

⚠ Not recommended after the page has loaded because it overwrites the entire page.
4. Using innerHTML (Inject into HTML element)

Displays output inside an HTML element.

<div id="output"></div>
<script>
[Link]("output").innerHTML = “Welcome to javascript!";
</script>

✅ Safe and widely used for dynamic content.


Data Types in JavaScript
Data types tells what kind of value a variable holds.
There are two main categories:

[Link] Data Types → simple, single values


[Link]-Primitive Data Types (Objects) → more complex, can store multiple values

1⃣ Primitive Data Types


These are simple and immutable (cannot be changed once created).
a) Number
•Represents numeric values (both integers and decimals).
Example:
<script>
let age = 20; // integer
let price = 99.99; // decimal
[Link](age, price);
</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

2⃣ Non-Primitive Data Type


Object

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()

let person = new Object();


[Link] = "John";
[Link] = 25;

[Link]([Link]); // John

3. Using Constructor Function

function Person(name, age) {


[Link] = name;
[Link] = age;
}

let p1 = new Person("Alice", 30);


[Link]([Link]); // Alice
4. Using ES6 class

class Student {
constructor(name, roll) {
[Link] = name;
[Link] = roll;
}
}

let s1 = new Student("Anil", 101);


[Link]([Link]); // Anil
🔹 Arrays in Javascript

🔹 Creating Arrays

Using square brackets (most common):


let fruits = ["Apple", "Banana", "Mango"];
[Link](fruits[0]); // Apple
[Link](fruits[2]); // Mango

🔹 Looping Through 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:

let numbers = new Array(10, 20, 30);


for (let i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}

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

Property Meaning Example


[Link] Value of π (3.14159…) [Link] → 3.14159…
Math.E Euler’s number (2.718…) Math.E → 2.718…
Math.SQRT2 Square root of 2 Math.SQRT2 → 1.414…
Math.LN2 Natural log of 2 Math.LN2 → 0.693…

🔹 Common Math Methods


1. Rounding Numbers

[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)

2. Power and Roots

[Link](2, 3); // 8 (2³)


[Link](25); // 5 (√25)
4. Min and Max

[Link](3, 7, 1, 9); // 1
[Link](3, 7, 1, 9); // 9

5. Random Numbers

[Link](); // Random number between 0 and 1


[Link]([Link]() * 10); // Random number 0–9
[Link]([Link]() * 100) + 1; // Random number 1–100

Example 1: Random Number between 0 and 1

let num = [Link]();


[Link](num);
// Example output: 0.456789 (always between 0 and 1)

Example 2: Random Number between 1 and 10

let num = [Link]([Link]() * 10) + 1;


[Link](num);
// Example output: 7 (integer between 1 and 10)
Example: Random Number between Any Range (min–max)

function getRandom(min, max) {


return [Link]([Link]() * (max - min + 1)) + min;
}

[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

let today = new Date();

[Link]([Link]()); // Year (e.g., 2025)


[Link]([Link]()); // Month (0–11)
[Link]([Link]()); // Day of month (1–31)
[Link]([Link]()); // Day of week (0–6, Sunday=0)
[Link]([Link]()); // Hours (0–23)
[Link]([Link]()); // Minutes (0–59)
[Link]([Link]()); // Seconds (0–59)
[Link]([Link]());// Milliseconds (0–999)
[Link]([Link]()); // Timestamp (ms since 1 Jan 1970)
Q: Write a program in JavaScript to display digital clock showing HH:MM:SS.
<!DOCTYPE html>
<head>
</head>
<body>
<h1>Digital Clock</h1>
<p id="clock"></p>
</body>
<script>
function showTime(){
let now=new Date();
let hours=[Link]();
let minutes=[Link]();
let seconds=[Link]();
if(hours<10) hours="0"+hours;
if(minutes<10) minutes="0"+minutes;
if(seconds<10) seconds= "0"+seconds;
let time=hours+":"+minutes+":"+seconds;
[Link]("clock").innerHTML=time;
}
//update every 1 seconds
setInterval(showTime,1000);
showTime();
</script>
</html>
DOM(Document Object Model)
It is a programming interface for web documents (HTML or XML).
The browser creates a tree-like structure of the entire web page.
Each element (like <p>, <h1>, <div>, etc.) becomes a node/object that
JavaScript can access and manipulate.
The document is the root (grandparent).
Inside it are parents (like <html>, <body>).
Inside parents are children (like <h1>, <p>).
Each tag is connected just like family members in a tree structure.

<!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";

4. Modern Query Selectors

[Link](".text").innerHTML = "Changed using querySelector!";


[Link]("p")[0].[Link] = "20px";
🛠 Manipulating DOM

[Link] content
[Link](“demo").innerText = "DOM Updated!";

[Link] style
[Link](".text").[Link] = "red";

[Link] new element

let newPara = [Link]("p");


[Link] = "This is a new paragraph.";
[Link](newPara);

[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.

•When the event happens, the function runs automatically.


Example in real life:
•Event = Someone presses a doorbell.
•Event Handler = The bell rings.

Some common Events:


•Mouse Events → onclick, ondblclick, onmouseover, onmouseout
•Keyboard Events → onkeydown, onkeyup
•Form Events → onsubmit, onfocus, onblur
•Window Events → onload, onresize

Ways to Handle Events in JavaScript

Method 1: Inline Event Handling


Write JavaScript directly inside the HTML tag.

<button onclick="alert('Button clicked!')">Click Me</button>


Method 2: Using HTML Properties
Call a JavaScript function when the event occurs.

<!DOCTYPE html>
<html>
<body>

<h2>Event Handling Example</h2>


<button onclick="showMessage()">Click Me</button>

<script>
function showMessage() {
alert("Hello! You clicked the button.");
}
</script>

</body>
</html>
Method 3: Using addEventListener() (Best Practice)

This method keeps HTML and JS separate.

<!DOCTYPE html>
<html>
<body>

<h2>Event Listener Example</h2>


<button id="myBtn">Click Me</button>

<script>
[Link]("myBtn").addEventListener("click", function() {
alert("Button was clicked!");
});
</script>

</body>
</html>
Advantages of addEventListener():

•Cleaner code (HTML and JS are separate).

Common Events in JavaScript

Event Name Description


onclick When an element is clicked
ondblclick When double-clicked
onmouseover When mouse is moved over element
onmouseout When mouse leaves element
onkeydown When a key is pressed
onkeyup When a key is released
onload When page finishes loading
onsubmit When a form is submitted
Change Text on Click
<!DOCTYPE html>
<html>
<head>
<title>Event Handling Example</title>
</head>
<body>
<h1 id="heading">Hello Students!</h1>
<button id="changeBtn">Change Text</button>
<script>
// Select button and heading
let btn = [Link]("changeBtn");
let heading = [Link]("heading");

// Add event listener to button


[Link]("click", function() {
[Link] = "You just clicked the button!";
[Link] = "blue";
});
</script>
</body>
</html>
Example : Change Text Color on Hover
When you move the mouse over the text → it turns red.
When you move the mouse out → it turns black again.

<!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]();

// Clear old error messages


[Link]("nameError").innerText = "";
[Link]("emailError").innerText = "";

let isValid = true;


// Check Name field
if (name === "") {
[Link]("nameError").innerText = " * Name is required";
isValid = false;
}

// Check Email field


if (email === "") {
[Link]("emailError").innerText = " * Email is required";
isValid = false;
}
return isValid; // If false → form will not submit
}
[Link] a program in JavaScript to display digital clock showing HH:MM:SS.

[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] function in Java Script. Outline a JS function that takes 4 variables, a, b, c, d,


and prints true in an alert box if input a > input b and input c > input d. Else, print false in
an alert box.

[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.

It’s not a programming language, but a technique used in web development


to:
Send and receive data from a web server asynchronously — without reloading
the whole webpage.
Normally, when you fill a form or click a link, the browser reloads the whole
page to get new data.
But with AJAX, only part of the page updates — making websites faster and
more dynamic.

Example :
In [Link] results appear instantly — that’s AJAX at work!

The page doesn’t reload, but it fetches data in the background.


In this website page reload i.e AJAX not used

[Link]
XMLHttpRequest
Request
Client Response Server
(Browser)

1. User triggers an event 4. Server processes the request


(e.g., button click, typing in a search box)
[Link] creates a request 5. Server sends a response
(using XMLHttpRequest ) (usually in JSON or XML format)
3. Request is sent to the server
6. JavaScript updates the web page
dynamically (without reloading)
The XMLHttpRequest Object
The XMLHttpRequest object can be used to exchange data with a server
behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox, Edge (and IE7+), Safari, Opera)
have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Example

var xhttp = new XMLHttpRequest();


XMLHttpRequest Object Methods

open(method,url,async) Specifies the request

method: the request type GET or


POST
url: the file location
async: true (asynchronous) or false
(synchronous)

send() Sends the request to the server


Used for GET requests
XMLHttpRequest Object Properties
readyState Holds the status of the
XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is
ready
onreadystatechange Defines a function to be called
when the readyState property
changes
responseText Returns the response data as a string

responseXML Returns the response data as XML


data
Status Returns the status-number of a request
200: "OK“ (Request Successfully
Processed and sent back)
403: "Forbidden“ (The client
(browser or AJAX script) is not allowed
to access this resource.)
<!DOCTYPE html>
<html>
<body>
<p id="demo">Here we load data.</p>
<button onclick="loadData()">Click</button>
<script>
function loadData(){
var xhttp=new XMLHttpRequest();
[Link]=function(){
if([Link]==4 && [Link]==200){
[Link]("demo").innerHTML=[Link];
}
}
[Link]('GET',"[Link]",true);
[Link]();
}
</script>
</body>
</html>

[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.

It is the modern way of doing AJAX.

<!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.

It’s not a programming language, but a technique used in web development


to:
Send and receive data from a web server asynchronously — without reloading
the whole webpage.
Normally, when you fill a form or click a link, the browser reloads the whole
page to get new data.
But with AJAX, only part of the page updates — making websites faster and
more dynamic.

Example :
In [Link] results appear instantly — that’s AJAX at work!

The page doesn’t reload, but it fetches data in the background.


In this website page reload i.e AJAX not used

[Link]
XMLHttpRequest
Request
Client Response Server
(Browser)

1. User triggers an event 4. Server processes the request


(e.g., button click, typing in a search box)
[Link] creates a request 5. Server sends a response
(using XMLHttpRequest ) (usually in JSON or XML format)
3. Request is sent to the server
6. JavaScript updates the web page
dynamically (without reloading)
The XMLHttpRequest Object
The XMLHttpRequest object can be used to exchange data with a server
behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox, Edge (and IE7+), Safari, Opera)
have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Example

var xhttp = new XMLHttpRequest();


XMLHttpRequest Object Methods

open(method,url,async) Specifies the request

method: the request type GET or


POST
url: the file location
async: true (asynchronous) or false
(synchronous)

send() Sends the request to the server


Used for GET requests
XMLHttpRequest Object Properties
readyState Holds the status of the
XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is
ready
onreadystatechange Defines a function to be called
when the readyState property
changes
responseText Returns the response data as a string

responseXML Returns the response data as XML


data
Status Returns the status-number of a request
200: "OK“ (Request Successfully
Processed and sent back)
403: "Forbidden“ (The client
(browser or AJAX script) is not allowed
to access this resource.)
<!DOCTYPE html>
<html>
<body>
<p id="demo">Here we load data.</p>
<button onclick="loadData()">Click</button>
<script>
function loadData(){
var xhttp=new XMLHttpRequest();
[Link]=function(){
if([Link]==4 && [Link]==200){
[Link]("demo").innerHTML=[Link];
}
}
[Link]('GET',"[Link]",true);
[Link]();
}
</script>
</body>
</html>

[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.

It is the modern way of doing AJAX.

<!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

Scripting: Java script: Introduction, documents, forms, statements, functions, objects,


introduction to AJAX.

Networking: Internet Addressing, InetAddress, Factory Methods, Instance Methods, TCP/IP


, Client Sockets, URL, URL Connection, TCP/IP Server Sockets, Datagram.
Internet Addressing
Internet Addressing means assigning a unique address to each device on a network so that
data can be sent to the correct destination.
On the Internet, this is done using IP
Addresses.
Every device (computer, mobile, router, server) must have a unique IP address to
communicate.
🧩 Types of Internet Addressing
IP Addressing (Logical Addressing)
IP = Internet Protocol
Used to uniquely identify each device on a
Twonetwork.
versions:
IPv4 (32-bit) – older, still widely used
IPv6 (128-bit) – newer, replaces IPv4
🟦 IPv4 Address
32-bit address
Written as 4 decimal numbers, separated by dots
Example:[Link]
🟧 IPv6 Address
128-bit
Written in hexadecimal
Separated by colons
Example:
2001:0db8:85a3:0000:0000:8a2e:0370:7334

📍 MAC Address (Physical Address)

Assigned to hardware (network card)


48-bit (6 bytes)
Example: 34-12-98-AB-CD-11
InetAddress
InetAddress is a class in [Link] package used to represent:
IP address
Hostname
DNS lookup
Local machine address
Domain’s IP addresses (IPv4 & IPv6)
Java uses this class to perform internet addressing and network identification.

Why do we need InetAddress?


InetAddress helps in:
✓ Finding IP of a website
✓ Converting hostname → IP
✓ Getting local system IP
✓ Supporting multi-IP domains
✓ Used internally in Sockets, URL, Datagram
Factory methods of InetAddress class

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

An instance method in Java is a method that belongs to an object (instance) of a class

public String getHostName() it returns the host name of the IP address.


public String getHostAddress() it returns the IP address in string format.
[Link]
import [Link].*;
public class InetExample {
public static void main(String[] args) {
try {
InetAddress local = [Link]();
[Link]("Local Host: " + local);
[Link]("Host Name: " + [Link]());
[Link]("Host Address: " + [Link]());

InetAddress google = [Link]("[Link]");


[Link]("\nGoogle Host Name: " +
[Link]());
[Link]("Google IP: " + [Link]());

[Link]("\nAll Google IPs:");


InetAddress[] all = [Link]("[Link]");
for (InetAddress ip : all) {
[Link](ip);
}
} catch (Exception e) {
Program

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

Uniform Resource Locator


URL provides an intelligible form to uniquely identify resources on the internet.
URLs are universal, every browser uses them to identify resources on the web.
URL Contains 4 components.
1. Protocol ([Link]
2. Server name or IP address ([Link]
3. Port number which is optional (:8090)
4. Directory resource ([Link])

Protocol Port Number

[Link]

File Name or directory name


Server name or IP
Address
URL class methods

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.

URL obj=new URL(String urlSpecifier) throws MalformedURLException


URLConnection conn=[Link]();
URLConnection class methods

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.

There are two kinds of TCP/IP sockets classes in java.


[Link]/IP Server Socket for server
2. TCP/IP Client Socket for client
The Socket class is for clients, and ServerSocket class is for server.
[Link]/IP Server Socket :
A TCP/IP Server Socket in Java is a server-side
object that listens for TCP (Transmission Control Port Number
Server Socket

Protocol) connections from clients over an IP


ServerSocket 1010
network.
The Java code for creating socket at Server side.
In Java, it is created using the class: 80
S

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

[Link] a Socket for communication Computer


[Link] and receive data
[Link]/IP Client Socket :
A TCP/IP Client Socket in Java is a program that connects to a TCP server using [Link]

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);

// Step 4: Read client message


String message = [Link]();
[Link]("Client says: " + message);

// Step 5: Send reply to client


[Link]("Hello Client! Message received successfully.");
// Step 6: Close sockets
[Link]();
[Link]();
} catch (Exception e) {
[Link](e);
} }}
[Link]
import [Link].*;
import [Link].*;
import [Link];
public class TCPClient {
public static void main(String[] args) {
try {
// Step1: Connect to server running on localhost at port 5000
Socket socket = new Socket("localhost", 5000);
[Link]("Connected to Server.");
// Step2: Create I/O streams
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
// Step3: Scanner to take input from keyboard
Scanner sc = new Scanner([Link]);
[Link]("Enter your message to Server: ");
String msg = [Link]();

//Step4: Send message to server


[Link](msg);

// Step5: Read reply from server


String reply = [Link]();
[Link]("Server says: " + reply);
[Link]();
} catch(Exception e) {
[Link]();
} }}
UDP (User Datagrams Protocol)

A Datagram is a packet of information sent over a network using UDP (User Datagram
Protocol).
Features of Datagram / UDP:

Connectionless → No connection between client & server.


Fast → Less overhead than TCP.
No guarantee of delivery.
Packets (Datagrams) may arrive out of order, duplicate, or may be lost.
Used in:
• Video streaming
• Online gaming
Java Datagram Example (UDP Client & Server)
Program

Write a program to create Sender and Receiver for connectionless communication.


UDPServer .java UDPClient
import [Link].*; import [Link].*;
public class UDPServer { import [Link];
public static void main(String[] args) { public class UDPClient {
try { public static void main(String[] args) {
DatagramSocket ds = new DatagramSocket(5000); try {
[Link]("UDP Server running..."); DatagramSocket ds = new DatagramSocket();
byte[] buffer = new byte[1024]; Scanner sc = new Scanner([Link]);
// create Datagram Packet to receive data [Link]("Enter message to send: ");
DatagramPacket dp = new DatagramPacket(buffer, [Link]); String message = [Link]();
// Wait for client to send message byte[] data = [Link]();
[Link](dp);
//Extract message from packet // Send to localhost, port 5000
String message = new String([Link](), 0, [Link]()); InetAddress ip = [Link]("localhost");
[Link]("Client says: " + message); DatagramPacket dp = new DatagramPacket(data, [Link], ip, 5000);
Output [Link](dp);
[Link](); [Link](); Output
} catch (Exception e) { } catch (Exception e) {
[Link](); [Link]();
} }
} }
} }

You might also like