Link to home
Start Free TrialLog in
Avatar of ITsolutionWizard
ITsolutionWizardFlag for United States of America

asked on

javascript get query string

I have a response page like
response.html?total=2&firstname1=john&firstname2=mary or
response.html?total=1&firstname=sam

we are not sure how many we will get. but I just need a way in javascript/jquery to capture all of the query string. and shown
into alert()

how can i do that?
Avatar of Big Monty
Big Monty
Flag of United States of America image

try using this function:

function getParameterByName(name) {
    var url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Open in new window


alert( getParameterByName( 'queryStringName' ) );
Avatar of ITsolutionWizard

ASKER

What name I suppose to put in ?
I need to get all names that I may not even know in advance
can you use jquery?
this might do the trick:

function getQueryVariable()
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               alert( pair( 0 ] + ' = ' + pair[ 1 ] );
       }
       return(false);
}

Open in new window

I'm not sure what your question is. But it almost sounds as if you're struggling with the unknown quantity of names and creating variable names for each one. You could list the names as a group, separated by pipe characters.
response.html?firstnames=john|mary|george|susan 

Open in new window

Then you could alert the list of names as a group.
alert(window.location.search.substr(12).replace('|',', ','g') );

Open in new window

It would help if you could explain your objective a little more. URL query strings are intended to send information to the backend to be processed by the server using something like PHP or .NET. It is rare that javascript would be concerned with these.
Big Monty: Work thank. but now it keeps opening alert....is it possible to get all in one alert box?
ASKER CERTIFIED SOLUTION
Avatar of Big Monty
Big Monty
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
big monty: work and have another one if you have time for helps
glad I could help :)

go ahead and post it, then message me a link to it, if i have time this evening i'll have a look