After redirecting to home.html page, i can see the querystring values which i had given in the previous page.
Home.html?FirstName=dd&LastName=ee&smtButton=Submit
And am getting the result as:
firstname = undefined
lastname = undefined
age = undefined
Could anyone help me to solve this?
JS:
function getParams() {
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx + 1, document.URL.length).split('&');
for (var i = 0; i < pairs.length; i++) {
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
Inside your function function getParams()
you are declared variable var params = new Array();
, I think this makes confusion for you
if a match is found , you assigned url param like params[nameVal[0]] = nameVal[1];
, this actually not adding value into array object. so params.length
is 0 .but it will works as array is instance of object .. ie params instanceof Object
is true
so change into basic object .. to avoid confusion
function getParams() {
var idx = document.URL.indexOf('?');
var params = {}; // simple js object
.. here goes other code
}
and object key is case sensitive, so FirstName
will work ..
firstname = unescape(params["FirstName"]);
to print all values try this
params = getParams();
for( var i in params ){
console.log( i , params[i] );
}
it will print
FirstName dd
LastName ee
smtButton Submit
and I have modified your getParams code
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With