0% found this document useful (0 votes)
18 views22 pages

Important Programs With Solutions

This document provides various JavaScript and AJAX programs demonstrating basic operations such as addition and subtraction of numbers, user-defined functions for calculating square and cube, and usage of math and string functions. It also covers date functions, array manipulations, and form validation techniques. Each section includes HTML and JavaScript code snippets to illustrate the concepts effectively.

Uploaded by

vibhavbhartiya13
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)
18 views22 pages

Important Programs With Solutions

This document provides various JavaScript and AJAX programs demonstrating basic operations such as addition and subtraction of numbers, user-defined functions for calculating square and cube, and usage of math and string functions. It also covers date functions, array manipulations, and form validation techniques. Each section includes HTML and JavaScript code snippets to illustrate the concepts effectively.

Uploaded by

vibhavbhartiya13
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
You are on page 1/ 22

UNIT-3

Basic programs on JavaScript and AJAX

Addition and Subtraction of 2 numbers by assigning values directly to variables


<html>
<head>
<script type="text/javascript">
document.write("HELLO ALL");
<!--Addition and Subtraction of 2 numbers by assigning values directly to variables -->
var n1=10, n2=20,c=0,d=0;
c=n1+n2;
d=n2-n1;
document.writeln("<br>Sum is="+c);
document.writeln("<br> Sub is="+d);
</script>
</head></html>

Addition and Subtraction of 2 numbers by assigning values to


variables dynamically at runtime without parsing
<html>
<head>
<script type="text/javascript">
<!--Addition and Subtraction of 2 numbers by assigning values to
variables dynamically at runtime without parsing-->
document.writeln("<h1> Addition without parsing!!</h1>");
var n1, n2,c;
n1=prompt("Enter first number:");
n2=prompt("Enter second number:");
c=n1+n2;
document.writeln("Sum is="+c);
</script>
</head></html>

Same as above but use of parseInt


<html> <head>
<script language="javascript">
<!--Addition and Subtraction of 2 numbers by assigning
values to variables dynamically at runtime without parsing-->
document.writeln("<h1> Addition with parsing!!</h1>");
var n1, n2,c;
<!--parseInt convert a string into integer-->
n1=parseInt(prompt("Enter first number:"));
n2=parseInt(prompt("Enter second number:"));
c=n1+n2;
document.writeln("Sum is="+c);
</script>
</head></html>

-- UDF to find Squre and Cube of a number--


