[javascript] how to get GET and POST variables with JQuery?

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

This question is related to javascript jquery

The answer is


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


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.


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.


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


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.


You can try Query String Object plugin for jQuery.


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

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


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.


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


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

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.


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.


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.


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


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.


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

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.


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

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.

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


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

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


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


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

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.


You can try Query String Object plugin for jQuery.


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.


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.


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

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

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.


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.