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 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'));
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);
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']; ?>";
//alert(targetParam);
}
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.
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.
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]);
}
});
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.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.
jQuery plugins seem nice but what I needed is a quick js function to parse the get params. Here is what I have found.
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]);
})();
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.