Okt 28 2006

jQuery-Plugin – getURLParam

Veröffentlicht by . Filed under: jQuery

Version 2 is avaiable

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.

46 responses so far

1 Star2 Stars3 Stars4 Stars5 Stars
Loading ... Loading ...
^

46 responses so far

  1. Dominik Hahnon 28 Okt 2006 at 11:43 pm

    Danke Mathias! :-)

  2. anonymous cowardon 15 Nov 2006 at 11:21 am

    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.

  3. mathias-bank.deon 15 Nov 2006 at 12:48 pm

    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.

  4. Stefan Holmbergon 17 Nov 2006 at 9:13 am

    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.

  5. Hinnerk Rümenapfon 20 Dez 2006 at 5:25 pm

    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

  6. Hinnerk Rümenapfon 20 Dez 2006 at 5:31 pm

    Sorry, your upload filter has removed parts of the code I submitted. I hope you get the idea in spite of this.

    :-/

    Hinnerk

  7. mathias-bank.deon 20 Dez 2006 at 8:23 pm

    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.

  8. mdrisseron 20 Dez 2006 at 10:31 pm

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

  9. Seanon 13 Feb 2007 at 4:22 pm

    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

  10. Elion 08 Mrz 2007 at 4:44 am

    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

  11. Elion 08 Mrz 2007 at 4:46 am

    Oops.. forgot to give the jQuery.regExp.escape function. Here it is:

    function(str) {
    return str.replace(/[.*+?^${}()|[\]\/\\]/g,’\\$0′);
    }

  12. Jorgon 29 Mrz 2007 at 6:02 pm

    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.

  13. LoveDubon 30 Mrz 2007 at 12:04 pm

    Great script except for one thing, it doesn’t decode URL parameters. Line 29 should be:

    strReturn = decodeURIComponent(aParam[1]);

  14. LoveDubon 30 Mrz 2007 at 12:06 pm

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

  15. Tom Leonardon 13 Apr 2007 at 10:21 pm

    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

  16. Tom Leonardon 13 Apr 2007 at 10:24 pm

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

  17. Tom Leonardon 13 Apr 2007 at 10:26 pm

    Good lord, that was supposed to be a less than. I quit…

  18. [...] Some time ago, I have written a small jQuery plugin to easily get GET-Variables. The plugin is used by a lot of people. But it doesn’t satisfy all possibilities, you need. [...]

  19. [...] Dabei möchte ich aber gern aufgrund des #comment-Ankers, denn man bekommt, sobald man einen Kommentar ausgegeben hat, auslesen. Denn dann, soll der Bereich des Kommentars nicht asugeblenedet werden (hide oder toogle). Um Parameter, also auch Anker aus der URL auszulesen kann man ebenfalls jQuery nutzen, eine kleines Plugin getURLParam (1K) sorgt dafür. Leicht zu implementieren und zu nutzen. Mit PHP kann man das nicht so einfach und so ist es eine saubere Lösung. [...]

  20. Andre Michaelison 12 Jul 2007 at 8:46 pm

    GREAT!

  21. Werbeagenturon 25 Dez 2007 at 1:10 pm

    Usefully script! thanks for sharing it!
    thx from Germany

  22. Tancon 12 Mrz 2008 at 11:29 am

    Nice one buddy, this proved to be a quick solution to a problem I was having. Thanks for posting your code.

  23. Dmbaggieon 26 Jun 2008 at 7:38 pm

    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?

  24. Mojoon 29 Sep 2008 at 4:40 pm

    ty for sharing

  25. [...] to do manually, but still, a task that must be done manually.  That is until I found a handy JQuery plugin suited perfectly to this [...]

  26. Bennyfreshnesson 13 Feb 2009 at 7:23 pm

    Thanks homeboy from CA!!! This works great.. And sorry for “anonymous coward,” I think he was PMS-ing :/

  27. Avleshon 21 Feb 2009 at 6:31 am

    Thanks for the plugin Mathias. This is in continuation of what Jorg said long time back. Its here -
    http://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;

  28. Alien Blog » useful pluginon 18 Mrz 2009 at 4:32 pm

    [...] getURLParams - It allows you to check / get specific URL parameters. [...]

  29. Gacksonon 30 Mrz 2009 at 3:32 pm

    Great plugin! this will com in very handy!!

  30. morjonon 01 Apr 2009 at 4:00 pm

    thanks :)

  31. Ahrenon 20 Apr 2009 at 1:27 am

    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?

  32. Michaelon 07 Mai 2009 at 12:35 pm

    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?

  33. richardon 03 Jun 2009 at 4:18 am

    Excellent little plugin. Saved me a heap of time!
    And I like your coding style! :D

  34. Joel Ferreiraon 08 Jun 2009 at 11:42 am

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

  35. Josh Fraseron 24 Jun 2009 at 9:37 pm

    Here is my 3 line version that does the same thing.

    http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/

  36. Cosas de Agapornison 09 Jul 2009 at 12:33 pm

    Great plugin, it saved to me a lot of time.

    Thanks for sharing.

  37. anonymon 17 Jul 2009 at 3:58 pm

    I have done that in three lines as well :)
    5 years ago though …
    http://snippets.dzone.com/posts/show/4681

  38. jQuery Howtoon 16 Sep 2009 at 2:01 pm

    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.

  39. Shaaaon 21 Okt 2009 at 6:20 am

    Nice work… Thank u… :)

  40. TYPO3 Freelanceron 08 Dez 2009 at 11:10 am

    Thank you … this plugin has me very helped.

  41. atasözlerion 18 Feb 2010 at 9:52 am

    Thank you, very nice and usefully!

  42. Josh Orvison 25 Mai 2010 at 10:21 pm

    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 (http://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;
    }
    });

  43. arusson 28 Okt 2010 at 1:37 am

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

  44. [...] http://www.mathias-bank.de/2006/10/28/jquery-plugin-geturlparam/ [...]

  45. major depression disorderon 31 Jul 2011 at 10:50 pm

    Remarkable stuff. Were did you acquired all the information from

  46. Software Managementon 12 Mrz 2012 at 3:45 pm

    Thanks, this jquery plugin has me very helped.

Trackback URI | Comments RSS

Hinterlasse eine Antwort