<html><head>
<script type="text/javascript">
document.writeln("<h1> UDF-Squre and Cube!!!</h1>");
var a=parseInt(prompt("Enter any number"));
document.writeln("Squre of a number is:"+square(a));
document.writeln("<br><br>Cube of a number
is:"+cube(a));
function square(x)
{
var s=x*x;
return s;
}

function cube(c)
{
var cb=c*c*c;
return cb;
}
</script> </head></html>

=== Program on MATH FUNCTION===


<html><head>
<script type="text/javascript">
document.writeln("<h3> MATH FUNCTION!!</h3>");
document.writeln("<br>Min(10,7)=>>"+Math.min(10,7));
document.writeln("<br>Max(10,7)=>>"+Math.max(10,7));
document.writeln("<br>sqrt(16)=>>"+Math.sqrt(16));
document.writeln("<br>Abs(-10)=>>"+Math.abs(-10));
document.writeln("<br>Ceil: 5.8 and
5.1=>>"+Math.ceil(5.8)+" and:"+ Math.ceil(5.1));
document.writeln("<br>Round: 5.8 and
5.1=>>"+Math.round(5.8)+" and:"+ Math.round(5.1));
document.writeln("<br>Pow(5,2): =>>"+Math.pow(5,2));
document.writeln("<br>Sin(90): =>>"+Math.sin(90));
document.writeln("<br>Cos(0): =>>"+Math.cos(0));
document.writeln("<br>Tan(45): =>>"+Math.tan(45));
document.writeln("<br>Log(2.71): =>>"+Math.log(2.71));
</script> </head></html>
<html><head>
<script type="text/javascript">
document.writeln("<h3> STRING FUNCTION!!</h3>");
//var s=prompt("Enter any sring/name:");
var s="Abhineet Maitrey";
document.writeln("<br> s.toLowerCase=>"+s.toLowerCase());
document.writeln("<br> s.toUpperCase=>"+s.toUpperCase());
document.writeln("<br> s.concat=>"+s.concat("Kunj"));
document.writeln("<br> s.charAt(2)=>"+s.charAt(2));
document.writeln("<br> s.subStr(4,4)=>"+s.substr(4,4));
document.writeln("<br> s.indexOf('n')=>"+s.indexOf('n'));
document.writeln("<br> s.lastIndexOf('t')=>"+s.lastIndexOf('t'));
document.writeln("<br> s.length=>"+s.length);
</script> </head></html>

===DATE FUNCTIONS===
===DATE FUNCTIONS===
(1) By default, JavaScript will use the browser's time zone and display a date
as a full text string:
<html><body>
<h2>Using new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
//or
document.write(d);
</script></body></html>

(2) Display Date and Time by formatting into string


<html><body>
<h2>Using new Date()</h2>
<p id="demo"></p>
<script>
//Complete Date and Time
const d = new Date();
document.getElementById("demo").innerHTML = d;
var dt=d.toDateString(); // get the date as a string
var t=d.toLocaleTimeString();// get the time as a string
document.write("<br> Date=:"+dt);
document.write("<br> Time=:"+t);
</script></body></html>

(3) Same as above but display date, month, year, hour, minutes, seconds
separately
<html> <body>
<h3>Using new Date()</h3>
<script>
const now = new Date();
document.write("<br>Current date and time: " + now);
document.write("<br>Year: " + now.getFullYear()); // Get current year
document.write("<br>Month: " + (now.getMonth() + 1)); // Get the current month
(0-11, so +1)document.write("<br>Day: " + now.getDate()); // Get the current day
document.write("<br>Hours: " + now.getHours()); // Get current hours
document.write("<br>Minutes: " + now.getMinutes()); // Get current minutes
document.write("<br>Seconds: " + now.getSeconds()); // Get current seconds
</script> </body> </html>

(4) Same as above but display date, month, year as: dd/mm/yyyy
And hour, minutes, seconds as: hh:mm:ss

<html>
<body>
<h3>Using new Date()</h3>
<script>
var now = new Date();
document.write("<br>" + now);
y=now.getFullYear();
m=(now.getMonth() + 1); d=now.getDate();
document.write("<br><br><B> Today's date:"+d+"/"+m+
"/"+y);
h=now.getHours();
min=now.getMinutes();
sec=now.getSeconds();
document.write("<br><br><b>" +h+":"+min+":"+sec);
</script> </body> </html>

ARRAY FUNCTIONS

(1) All the Array Functions


<html> <body>
<h3>JavaScript Array Functions</h3>
<script>
// Array creation
const fruits = ["Apple", "Banana", "Mango"];
document.write("Initial Array: " + fruits + "<br>");

// Access elements of an array


document.write("First element: " + fruits[0] + "<br>");
document.write("Second element: " + fruits[1] + "<br>");

// Add an element to the end of the array (push)


fruits.push("Orange");
document.write("After push (Add Orange): " + fruits + "<br>");

// Remove the last element from the array (pop)


fruits.pop();
document.write("After pop (Remove last element): " + fruits + "<br>");

// Add an element to the beginning of the array (unshift)


fruits.unshift("Grapes");
document.write("After unshift (Add Grapes to the beginning): " + fruits + "<br>");

// Remove the first element from the array (shift)


fruits.shift();
document.write("After shift (Remove first element): " + fruits + "<br>");

// Check if an element exists in the array (includes)


document.write("Does the array include 'Banana'? " + fruits.includes("Banana") + "<br>"); // true
document.write("Does the array include 'Grapes'? " + fruits.includes("Grapes") + "<br>"); // false

// Find the index of an element in the array (indexOf)


document.write("Index of 'Mango': " + fruits.indexOf("Mango") + "<br>"); // 2

// Sort the array alphabetically (sort)


fruits.sort();
document.write("Sorted Array: " + fruits + "<br>");

// Reverse the array (reverse)


fruits.reverse();
document.write("Reversed Array: " + fruits + "<br>");

// Concatenate two arrays (concat)


const vegetables = ["Carrot", "Potato"];
const combinedArray = fruits.concat(vegetables);
document.write("After concat (Combine fruits and vegetables): " + combinedArray + "<br>");

// Slice a portion of the array (slice)


const slicedArray = combinedArray.slice(1, 4);
document.write("Sliced Array (from index 1 to 4): " + slicedArray + "<br>");

// Splice the array (Add/Remove elements) (splice)


combinedArray.splice(2, 1, "Tomato");
document.write("After splice (Replace element at index 2 with 'Tomato'): " + combinedArray + "<br>");

// Find an element based on a condition (find)


const numbers = [5, 12, 8, 130, 44];
const firstLargeNumber = numbers.find(num => num > 10);
document.write("First number greater than 10: " + firstLargeNumber + "<br>"); // 12

// Filter elements based on a condition (filter)


const filteredNumbers = numbers.filter(num => num > 10);
document.write("Numbers greater than 10: " + filteredNumbers + "<br>"); // [12, 130, 44]
// Map over the array (map)
const doubledNumbers = numbers.map(num => num * 2);
document.write("Doubled Numbers: " + doubledNumbers + "<br>"); // [10, 24, 16, 260, 88]

// Reduce the array to a single value (reduce)


const sumOfNumbers = numbers.reduce((acc, curr) => acc + curr, 0);
document.write("Sum of Numbers: " + sumOfNumbers + "<br>"); // 199

// Check if all elements meet a condition (every)


const allAboveFour = numbers.every(num => num > 4);
document.write("Are all numbers greater than 4? " + allAboveFour + "<br>"); // true

// Check if at least one element meets a condition (some)


const anyNegativeNumber = numbers.some(num => num < 0);
document.write("Is there any negative number? " + anyNegativeNumber + "<br>"); // false

</script> </body> </html>

The reduce() method takes an array and reduces it to a single value by applying a function (like addition) to each
element in the array.
How reduce() works:
1. It starts with an initial value (in this case, 0).
2. It iterates over the array, applying a function that takes two arguments:
o acc (accumulator): This is the running total, which starts with the initial value.
o curr (current value): This is the current element of the array during each iteration.
3. It updates the accumulator with the result of the function applied to the current element.

Explaination:
num => num > 10:

 num is just a temporary name (a placeholder) that represents each number in the numbers array.
 As find() goes through the array, it looks at each number one by one, and for each number, it temporarily
assigns that value to num.
 Condition (num > 10): The part after the => is a condition that checks if the current number (represented
by num) is greater than 10.
2) Accessing all ements of an Array

<html><head><title>Looping Through Array</title></head>


<body>
<script>
// Array creation
var stud = ["Avi", "Beena", "Mani", "Om"];
// Looping through array using for loop
document.write("<b>List of Students=>></b><br>");
for (var i = 0; i < stud.length; i++) {
document.write("Stud-"+i+"="+stud[i] + "<br>");
}
</script></body></html>

3) To display Duplicate enteries in array and then Unique numbers from an Array

<html><head><title>Remove Duplicates</title></head>
<body>
<script>
// Array with duplicates
var nums = [1, 2, 2, 3, 4, 4, 5];
// To display original array with duplicate values:
document.write("Original Array Content=>");
for(var i=0; i<nums.length; i++)
{
document.write(nums[i]+",");
}
// Array to hold unique numbers
var unique = [];

// Loop through the original array


for (var i = 0; i < nums.length; i++) {
// Check if the number is not already in unique
var found = false;
for (var j = 0; j < unique.length; j++) {
if (nums[i] === unique[j]) {
found = true; // Mark as found
break; // Exit inner loop
}
}
// If not found, add to unique
if (!found) {
unique.push(nums[i]);
}
}

// Display unique numbers


document.write("<br><br>Unique numbers: " + unique);
</script> </body> </html>

VALIDATIONS

(1) Validation using Form and its Elements


<html><head>
<title>Simple Registration Form Validation</title></head>
<body>
<h3>Registration Form</h3>
<form id="registrationForm">
Name: <input type="text" id="name"><br><br>
Email: <input type="text" id="email"><br><br>
Password: <input type="password" id="password"><br><br>
Confirm Password: <input type="password" id="confirmPassword"><br><br>
Age: <input type="number" id="age"><br><br>
<input type="button" value="Submit" onclick="validateForm()">
</form>
<h3>Validation Results:</h3>
<div id="result"></div>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var confirmPassword = document.getElementById('confirmPassword').value;
var age = document.getElementById('age').value;
var result = "";

// Name validation
if (name === "") {
result += "Name cannot be empty.<br>";
} else {
result += "Name is valid.<br>";
}

// Email validation (simple regex)


const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (email === "") {
result += "Email cannot be empty.<br>";
} else if (!email.match(emailPattern)) {
result += "Invalid email format.<br>";
} else {
result += "Email is valid.<br>";
}

// Password validation
if (password === "") {
result += "Password cannot be empty.<br>";
} else if (password.length < 6) {
result += "Password must be at least 6 characters long.<br>";
} else {
result += "Password is valid.<br>";
}

// Confirm Password validation


if (confirmPassword === "") {
result += "Confirm password cannot be empty.<br>";
} else if (password !== confirmPassword) {
result += "Passwords do not match.<br>";
} else {
result += "Passwords match.<br>";
}

// Age validation
if (age === "") {
result += "Age cannot be empty.<br>";
} else if (age < 18) {
result += "You must be 18 or older.<br>";
} else {
result += "Age is valid.<br>";
}

document.getElementById('result').innerHTML = result;
}
</script> </body> </html>
the regex ^[^ ]+@[^ ]+\.[a-z]{2,3}$ checks if a given string matches the general structure of an email address.
Specifically, it verifies that:
 The email starts with one or more characters (excluding spaces).
 It contains an @ symbol.
 It follows with one or more characters (excluding spaces).
 It includes a . (dot).
 It ends with a TLD that is 2 to 3 lowercase letters.
