Saturday, June 27, 2026

DATA TRANSFER BETWEEN ONE PAGE TO AN OTHER PAGE USING JAVA SCRIPT

 You can transfer data from one HTML page to another using JavaScript in several ways. One of the simplest methods is by using URL Query String.

Example: Transfer Data Using Query String

Page 1 (index.html)

<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
<script>
function sendData() {
var name = document.getElementById("txtName").value;
var city = document.getElementById("txtCity").value;

if (name.trim() == "" || city.trim() == "") {
alert("Please fill all fields.");
return;
}

window.location.href = "display.html?name="
+ encodeURIComponent(name)
+ "&city="
+ encodeURIComponent(city);
}
</script>
</head>
<body>

<h2>Page 1</h2>

Name:
<input type="text" id="txtName"><br><br>

City:
<input type="text" id="txtCity"><br><br>

<button onclick="sendData()">Next</button>

</body>
</html>

Page 2 (display.html)

<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
<script>
function getData() {

var params = new URLSearchParams(window.location.search);

var name = params.get("name");
var city = params.get("city");

document.getElementById("lblName").innerHTML = name;
document.getElementById("lblCity").innerHTML = city;
}
</script>
</head>

<body onload="getData()">

<h2>Received Data</h2>

Name : <span id="lblName"></span><br><br>

City : <span id="lblCity"></span>

</body>
</html>

Output

Page 1

Name : Nilesh Gupta
City : Nagpur

[ Next ]

After clicking Next, the browser URL becomes:

display.html?name=Nilesh%20Gupta&city=Nagpur

Page 2

Received Data

Name : Nilesh Gupta

City : Nagpur

Another Method: Using localStorage

Page 1

<script>
function sendData() {

localStorage.setItem("Name", document.getElementById("txtName").value);
localStorage.setItem("City", document.getElementById("txtCity").value);

window.location = "display.html";
}
</script>

Page 2

<script>
window.onload = function () {

document.getElementById("lblName").innerHTML =
localStorage.getItem("Name");

document.getElementById("lblCity").innerHTML =
localStorage.getItem("City");

}
</script>

Common Methods to Transfer Data Between Pages

MethodBest Use Case
Query String (URLSearchParams)Small, non-sensitive data
localStorageData that should persist even after page refresh
sessionStorageData only for the current browser tab/session
CookiesSmall data shared across pages or sessions
Server-side (PHP, ASP.NET, Node.js, etc.)Secure or database-backed applications

For beginners, localStorage and Query String are the easiest and most commonly used methods in JavaScript.

No comments:

Post a Comment

DATA TRANSFER BETWEEN ONE PAGE TO AN OTHER PAGE USING JAVA SCRIPT

 You can transfer data from one HTML page to another using JavaScript in several ways. One of the simplest methods is by using URL Query Str...