2

I'm noob to JavaScript and want to use Prototype JS Framework to get some URL parameters. Imagine I have the following URL on my current browser:

http://www.somewhere.com?param=abc

how can I get the value of 'param' using any function or utility of Prototype JS ?

Sal Prima
  • 1,412
  • 2
  • 18
  • 23
  • possible duplicate of [Get query string values in JavaScript](http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript) – Rob W Dec 29 '11 at 15:25

3 Answers3

11

Prototype.js DOES provide a utility:

uri.toQueryParams();
Scott
  • 111
  • 1
  • 2
4

Expanding on Scott's answer: to put the value of the URL variable 'param' into the javascript variable 'x' you would use Prototype like so:

x = document.URL.toQueryParams().param;
agamemnerd
  • 41
  • 1
4

You really don't need Prototype for this:

function get_param(param) {
   var search = window.location.search.substring(1);
   var compareKeyValuePair = function(pair) {
      var key_value = pair.split('=');
      var decodedKey = decodeURIComponent(key_value[0]);
      var decodedValue = decodeURIComponent(key_value[1]);
      if(decodedKey == param) return decodedValue;
      return null;
   };

   var comparisonResult = null;

   if(search.indexOf('&') > -1) {
      var params = search.split('&');
      for(var i = 0; i < params.length; i++) {
         comparisonResult = compareKeyValuePair(params[i]); 
         if(comparisonResult !== null) {
            break;
         }
      }
   } else {
      comparisonResult = compareKeyValuePair(search);
   }

   return comparisonResult;
}

var param_value = get_param('param'); //abc
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • hi jacob thank you for your reply, but i want to know is there any utility provided by Prototype js for this requirement ? – Sal Prima Dec 17 '10 at 04:36
  • @dprima There is no utility that does this that I know of. – Jacob Relkin Dec 17 '10 at 04:53
  • oh i see, thx jacob, both your answer and tim's below were true, but because you're the first, ill mark your answer as accepted – Sal Prima Dec 17 '10 at 06:18
  • It may be worth calling `decodeURIComponent` on `key_value[1]` and ideally on `key_value[0]` before comparing it to the param. – Mike Samuel Jan 03 '12 at 22:09
  • @MikeSamuel I refactored the entire function to be a whole lot cleaner. I provided the original answer to this question over a year ago, so this should be a lot better... Any comments on the updated code are welcome! :) – Jacob Relkin Jan 03 '12 at 22:47
  • @Jacob, looks correct. Valueless attributes are treated as having a value of `undefined` which seems reasonable: `get_param('foo') === undefined` when `location.search === '?foo'`. – Mike Samuel Jan 03 '12 at 22:52