98

How do I simply get GET and POST values with JQuery?

What I want to do is something like this:

$('#container-1 > ul').tabs().tabs('select', $_GET('selectedTabIndex'));
A.L
  • 10,259
  • 10
  • 67
  • 98
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

14 Answers14

176

For GET parameters, you can grab them from document.location.search:

var $_GET = {};

document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

    $_GET[decode(arguments[1])] = decode(arguments[2]);
});

document.write($_GET["test"]);

For POST parameters, you can serialize the $_POST object in JSON format into a <script> tag:

<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;

document.write($_POST["test"]);
</script>

While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:

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

Note: You'll need PHP version 5 or higher to use the built-in json_encode function.


Update: Here's a more generic implementation:

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

var $_GET = getQueryParams(document.location.search);
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
  • 3
    Your extraction method doesn’t consider arguments with no value (”?foo&bar=baz“ => {foo:"", bar:"baz"}). – Gumbo Feb 05 '09 at 15:01
  • 1
    Nice catch Gumbo! The = in the regex should be made optional: ...snip...(?:=([^&]*))?&?)/g – Ates Goral Feb 05 '09 at 16:18
  • 1. Your first GET example doesn't seem to work for me. 2. In your update, your function name has a typo in it – Jake Wilson Oct 04 '09 at 02:36
  • Have you tried running that in safari or chrome? It creates an infinite loop and crashes the browser. Try it with something as simple as "?p=2" – MrColes Mar 08 '11 at 21:12
  • @MrColes: Yikes. It has been a while since I wrote this. Since then, I've discovered that Webkit doesn't update the internal position counter of the RegExp object when it is used as a literal. I'll update my answer with the fix. – Ates Goral Mar 08 '11 at 21:38
  • I don't think this can match arrays sent via GET. – funforums Jun 18 '14 at 11:20
  • @funforums Yup, this implementation doesn't attempt to support arrays. Besides, an array can be encoded in a URL in a number of different ways. – Ates Goral Jun 18 '14 at 15:27
  • @AtesGoral That's a pity, because the current implementation already can support arrays in at least a single way, if it did push into a result array instead of making a variable assignment in the loop. I have a working modification for this. Do you think i should edit it? – funforums Jun 18 '14 at 16:32
  • This is a beautiful piece of code, thank you so much for this! – Edmund Rojas Mar 15 '15 at 14:39
  • There is no mention of PHP in the OP's question. – Mark W Jan 25 '16 at 10:35
  • There was a hint: `$_GET`. And the OP accepted this as the correct answer back in 2009, so I think it's safe to assume that the OP's problem had something to do with PHP. – Ates Goral Jan 25 '16 at 17:56
16

There's a plugin for jQuery to get GET params called .getUrlParams

For POST the only solution is echoing the POST into a javascript variable using PHP, like Moran suggested.

Leandro Ardissone
  • 3,009
  • 6
  • 32
  • 31
5

why not use good old PHP? for example, let us say we receive a GET parameter 'target':

function getTarget() {
    var targetParam = "<?php  echo $_GET['target'];  ?>";
    //alert(targetParam);
}
tony gil
  • 9,424
  • 6
  • 76
  • 100
  • 8
    Because this is server side solution, and question was about client side / javascript / jQuery side. – Hrvoje Kusulja Jan 31 '14 at 21:37
  • @hkusulja adding insult to injury: even though you affirm it, i still cant see that the question is exclusively server-side. i feel thick as a tool... – tony gil Feb 03 '14 at 16:50
  • 2
    This script is hideous. Use this if you want your site hacked. Always escape user entered variables!! DO NOT output $_GET directly. – charj Aug 05 '16 at 10:17
5

Or you can use this one http://plugins.jquery.com/project/parseQuery, it's smaller than most (minified 449 bytes), returns an object representing name-value pairs.

4

Keep it simple

replace VARIABLE_KEY with the key of the variable to get its value

 var get_value = window.location.href.match(/(?<=VARIABLE_KEY=)(.*?)[^&]+/)[0]; 
Kareem
  • 5,068
  • 44
  • 38
3

