how to get GET and POST variables with JQuery?

JavascriptJquery

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - 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.

Solution 3 - Javascript

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

Solution 4 - 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.

Solution 5 - Javascript

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.

Solution 6 - Javascript

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

Solution 7 - Javascript

You can try Query String Object plugin for jQuery.

Solution 8 - Javascript

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

Solution 9 - Javascript

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

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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.

Solution 13 - Javascript

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

Solution 14 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdward TanguayView Question on Stackoverflow
Solution 1 - JavascriptAtes GoralView Answer on Stackoverflow
Solution 2 - JavascriptLeandro ArdissoneView Answer on Stackoverflow
Solution 3 - Javascripttony gilView Answer on Stackoverflow
Solution 4 - JavascriptMichaelView Answer on Stackoverflow
Solution 5 - JavascriptEndangeredMassaView Answer on Stackoverflow
Solution 6 - JavascriptMatt GardnerView Answer on Stackoverflow
Solution 7 - JavascriptBurak ErdemView Answer on Stackoverflow
Solution 8 - JavascriptKareemView Answer on Stackoverflow
Solution 9 - JavascriptSvetoslav MarinovView Answer on Stackoverflow
Solution 10 - JavascriptWoodyNaDobharView Answer on Stackoverflow
Solution 11 - JavascriptLukas LiesisView Answer on Stackoverflow
Solution 12 - Javascriptashsam786View Answer on Stackoverflow
Solution 13 - Javascriptotaxige_aolView Answer on Stackoverflow
Solution 14 - JavascriptChud37View Answer on Stackoverflow