Example Matches
 Valid Emails:
o [email protected]
o [email protected]
o [email protected]

(2) Validation using Table and Form Elements


<html>
<head> <title>Registration Form with Table</title></head>
<body>
<h2>Registration Form</h2>
<table border="1" bgcolor="cyan">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name"></td> </tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" id="email"></td> </tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" id="password"></td> </tr>
<tr>
<td><label for="confirmPassword">Confirm Password:</label></td>
<td><input type="password" id="confirmPassword"></td> </tr>
<tr>
<td><label for="age">Age:</label></td>
<td><input type="number" id="age" /></td> </tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="Submit" onclick="validateForm()"> </td> </tr>
</table>

<h3>Validation Results:</h3>
<div id="result"></div>

<script>
function validateForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirmPassword').value;
const age = document.getElementById('age').value;

let result = "";

// Name validation
if (name === "") {
result += "Name cannot be empty.<br>";
} else {
result += "Name is valid.<br>";
}

// Email validation (simple regex)


const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (email === "") {
result += "Email cannot be empty.<br>";
} else if (!email.match(emailPattern)) {
result += "Invalid email format.<br>";
} else {
result += "Email is valid.<br>";
}

// Password validation
if (password === "") {
result += "Password cannot be empty.<br>";
} else if (password.length < 6) {
result += "Password must be at least 6 characters long.<br>";
} else {
result += "Password is valid.<br>";
}