With any server-side language, you will have to emit the POST variables into javascript.

.NET

var my_post_variable = '<%= Request("post_variable") %>';

Just be careful of empty values. If the variable you attempt to emit is actually empty, you will get a javascript syntax error. If you know it's a string, you should wrap it in quotes. If it's an integer, you may want to test to see if it actually exists before writing the line to javascript.

EndangeredMassa
  • 17,208
  • 8
  • 55
  • 79
  • 1
    You don't always have access to server-side languages though. For example GitHub pages... – Adam B Nov 11 '13 at 09:10
2

Here's something to gather all the GET variables in a global object, a routine optimized over several years. Since the rise of jQuery, it now seems appropriate to store them in jQuery itself, am checking with John on a potential core implementation.

jQuery.extend({
    'Q' : window.location.search.length <= 1 ? {}
        : function(a){
            var i = a.length, 
                r = /%25/g,  // Ensure '%' is properly represented 
                h = {};      // (Safari auto-encodes '%', Firefox 1.5 does not)
            while(i--) {
                var p = a[i].split('=');
                h[ p[0] ] = r.test( p[1] ) ? decodeURIComponent( p[1] ) : p[1];
            }
            return h;
        }(window.location.search.substr(1).split('&'))
});

Example usage:

switch ($.Q.event) {
    case 'new' :
        // http://www.site.com/?event=new
        $('#NewItemButton').trigger('click');
        break;
    default :
}

Hope this helps. ;)

Apex
  • 1,018
  • 1
  • 11
  • 13
2

You can try Query String Object plugin for jQuery.

Burak Erdem
  • 19,630
  • 7
  • 36
  • 56
1

If your $_GET is multidimensional, this might be what you're wanting:

var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
            return decodeURIComponent(s.split("+").join(" "));
    }

    //handling for multidimensional arrays
    if(decode(arguments[1]).indexOf("[]") > 0){
        var newName = decode(arguments[1]).substring(0, decode(arguments[1]).length - 2);
        if(typeof $_GET[newName] == 'undefined'){
            $_GET[newName] = new Array();
        }
        $_GET[newName].push(decode(arguments[2]));
    }else{
        $_GET[decode(arguments[1])] = decode(arguments[2]);
    }
});
WoodyNaDobhar
  • 173
  • 3
  • 10
1

simple, but yet usefull to get vars/values from URL:

function getUrlVars() {
    var vars = [], hash, hashes = null;
    if (window.location.href.indexOf("?") && window.location.href.indexOf("&")) {
        hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    } else if (window.location.href.indexOf("?")) {
        hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
    }
    if (hashes != null) {
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}

I found it somewhere on the internet, just fixed few bugs

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
1

Use following function:

var splitUrl = function() {
    var vars = [], hash;
    var url = document.URL.split('?')[0];
    var p = document.URL.split('?')[1];
    if(p != undefined){
        p = p.split('&');
        for(var i = 0; i < p.length; i++){
            hash = p[i].split('=');
            vars.push(hash[1]);
            vars[hash[0]] = hash[1];
        }
    }
    vars['url'] = url;
    return vars;
};

and access variables as vars['index'] where 'index' is name of the get variable.

Weafs.py
  • 22,731
  • 9
  • 56
  • 78
ashsam786
  • 143
  • 1
  • 6
  • This code fails for UTLs like `http://foo.com/?a=b#bar` . It thinks `b#bar` is the value for `a`. – M.M Nov 18 '15 at 05:00
1

jQuery plugins seem nice but what I needed is a quick js function to parse the get params. Here is what I have found.

http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx

Svetoslav Marinov
  • 1,498
  • 14
  • 11
0

My approach:

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]);
})();
otaxige_aol
  • 341
  • 1
  • 4
  • 6
-1

Just for the record, I wanted to know the answer to this question, so I used a PHP method:

<script>
var jGets = new Array ();
<?
if(isset($_GET)) {
    foreach($_GET as $key => $val)
        echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>

That way all my javascript/jquery that runs after this can access everything in the jGets. Its an nice elegant solution I feel.

Chud37
  • 4,907
  • 13
  • 64
  • 116