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

56

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
Sign up to request clarification or add additional context in comments.

1 Comment

decodeURIComponent, not unescape, which will get +s and all non-ASCII characters wrong.
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 Comments

it is simply an IDEA that can go beyond itself... creating dynamic code rather than data.... i ♥ it...
Also, if you're going to inject PHP in to JS, this is just about the safest and CLEANest way to do it.
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 Comment

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),{});
5

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 Comments

you would want to be sure you escape out double quotes in the strings too ;) otherwise that's a security risk.
You mean var to = \" ... \"?
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 Comment

Your answer should contain an explanation of your code and a description how it solves the problem.
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)

Comments

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]);
    })();

Comments

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;
    }
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.