22

I suppose I could use PHP to access $_GET variables from JavaScript:

<script>
var to = $_GET['to'];
var from = $_GET['from'];
</script>
<script src="realScript" type="text/javascript"></script>

But perhaps it's even simpler. Is there a way to do it directly from JS?

9 Answers 9

55

Look at

window.location.search

It will contain a string like this: ?foo=1&bar=2

To get from that into an object, some splitting is all you need to do:

var parts = window.location.search.substr(1).split("&");
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
    var temp = parts[i].split("=");
    $_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}

alert($_GET['foo']); // 1
alert($_GET.bar);    // 2
1
  • 1
    decodeURIComponent, not unescape, which will get +s and all non-ASCII characters wrong.
    – bobince
    Commented Oct 19, 2009 at 0:33
11

Here's another idea:

<script type="text/javascript">

var $_GET = <?php echo json_encode($_GET); ?>;

alert($_GET['some_key']);
// or
alert($_GET.some_key);

</script>
2
  • 1
    it is simply an IDEA that can go beyond itself... creating dynamic code rather than data.... i ♥ it...
    – vinrav
    Commented Oct 13, 2015 at 2:29
  • 2
    Also, if you're going to inject PHP in to JS, this is just about the safest and CLEANest way to do it.
    – Phil
    Commented Nov 11, 2015 at 8:55
6

I know this topic is old, but I want to share my own ES6 solution for $_GET in JavaScript.

One Liner

window.$_GET = location.search.substr(1).split("&").reduce((o,i)=>(u=decodeURIComponent,[k,v]=i.split("="),o[u(k)]=v&&u(v),o),{});

Here is the MDN documentation on array.reduce(), arrow functions, the comma operator, destructuring assignment, and short-cicuit evaluation.

So, for a URL like google.com/webhp?q=foo&hl=en&source=lnt&tbs=qdr%3Aw&sa=X&ved=&biw=12 you've got an object:

$_GET = {
   q: "foo",
   hl: "en",
   source: "lnt",
   tbs: "qdr:w",
   sa: "X",
   ved: "",
   biw: "12"
}

and you can do things like $_GET.q or $_GET['biw'] to get what you need. Note that this approach replaces duplicated query parameters with the last-given value in the search string, which may be undesired/unexpected

URLSearchParams()

Now we also have URLSearchParams() in new browsers, which lets you do things like:

window.$_GET = new URLSearchParams(location.search);
var value1 = $_GET.get('param1');
1
  • Don't know if my instance was an edge case, but I found I had to use ".href" rather than ".search", e.g.: window.location.href.substr(1).split("&").reduce((o,i)=>(u=decodeURIComponent,[k,v]=i.split("="),o[u(k)]=v&&u(v),o),{}); Commented Jun 26, 2018 at 8:14
4

I suppose you were thinking this:

<script type="text/javascript">

    var to = "<?= $_GET['to']; ?>";
    var from = "<?= $_GET['from']; ?>";

</script>

...this would just be syntax-correction of your idea :)

2
  • you would want to be sure you escape out double quotes in the strings too ;) otherwise that's a security risk.
    – user19302
    Commented Oct 19, 2009 at 0:07
  • You mean var to = \" ... \"? Commented Oct 19, 2009 at 0:10
1
document.get = function (d1,d2,d3) {
var divider1 = (d1 === undefined ? "?" : d1);
var divider2 = (d2 === undefined ? "&" : d2);
var divider3 = (d3 === undefined ? "=" : d3);
var url = window.location.href; //the current url
var pget = url.split(divider1)[1]; //slit the url and assign only the part after the divider 1
var pppget = {}; //define the contenitor object
if (pget.search(divider2) > -1) { //control if there is variable other than the first (?var1=a&var2=b) the var2 in this example
    var ppget = pget.split(divider2); //split the divider2 
    for (i = 0;i==ppget.lenght; i++) { //start a for and stop it when i == at object length
        if (ppget[i].search(divider3) > -1) { //control if is an empty var 
            psget = ppget[i].split(divider3);//if is split in 2 part using divider 3
            pppget[psget[0]] = psget[1];//assign to the object the value of first element and for value the second value  ex {var1=a,...}  
        } else {//if is a empty var (?var1&...)
            pppget[ppget[i]] = "";//assign only the value of first element with value a blank string
        }
    }
} else {//if the url don't contain other variable 
    if (pget.search(divider3) > -1) { //control if is an empty var 
        var ppget = pget.split(divider3);//if is split in 2 part using divider 3
        pppget[ppget[0]] = ppget[1];//assign to the object the value of first element and for value the second value  ex {var1=a}  
    } else {//if is a empty var (?var1)
        pppget[pget] = "";//assign only the value of first element with value a blank string
    }
}
return pppget;
/* return the object 
 * the use of the function is like this $_GET=document.get()
 * echo $_GET[var]
 * or use custom divider the default is setted for php standard divider
 */};
1
  • 4
    Your answer should contain an explanation of your code and a description how it solves the problem. Commented Jan 14, 2015 at 18:24
0

As others have explained you can parse page URL from JS to get the variables.

You could also use AJAX in the page which submits the values. It really depends on what kind of information you're passing and then returning back to the user. (It's definitely not simpler or more direct way of doing it, just an alternative approach)

0

i use this one for Get request (like $_GET in php):

  var urlParams;
  (window.onpopstate = function () {
    var match,
          pl     = /\+/g,  Regex for replacing addition symbol with a space
           search = /([^&=]+)=?([^&]*)/g,
          decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
           query  = window.location.search.substring(1);
       urlParams = {};
       while (match = search.exec(query))
        urlParams[decode(match[1])] = decode(match[2]);
    })();
0
class Utils {
    static HTTP_GET(key){
        let map = this.HTTP_GET_ALL();

        if(map.has(key)){
            return map.get(key);
        }else {
            return null;
        }
    }

    static HTTP_GET_ALL(){
        let parts = window.location.search.substr(1).split("&");
        let map = new Map();

        for (let i = 0; i < parts.length; i++) {
            let temp = parts[i].split("=");
            map.set(decodeURIComponent(temp[0]), decodeURIComponent(temp[1]));
        }

        return map;
    }
}
0

From what I can see: the URLSearchParams function is a widely-available in-built function gives you to ability to get all of the current query parameters into a single object. You can then access those parameters either individually as a replacement to $_GET, or you can foreach loop over it to make it into an array.

/* Example - Accessing a property with using URLSearchParams in place of $_GET */

const params = new URLSearchParams(window.location.search);

// Expected Output: (string) "true"
console.log(params.get("is_the_cake_a_lie"));
/* Example - Creating a $_GET array using URLSearchParams */
const params = new URLSearchParams(window.location.search);
window.$_GET = {};

for (const [key, value] of params.entries()) {
    window.$_GET[key] = value;
}

// Expected Output: (object) { "is_the_cake_a_lie": "true" }, (string) "true"
console.log(window.$_GET, window.$_GET["is_the_cake_a_lie"]);

REF: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

Not the answer you're looking for? Browse other questions tagged or ask your own question.