javascript – how to get GET and POST variables with JQuery?-ThrowExceptions

Exception or error:

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'));
How to solve:

For GET parameters, you can grab them from

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

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


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); ?>;


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 = {},
        re = /[?&]?([^=]+)=([^&]*)/g;

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

    return params;

var $_GET = getQueryParams(;


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.


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'];  ?>";


Or you can use this one, it’s smaller than most (minified 449 bytes), returns an object representing name-value pairs.


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


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.


You can try Query String Object plugin for jQuery.


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.

    'Q' : <= 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;

Example usage:

switch ($.Q.event) {
    case 'new' :
    default :

Hope this helps. 😉


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


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

var $_GET = {};\??(?:([^=]+)=([^&]*)&?)/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[decode(arguments[1])] = decode(arguments[2]);


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


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[hash[0]] = hash[1];
    vars['url'] = url;
    return vars;

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


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


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

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

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


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  =;
   urlParams = {};
   while (match = search.exec(query))
    urlParams[decode(match[1])] = decode(match[2]);

Leave a Reply

Your email address will not be published. Required fields are marked *