// Confirm Password validation


if (confirmPassword === "") {
result += "Confirm password cannot be empty.<br>";
} else if (password !== confirmPassword) {
result += "Passwords do not match.<br>";
} else {
result += "Passwords match.<br>";
}

// Age validation
if (age === "") {
result += "Age cannot be empty.<br>";
} else if (age < 18) {
result += "You must be 18 or older.<br>";
} else {
result += "Age is valid.<br>";
}

document.getElementById('result').innerHTML = result;
}
</script></body></html>
EVENT HANDLING

== Program on event handling functions: onload, onsubmit, onBlur, onKeyDown, onChange,


onDblClick, onClick, onmousemove===
<html>
<body onLoad='alert("JavaScript Event Handling")'>
<h3 align="center">Handling Events</h3><br>
<form name="frm1" onsubmit='alert("SUBMIT BUTTON PRESSES!!!")'><br>
onBlur Event:<input type="text" value="Click Here" onBlur='alert("Not Clear!!")'><br>
onKeyDown Event:<input type =text" value="Click Here" onKeyDown='alert("KeyDown
Event!!!")'><br>
onChange Event:<input type="text" value="click here" onChange='alert("Content
Changed!!!")'><br>
onDblClick Event:<input type ="button" value=" Double Click Here" ondblClick='sum()'><br>

