Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Parse search string into get variables

    I feel like I have been repeating this code lately, so I cleaned it up and am gonna show it here. This function returns an array (with hash names) containing all the get variables.
    Code:
    function parseGetVars() {
    	var getVars = new Array();
    	var qString = unescape(top.location.search.substring(1));
    	var pairs = qString.split(/\&/);
    	for (var i in pairs) {
    		var nameVal = pairs[i].split(/\=/);
    		getVars[nameVal[0]] = nameVal[1];
    		}	
    	return getVars;
    	}
    A simple page to test this looks like
    Code:
    <html>
    <head>
    <title>Test</title>
    
    <script>
    function parseGetVars() {
    	var getVars = new Array();
    	var qString = unescape(top.location.search.substring(1));
    	var pairs = qString.split(/\&/);
    	for (var i in pairs) {
    		var nameVal = pairs[i].split(/\=/);
    		getVars[nameVal[0]] = nameVal[1];
    		}	
    	return getVars;
    	}
    </script>
    </head>
    
    <body>
    <script>
    var g = parseGetVars();
    for (var i in g)
    	document.writeln(i+'='+g[i]+'<br>');
    </script>
    
    </body>
    
    </html>
    Hope this helps anyone...optimizations/comments are welcome!
    Last edited by beetle; 08-21-2002 at 06:16 PM.

  • #2
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Great minds think alike:
    add text to image in new window


  • #3
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Heh, so they do indeed

  • #4
    Regular Coder
    Join Date
    Jun 2002
    Location
    Atlanta, GA.
    Posts
    313
    Thanks
    0
    Thanked 0 Times in 0 Posts

    making them "real" variables

    Did you know when you create variables they become part of the window object? I used this fact to make your (very usefull) parseGetVars create real variables that can be used directly in a script.
    Code:
    function parseGetVars() 
    {
    	var qString = unescape(top.location.search.substring(1));
    	var pairs = qString.split(/\&/);
    	for (var i in pairs)
    	{
    		var nameVal = pairs[i].split(/\=/);
    		window[nameVal[0]] = nameVal[1];
    	}	
    }
    parseGetVars();
    If you place that code as the first code in the HEAD of your document then all the variables will be available to your scripts.
    -------------------------------------------------------------------------------
    Hers is a test (I created a putVars() to send the vars to the next page).
    Save this as index.html - it initially creates the vars 'aa' and 'bb'
    Code:
    <html>
    <head>
    <title>index.html - initialy creates the vars</title>
    <script>
    /********** Created here ***********/
    	aa=1;
    	bb=1;
    /***********************************/
    
    function putVars(url)
    {
    	var str = "?";
    	var i;
    	for(i=1 ; i<arguments.length-1 ; i++)
    		str+=(arguments[i] + "=" + window[arguments[i]] + "&");
    	str+=(arguments[i] + "=" + window[arguments[i]]);
    	url.href += str;
    }
    </script>
    </head>
    
    <body>
    <A HREF="#" onClick="alert(aa);return false" >Value of aa</A><br>
    <A HREF="#" onClick="alert(bb);return false" >Value of bb</A><br>
    <A HREF="#" onClick="aa++;return false" >aa = aa + 1 </A><br>
    <A HREF="#" onClick="bb++;return false" >bb = bb + 1 </A><br>
    <A HREF="#" onClick="bb = (parseInt(bb) + 2);return false" >aa = aa+2</A><br>
    <A HREF="#" onClick="bb = (parseInt(bb) + 2);return false" >bb = bb+2</A><br>
    <A HREF="index2.html" onClick="putVars(this, 'aa', 'bb');return true" >Put aa,bb</A><br>
    </body>
    </html>
    Save this next file as "index2.html" - it reads the vars and recreates them
    Code:
    <html>
    <head>
    <title>index2.html - reads the query string and re-creates the vars</title>
    
    <script>
    function parseGetVars() 
    {
    	var qString = unescape(top.location.search.substring(1));
    	var pairs = qString.split(/\&/);
    	for (var i in pairs)
    	{
    		var nameVal = pairs[i].split(/\=/);
    		window[nameVal[0]] = nameVal[1];
    	}	
    }
    parseGetVars();
    /*** You can now use the vars 'aa' and 'bb'***/
    status = "aa=" + aa + ":bb=" + bb;
    /********************************/
    function putVars(url)
    {
    	var str = "?";
    	var i;
    	for(i=1 ; i<arguments.length-1 ; i++)
    		str+=(arguments[i] + "=" + window[arguments[i]] + "&");
    	str+=(arguments[i] + "=" + window[arguments[i]]);
    	url.href += str;
    }
    </script>
    </head>
    
    <body>
    <A HREF="#" onClick="alert(aa);return false" >Value of aa</A><br>
    <A HREF="#" onClick="alert(bb);return false" >Value of bb</A><br>
    <A HREF="#" onClick="aa++;return false" >aa = aa + 1 </A><br>
    <A HREF="#" onClick="bb++;return false" >bb = bb + 1 </A><br>
    <A HREF="#" onClick="bb = (parseInt(bb) + 2);return false" >aa = aa+2</A><br>
    <A HREF="#" onClick="bb = (parseInt(bb) + 2);return false" >bb = bb+2</A><br>
    <A HREF="index2.html" onClick="putVars(this, 'aa', 'bb');return true" >Put aa,bb</A><br>
    </body>
    </html>

  • #5
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yes! I did. A good modification nonetheless. (oh, and the proper term for 'real' variables is 'global' )

    I kept the getVars array for my purposes as to not cause any variable conflicts.

    Here's an idea to extend it more...
    Code:
    function parseGetVars(prefix) 
    {
    	if (typeof prefix == 'undefined') prefix = '';
    	var qString = unescape(top.location.search.substring(1));
    	var pairs = qString.split(/\&/);
    	for (var i in pairs)
    	{
    		var nameVal = pairs[i].split(/\=/);
    		window[prefix + nameVal[0]] = nameVal[1];
    	}	
    }
    parseGetVars('get_');
    Now all my get variables are global, but prefixed by 'get_'. Of course, it's optional, so you can just leave it out.

  • #6
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts

    A "Real" fix

    I noticed that there is a tiny error in the logic of this script, that will only affect it when there is an equal sign as part of a value of one of the get variables. Here's the solution.
    Code:
    function parseGetVars() {
    	var getVars = new Array();
    	var qString = top.location.search.substring(1);
    	var pairs = qString.split(/\&/);
    	for (var i in pairs) {
    		var nameVal = pairs[i].split(/\=/);
    		getVars[unescape(nameVal[0])] = unescape(nameVal[1]);
    		}	
    	return getVars;
    	}
    Cheers
    Last edited by beetle; 09-12-2002 at 05:33 PM.
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  • #7
    Senior Coder
    Join Date
    Jun 2002
    Location
    41° 8' 52" N -95° 53' 31" W
    Posts
    3,660
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I kept the getVars array for my purposes as to not cause any variable conflicts.
    That's the only flaw I see in the improvement... I'm going to see how I can improve my code further to do the same thing while trying to avoid conflicts.... looks like we're all aiming for the perfect "querystring parsing script", eh?

    I think we're all spoiled by server-side scripting and want to force javascript to do the same for us client-side. Which is a good thing.

    Also, in which case (as beetle said), I would avoid making them global variables using "window" on principle... there may be cases where that would cause a conflict, but perhaps glenngv had the easiest solution to that in a recent post, which was adding something like Macromedia does with Dreamweaver to the beginning of the variable... i.e. he used GV_varname, whereas Macromedia uses MM_varname (I'm sure anyone who has looked at any dreamweaver-generated javascript is quite familiar with that!).

    I think it's better to request something and define it as a 'local variable' where requested to err on the safe side, otherwise.

    So I guess "GV_blah" (in this case meaning "Global Variable" instead of "Glenn Vergara"), although that may have been his original meaning (I have no idea) might be a near-perfect solution.
    Last edited by whammy; 12-12-2002 at 01:10 AM.
    Former ASP Forum Moderator - I'm back!

    If you can teach yourself how to learn, you can learn anything. ;)

  • #8
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    10,964
    Thanks
    0
    Thanked 236 Times in 233 Posts
    oh whammy I didn't realize that! What I meant with GV is my name. But having a double-meaning with Global Variable is indeed very cool

    Thanks for that

  • #9
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Didn't my post a couple up show how to make the global variables prefixed?
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  • #10
    Regular Coder
    Join Date
    Jun 2002
    Location
    Atlanta, GA.
    Posts
    313
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Beetle did provide a version that did prefix all the variables. If you look you can see where the getvars is called with a prefix. I think it is the best solution as I would like to be able to get my vars un prefixed (by the getvars routine that is) so I could use the putvars. (I am thinking of a page that keeps updating but passing the vars between each reload).

    Beetle, you then posted an update that fixed an error but you kept the getVars array.

    Combining what you posted I personally prefer this as the best solution
    Code:
    function parseGetVars(prefix) 
    {
    	if (typeof prefix == 'undefined') prefix = '';
    	var qString = top.location.search.substring(1);
    	var pairs = qString.split(/\&/);
    	for (var i in pairs)
    	{
    		var nameVal = pairs[i].split(/\=/);
    		window[prefix + unescape(nameVal[0])] = unescape(nameVal[1]);
    	}	
    }
    parseGetVars('get_');
    //parseGetVars('GV_'); // use this to prefix with GV_
    //parseGetVars(); //use this for no prefix
    I think this is the best because it allows a user to use this piece of code cut'n' paste and if there is a variable conflict you can just go back and add/change the prefix. (But this is just my personal opinion).

    Anyway, I think this is a great piece of code and is the easiest way I have seen of passing vars between pages.

  • #11
    Senior Coder
    Join Date
    Jun 2002
    Location
    41° 8' 52" N -95° 53' 31" W
    Posts
    3,660
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Oops, my bad - you did indeed! Definitely a very nice piece of work.

    Wish I had known how all this worked a couple of years ago...
    Former ASP Forum Moderator - I'm back!

    If you can teach yourself how to learn, you can learn anything. ;)

  • #12
    Senior Coder
    Join Date
    Jun 2002
    Location
    Nashua, NH
    Posts
    1,724
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Originally posted by whammy

    I think we're all spoiled by server-side scripting and want to force javascript to do the same for us client-side. Which is a good thing.
    LOL Whammy, that is why I implemented the same functionality as follows:
    Code:
    function obj_queryString()
    {
        qs=document.URL.substring(document.URL.indexOf('?')+1,document.URL.length);
        queries=qs.split(/\&/);
        for(i=0;i<queries.length;i++)
          { query=queries[i].split(/\=/);
            this[query[0]]=unescape(query[1]);
          }
    }
    queryString=new obj_queryString();
    Vladdy | KL
    "Working web site is not the one that looks the same on common graphical browsers running on desktop computers, but the one that adequately delivers information regardless of device accessing it"

  • #13
    Senior Coder
    Join Date
    Jun 2002
    Location
    41° 8' 52" N -95° 53' 31" W
    Posts
    3,660
    Thanks
    0
    Thanked 0 Times in 0 Posts
    My, that looks even shorter...
    Former ASP Forum Moderator - I'm back!

    If you can teach yourself how to learn, you can learn anything. ;)

  • #14
    Senior Coder
    Join Date
    Jun 2002
    Location
    Zwolle, The Netherlands
    Posts
    1,120
    Thanks
    2
    Thanked 31 Times in 31 Posts
    i have created a version that produces a 2D array with all the querystring parameters in it, the name in the [0] and the content in the [1] part. A search function to get the desired vaiable out is also available. I realize it is a bit more code, but the risc of variable conflicts is absolutely minimized. works fine for me
    I am the luckiest man in the world

  • #15
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    10,964
    Thanks
    0
    Thanked 236 Times in 233 Posts
    I think the best code is Vladdy's. No need for the global variables (nothing to worry about variable conflicts)
    ...although he could have used location.search instead of document.URL


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •