jQuery is a fantastic JavaScript library with a fast growing community. In my opinion, the library has a lot of advantages against other libraries:
- It is fast
- It is easy to use
- …. (I think you have to use it to see the advantages)
One big advantage is the plugin-possibility. If you want not to write the same code every time, the library gives the possibility to write a plugin, you can use every time.
In this way, I want to publish my plugins at this page: today the getURLParam.
This plugin can be used to get the URL parameters. You have to specify, which parameter you want. If the parameter does not exist, you will get “null”.
var param1 = $.getURLParam("userID");
Even testing, if a specific parameter exists, is easy:
if ($.getURLParam("userID")==null) {
alert("There is no userID");
}
The code can be found here.
Danke Mathias! 🙂
Good, keep on publishing stuff.
But, if I may, please, p l e a s e, learn to code.
First, you code in js like you would in Java: that’s bad (you don’t code in Java like you would in C).
Second, you use hungarian notation: that’s bad (js is not strongly typed, just get it).
Third, you use too many not necessary variables: that’s not good for reading and maitaining.
Well, it’s GPL, improve it and show me, how I can make it better? I know, that JavaScript is no Java, but I don’t know, what you dislike. So, show it to me.
First, thanks Mathias! Both for the actual plugin and for your desire to share it.
Secondly, I’m no js guru, but I think your code is fine. The aim must be to write code that work and is easily readible, not using the coolest language features. So I agree with you, if someone doesn’t like it, they can rewrite it.
I found a bug in your javascript code. If a parameter LanguageID=de is set i a URL before a parameter ID=08154711, your routine returns the value “de” when searching for the parameter ID. I suggest the following change:
…
if ( strHref.indexOf(“?”) > -1 ){
// remove the question mark!
var strQueryString = strHref.substr(strHref.indexOf(“?”)+1);
var aQueryString = strQueryString.split(“&”);
var cmpstring = strParamName + “=”;
var cmplen = cmpstring.length;
for ( var iParam = 0; iParam -1 ){
if (aQueryString[iParam].substr(0, cmplen) == cmpstring ){
var aParam = aQueryString[iParam].split(“=”);
…
Best regards,
Hinnerk Rümenapf
Sorry, your upload filter has removed parts of the code I submitted. I hope you get the idea in spite of this.
:-/
Hinnerk
Thanks for the bug report. I have fixed the file and have tested it with your params. It works good. I will upload the new version immediately.
Mathias: Great work, I love this code. I actually stumbled upon this after working with a co-worker earlier today to do just this sort of thing, but we ended up going the “regular javascript” route.
Anonymous Coward: There is absolutely nothing wrong with Mathias’ coding style. In fact quite the opposite is true. Its many others who need to learn how to code. The style Mathias is using is NOT Java centric, and is in use by some of the top programmers in the world in a variety of languages.
JavaScript may not be strongly typed, but that is no reason to not code that way, as it enhances the readability of the code. (Which you agree should be the end result).
I agree with mdrisser! The code looks a-okay to me!
Good work, Mathias 🙂 jQuery needed this plugin!
I like your style and attitude. Take care!!
Sean
Look at this implementation.
If `qstr` is not given, then the query string from the url is taken.
**********
function(pname,qstr) {
qstr=(typeof(qstr)==’undefined’)?window.location.search:qstr;
var re = new RegExp(‘([?&]?)(‘+jQuery.regExp.escape(pname)+’)=([^&#]*)’,’g’);
var matched_val = null;
var m;
while (m=re.exec(window.location.search))
matched_val = m[3];
return matched_val;
}
**********
-thanks, Eli
Oops.. forgot to give the jQuery.regExp.escape function. Here it is:
function(str) {
return str.replace(/[.*+?^${}()|[\]\/\\]/g,’\\$0′);
}
Hi. I’ve used your lib lately, and found it excellent. Good work. Allthough I have one problem. If I have an url like so: http://www.foo.bar?id=2#345, then getting the id-parameter will return 2#345.
Great script except for one thing, it doesn’t decode URL parameters. Line 29 should be:
strReturn = decodeURIComponent(aParam[1]);
Also, you realize that you can get the URL query parameters by using window.location.search. Unless this it not cross-browser enough, there’s no need to parse the location for the ? and following characters. window.location.search holds everything after the ? (and including it).
Very useful plugin. I incorporate several ideas above and enhanced it slightly to 1) handle parameter arrays, ‘?a[]=1&a[]=2’, and compare escaped and unescaped parameter names, ‘a[] == a%5B%5D’.
Thanks,
Tom
Apologies if this doesn’t show up properly…
getURLParam: function(paramName){
paramName = escape(unescape(paramName));
var returnVal = null;
if (window.location.search.substr(1,paramName) > -1 ){
var returnVal = new Array();
var qString = window.location.search.substr(1).split(“&”);
for (var i=0;i
Sorry, needed to escape the greater than. Gotta have a preview!
getURLParam: function(paramName){
paramName = escape(unescape(paramName));
var returnVal = null;
if (window.location.search.substr(1,paramName) > -1 ){
var returnVal = new Array();
var qString = window.location.search.substr(1).split(“&”);
for (var i=0;i>qString.length; i++){
if (escape(unescape(qString[i].split(“=”)[0])) == paramName){
returnVal.push(qString[i].split(“=”)[1]);
}
}
}
return returnVal;
}
});
Good lord, that was supposed to be a less than. I quit…
GREAT!
Usefully script! thanks for sharing it!
thx from Germany
Nice one buddy, this proved to be a quick solution to a problem I was having. Thanks for posting your code.
I have at .htaccess file converting my parameter to “directories”. It doesn’t seem to find the php parameters one the .htaccess file rewrites it.
Any suggestions?
ty for sharing
Thanks homeboy from CA!!! This works great.. And sorry for “anonymous coward,” I think he was PMS-ing :/
Thanks for the plugin Mathias. This is in continuation of what Jorg said long time back. Its here –
https://www.mathias-bank.de/2006/10/28/jquery-plugin-geturlparam/#comment-4265
The problem is only for selectors other than “document” (window.location.search hides the anchor from the GET request queryString). The fix is small –
if (returnVal.length==0) return null;
else if(returnVal.length==1){var retArr=returnVal[0].split("#"); return retArr[0]}
else return returnVal;
Great plugin! this will com in very handy!!
thanks 🙂
Great script! However…
so, I’m having the same problem as Dmbaggie. I want to use this to parse the URL after it’s been rewritten by mod_rewrite. My .htaccess is redirecting “pretty” URLS as GET variables…
For instance…
http://www.mysite.com/blog/article/article1
is rewritten as:
http://www.mysite.com/index.php?url=blog/article/article1
PHP is able to access the rewritten paramaters as $_GET, but this function thinks there is nothing set for GET…
any thoughts?
Haven’t downloaded yet — no comment on the plugin per se, but @Ahren: JavaScript is a client-side scripting language, not server side. If the URL parameters are never actually delivered to the client (browser) then JavaScript will never see them. You will either have to stop doing the rewriting (which comes with a pile of other issues you probably don’t want) or you’ll have to come up with some other tricky way to deliver the parameters to the client — perhaps in some hidden form elements or something — you’d have to code that in PHP as part of your web application though unless there happens to be a plugin for your application that does this — can’t imagine there is, but who knows?
Excellent little plugin. Saved me a heap of time!
And I like your coding style! 😀
Great Script! Saved me lots of time coding 😉
I changed the script to work with the window.hash to toggle DIV visibility on my web page.
every 100ms the script read’s the url hash, if a new div name is detected, the script hides all the div’s with a class and show’s the div with the name on the hash.
http://index.php#div=main
http://index.php#div=news
// JAVASCRIPT
var currentdiv;
var changediv;
getURLParam: function(strParamName){
var strReturn = “”;
var strHref = window.location.hash;
var bFound=false;
var cmpstring = strParamName + “=”;
var cmplen = cmpstring.length;
if ( strHref.indexOf(“#”) > -1 ){
var strQueryString = strHref.substr(strHref.indexOf(“#”)+1);
var aQueryString = strQueryString.split(“&”);
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
var aParam = aQueryString[iParam].split(“=”);
strReturn = aParam[1];
bFound=true;
break;
}
}
}
if (bFound==false) return null;
return strReturn;
}
});
$(document).ready(function(){
readhash();
});
function readhash() {
changediv = $.getURLParam(“div”);
if(currentdiv != changediv) {
currentdiv = changediv;
$(“.maindivs”).hide();
$(“#”+changediv).show();
}
hashtimer=setTimeout(“readhash()”,100);
}
Here is my 3 line version that does the same thing.
http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
Great plugin, it saved to me a lot of time.
Thanks for sharing.
I have done that in three lines as well 🙂
5 years ago though …
http://snippets.dzone.com/posts/show/4681
Great plugin Mathias. I also wrote a code to get URL parameters with jQuery.
http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
Thanks for sharing your jQuery plugin yet again.
Nice work… Thank u… 🙂
Thank you … this plugin has me very helped.
Thank you, very nice and usefully!
I had some trouble with this at first because the variables are case-sensitive. In my application, I cannot guarantee that the variables will always be in the same case format, so I modified line 27 of the script to make it case-insensitive (values returned are still in the correct case)
Line 27: if (aQueryString[iParam].substr(0,cmplen).toLowerCase()==cmpstring.toLowerCase()){
Full script:
/* Copyright (c) 2006 Mathias Bank (https://www.mathias-bank.de)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Thanks to Hinnerk Ruemenapf – http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
*/
jQuery.extend({
/**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* @example value = $.getURLParam(“paramName”);
*/
getURLParam: function(strParamName){
var strReturn = “”;
var strHref = window.location.href;
var bFound=false;
var cmpstring = strParamName + “=”;
var cmplen = cmpstring.length;
if ( strHref.indexOf(“?”) > -1 ){
var strQueryString = strHref.substr(strHref.indexOf(“?”)+1);
var aQueryString = strQueryString.split(“&”);
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (aQueryString[iParam].substr(0,cmplen).toLowerCase()==cmpstring.toLowerCase()){
var aParam = aQueryString[iParam].split(“=”);
strReturn = aParam[1];
bFound=true;
break;
}
}
}
if (bFound==false) return null;
return strReturn;
}
});
you can extremly short your code, and it will still work 😉
jQuery.extend({
getUrlParam: function(n){
var r = new RegExp(‘[\\?&]’+n+’=([^&#]*)’).exec(window.location.href);
return r[1] || 0;
});
Remarkable stuff. Were did you acquired all the information from
Thanks, this jquery plugin has me very helped.