onClick Event:<input type ="button" value="Click Here" onClick='sub()'><br>


onmousemove Event:<input type="button" name="btn" value="Place Here"
onmousemove="mm(this)"><br>
onSubmit Event: <input type="submit" value="SUBMIT"><br>

<script>
function sum()
{
var a=10, b=20,c=0;
c=a+b;
alert("Sum:"+c);
}

function sub()
{
var a=10, b=20,c=0;
c=b-a;
alert("Subtraction:"+c);
}
function mm(btn)
{
btn.style.backgroundColor = "cyan"; }
</script>
</body></html>
Window Events
== Progam on Window methods: Alert, Prompt, Confirm, open, close
<html>
<body onload='alert("JavaScript window Event Handling")'>
<input type="button" value="New Window" onclick="window.open('js2.html', 'login',
'width=250,height=200')">

<!-- This won't close the main window but would work for windows opened via JavaScript -->
<input type="button" value="Close" onclick="window.close()">
</body>
</html>
In the window.open function, the second parameter 'login' is the name of the new window you
are opening. It acts like an identifier for the new window. Here's what it does:
 If you open multiple windows using the same name ('login'), each new call to
window.open with that name will reuse the same window instead of opening a new one.
 You can give it any meaningful name or leave it empty ('') if you don't need to reference
the window later.
Most modern browsers have restrictions on closing windows. A window can only be closed by
window.close() if:
1. It was opened by JavaScript (e.g., using window.open()).
2. You can't close a window that wasn't opened using window.open() (like the main window
or windows opened manually by the user).
DOM
DOM (Document Object Model) operations in JavaScript allow us to interact with and manipulate the
structure, style, and content of web pages. Let's go through some common DOM operations, with a
simple example to illustrate each operation:

1) ===== To display all tags used in Wep Page======


<html><head><title>Display All Tags</title>
<script>
function show() {
var wpelem = ""; // Start with an empty string
var allElements = document.getElementsByTagName('*'); // Get all elements
for (var i = 0; i < allElements.length; i++) {
wpelem += "<br>" + allElements[i].tagName; // Add each tag name
}
document.getElementById('pmsg').innerHTML += wpelem; // Set the content once after loop
}
</script>
</head>
<body onload="show()">
<p id="pmsg">Various tags used in this web document are:</p>
</body> </html>

2) To access content of any element, here example-h1(Accessing


Elements)
<html> <head> <title>Accessing Elements Example</title>
</head>
<body>
<h1 id="h1title">Hello All in JavaScript!</h1>

