Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the query string value and display it in my html page

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>");
like image 731
Venil Aravazhi Avatar asked Mar 27 '13 07:03

Venil Aravazhi


1 Answers

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;
}
like image 172
rab Avatar answered Nov 07 '22 16:11

rab