Friday, October 29, 2010

Simple way of passing values across web pages

By using simple java script and get method in HTML, values can be passed across web pages.

Page 1:
Lets create a simple html page "myname.html" with two text boxes for entering name.
<html>
<head>
</head>
<body>
<form name="theform" action="showname.html" method="get">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname"><br>
<input type="submit" value="Show">
</form>
</body>
</html>
Here get method is used to get the values from the text boxes and pass them to the action web page "showname.html".
 
Page 2:
Now let’s create a second html page "showname.html" which takes the values passed by "myname.html" web page.
<html>
<head>
<script type="text/javascript">
function getValue()
{
//First, we load the URL into a variable
var url = window.location.href;
//Next, split the url by the ?
var qparts = url.split("?");
//Check that there is a querystring, return "" if not
if (qparts.length == 0) { return ""; }
//Then find the querystring, everything after the ?
var query = qparts[1];
//Split the query string into variables(separates by &s)
var vars = query.split("&");
// Initialize the value with "" as default
var value = "";
// Iterate through vars, checking each one for varname
for (i=0;i<vars.length;i++)
{
// Split the variable by =, which splits name and value
var parts = vars[i].split("=");
// Load value into variable
value = value + " " + parts[1];
}
// Convert escape code
value = unescape(value);
// Convert "+"s to " "s
value.replace(/\+/g," ");
// Return the value
return value;
}
</script>
</head>
<body >
<h1>Hello,
<script type="text/javascript">
document.write(getValue());
</script>
</h1>
</body>
</html>
In the part 2 javascript method getValue() is the show maker. It does the job of getting the values passed by "myname.html" web page.

No comments:

Post a Comment