<script>
// Access the Element by ID
var title = document.getElementById('h1title');
document.write ("Accessing Heading 1 contents::<br>"+title.textContent);
//title.textContent accesses the text inside the paragraph element.
</script> </body> </html>
3) To modify content of any element, here example-h1(Modifying
Elements)

<html> <head>
<title>Modifying Content Example</title> </head>
<body>
<h1 id="h1title">Welcome to JavaScript!!!</h1>

<script>
// Access the h1 element by ID
var title = document.getElementById('h1title');

// Store and display the original content


var originalContent = title.textContent;
document.write("Original h1 content: " + originalContent + "<br>");

// Modify the h1 content


title.textContent = 'Welcome to DOM!';

// Display the modified content


document.write("Modified h1 content: " + title.textContent);
</script> </body> </html>

4) To create a new paragraph element and add to <div> (Creating and


Appending New Elements)
<html> <head> <title>Creating Elements Example</title> </head>
<body>
<div id="container"></div>
<script>
// To make new paragraph element
var newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph added using DOM operations.';
// Add this new created paragraph to DIV of the page
var container1 = document.getElementById('container');
container1.appendChild(newParagraph);
</script> </body> </html>

Explanation: using createElement('p') we made new paragraph and appendChild()


added this new child to <div>

5) To remove a Paragraph<p> element (Removing Elements)

<html> <head> <title>Removing Elements Example</title> </head>


<body>
<p id="rem-this">My First Paragraph!!!</p>
<script>
var para = document.getElementById('rem-this');
document.write("<br>Paragraph is:"+para.textContent);
document.write("<br> This Paragraph will be removed soon!");
para.remove();
document.write("<br>Paragraph is removed");
</script> </body> </html>

Explanation: Use remove() method to remove <p> element from page.


6) To change the styles of the element (Changing Styles)
<html> <head> <title>Changing Styles Example</title> </head>
<body>
<h1 id="h1title">Change My Color</h1>
<script>
var title = document.getElementById('h1title');
title.style.color = 'blue';
</script> </body> </html>

Explanation: Using style.color property to change the colour of <h1> to "blue" colour.
7) To use event handler when button is clicked ( Handling Events)
<html><head> <title>Handling Events Example</title></head>
<body>
<button id="my-button">Click Me!</button>
<script>
// Use of event listener on the Button click
var button = document.getElementById('my-button');
button.addEventListener('click', function() {
alert('Button was clicked!');
});
</script> </body> </html>

Error Handling/ Exception Handling


(1) Try, catch, throw. Program for Temperature conversion
<html><head> <title>Temperature Conversion</title>
<script>
function convertTemperature() {
var userInput = prompt("Enter temperature in Celsius:");

try {
// Check if the input is a valid number
if (isNaN(userInput) || userInput.trim() === "") {
throw new Error("Invalid input! Please enter a valid number.");
}

var celsius = parseFloat(userInput); // Parse the input to a float


var fahrenheit = (celsius * 9/5) + 32; // Convert Celsius to Fahrenheit

alert("Temperature in Fahrenheit: " + fahrenheit.toFixed(2)); // Display the converted


temperature
} catch (error) {
alert(error.message); // Show the error message
} finally {
// This block executes regardless of whether an error occurred
console.log("Temperature conversion completed."); // Log completion in console
}
}
</script>
</head>
<body>
<h2>Temperature Conversion</h2>
<input type="button" value="Convert Temperature" onclick="convertTemperature()">
</body>
</html>

(2) Check for age.


<html><head> <title>Age Validation</title>
<script>
function validateAge() {
var userInput = prompt("Enter your age:");
try {
if (isNaN(userInput) || userInput.trim() === "") {
throw new Error("Invalid input! Please enter a valid number.");
}

var age = parseInt(userInput);

if (age < 1 || age > 120) {


throw new Error("Age must be between 1 and 120.");
}
alert("Your age is valid: " + age);
} catch (error) {
alert(error.message);
} finally {

document.write("Age validation completed.");


}
}
</script> </head>
<body>
<h2>Age Validation</h2>
<input type="button" value="Check Age" onclick="validateAge()">
</body> </html>
AJAX
Fetch data from a text file using AJAX

(1) Create the HTML File


Step 1: Create an HTML file called index.html with the following code:

(2) Create the Data File


Step 2: Create a text file called data.txt in the same directory as your HTML file. Add
some sample text to it, like this:

(3) Run a Local Server


Step 3:
To run AJAX successfully, serve the HTML file through a local server.
1. Using Python:
o If you have Python installed, you can easily run a local server.
o Open your terminal/command prompt.
o Navigate to the directory where your files are located.
 Run the following command:
For Python 3:
c:\practice\JS>python -m http.server 8000

Step 4:
Access the Program
 Open your web browser.
 Go to http://localhost:8000
 Click the "Load Data" button and text from data.txt displayed on the page.
File 1: Index.html
<html> <head>
<title>AJAX Example</title>
<script>
function loadData() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.txt', true);
xhr.onload = function ()
{
if (xhr.status === 200)
{
document.getElementById('content').innerText = xhr.responseText;
}
else
{
document.getElementById('content').innerText = 'Error loading data';
}
};

xhr.send();
}
</script> </head>

<body>
<h1>AJAX Example</h1>
<button onclick="loadData()">Load Data</button>
<p id="content">Data will appear here...</p>
</body> </html>

File 2: Data.txt
Hello, this is data fetched using AJAX!

Output:

Explanation:
var xhr = new XMLHttpRequest(); : a new XMLHttpRequest object named xhr is
created, which allows us to send and receive data from a server.
 xhr.onreadystatechange = function() { ... }: This sets up a function that will run
whenever the readyState of xhr changes. The readyState tells us what stage the
request is in.
 if (xhr.readyState === 4 && xhr.status === 200) { ... }: This checks if the request
is complete (readyState === 4) and was successful (status === 200). If both
conditions are true, it means we got a valid response from the server.
 document.getElementById("result").innerText = xhr.responseText;: This line
updates the paragraph with the ID result to show the data we received from the
server (stored in xhr.responseText).
 xhr.open("GET", "data.txt", true);: This prepares the request. We specify that we
want to send a GET request to data.txt . The true means we want to perform the
request asynchronously
 xhr.send(): This sends the request to the server.
 document.getElementById("loadButton").onclick = loadData;: This sets up an
event listener for the button. When the button is clicked, it calls the loadData
function to load the data.

When the data is successfully fetched, it is displayed in the paragraph with the ID result.

To practice:
1. Create a function using the “function” keyword that takes a String as an argument & returns the
number of vowels in the string. Create an array function to perform the same task
2- For a given array of numbers, print the square of each value using the forEach loop.
3- We are given array of marks of students. Filter out of the marks of students that scored 90+.
4- For a given array with marks of students -> [85, 97, 44, 37, 76, 60]. Find the average marks of the
entire class.
5- Create an array to store companies -> “Bloomberg” , “Microsoft” , “Uber” , “Google” , “IBM” ,
“Netflix” a. Remove the first company from the array b. Remove Uber & Add Ola in its place c. Add
Amazon at the end.
6- Get user to input a number using prompt(“Enter a number: ”). Check if the number is a multiple of
5 or not
7- Write a code which can give grades to students according to their scores:
 80-100, A
 70-89, B
 60-69, C
 50-59, D
 0-49, F
8- Write a program to implement a basic AJAX request where the client sends a name to the server,
and the server responds with a greeting message.
9- Write a program to submit a form using AJAX, where the data is sent to the server, and the response
(e.g., "Form submitted successfully!") is displayed without refreshing the page.
OR
Implement a file upload feature using AJAX. The user should be able to upload an image without
reloading the page, and the uploaded image should be displayed on the page once the upload is
successful.

You might also like