Apr 21 2007
jQuery-Plugin – getUrlParam (version 2)
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.
Today, I have rewritten the plugin. It is now able to:
- Parse GET parameters of the document
$(document).getUrlParam(“param1″); - Parse image or JavaScript links with the help of the ID
$(“#javaScriptFile1″).getUrlParam(“ajaxUrl”);
The last method helps you to clearly separate html/php and JavaScript. I need it, because my php script is generating a special value. Now, I want to use this value in JavaScript, but I don’t want to write the value to my html-page (clear unobtrusive JavaScript). So I include the JavaScript file like this:
<script type=”text/javascript”
src=”/myScript.js?ajaxUrl=getAutocompleteList.php”
id=”javaScriptFile1″></script>
With this plugin, it is very easy to get the value of param ajaxUrl.
Have fun! Here is the source.
[Update]
The plugin is now able to handle href attributes, too. It checks now
- if you want a document parameter
- or there is a src attribute
- or there is a href attribute
- else it returns null

hello!
very nice !
i owuld like to suggest a tweak:
i need to find the value of a parameter of the src attribute of my A tag. unfortunately, that does not work
$(“a.ajax”)).getURLParam(“todo”);
could you make that mod ?
thanks!!
Yes, there is a new version (2.1) for this mod.
hello Mathias,
where can i find it ? i only find version 2. not 2.1. Am i being silly ?
I have replaced the old version. Perhaps, you get a cached version.
indeed, thank you very much!
Hallo Mathias, du scheinst ziemlich viel mit jQuery zu machen. Konnte leider keinen Link finden wie man mit dir Kontakt aufnehmen kann?
Weißt du wie man bei Klick auf einen Link einen Container neu laden kann bzw. Inhalt von einer bestimmten URL in einem Container laden kann?
Gruß,
Peter
Hallo Peter,
meine Lieblings-Referenz findest du unter Visual jQuery. Um auf den Klick zu reagieren brauchst du:
Und um Daten von einer URL zu holen z.B.
Zum setzen eines Conainer-Inhalts
Falls du weitere Unterstützung brauchst, kann ich dir die deutsche Community Strohhalm.org – Community for Webworkers empfehlen, da sind auch ein paar jQuery-Benutzer dabei.
Gruß
Mathias
You should use de/encodeURIComponent instead of un/escape. Also the values (just the keys) are not decoded. For details about encodings check this page :
http://xkr.us/articles/javascript/encode-compare/
Also none of the decode functions (that i know of) translate + to space. So here are the changed lines :
var val = decodeURIComponent( qString[i].split("=")[1].replace(/\+/g,' ') );returnVal.push(val);
Hi Mathias,
I’m rather new at Javascript and jQuery. I was wondering if you could awnser my question.
Im Using this script.
function mycarousel_itemFirstInCallback(carousel, item, idx, state)
{
if (state == ‘init’)
carousel.scroll(1, false);
};
As you can see i’m using jCarousel. The number in this string carousel.scroll(1, false);
is the id of a slide in the carousel. If I click on a link somewhere then I send this id with the link.
For example:
index.php?id=2
How do I get the id that I send into this carousel.scroll(MY ID, false);
I’m sorry Im a bit of a noob at javascript. I hope you can help me!
Greetz Tim
Well, that’s quite easy. If you call the function within the onclick-handler, you can get your id with
$(this).getUrlParam("id");
If “this” is not your link, you have to set an id in your link:
<a href="bla?id=2" id="myLink" />
Than, you can use:
$('#myLink').getUrlParam("id");
Hi Mathias,
Thanks for the quick reply!
I understand the way you explain it, but how do I integrate it into the code…
This is what I have:
if (state == ‘init’)
carousel.scroll(1, false);
Does it become this?
id = $(‘#myLink’).getUrlParam(“id”);
if (state == ‘init’)
carousel.scroll(‘ + id + ‘, false);
Thanks man!
Tim
No, just use
carousel.scroll(id, false);
Sorry to bother you again
Where do I put this:
$(’#myLink’).getUrlParam(”id”);
If I use this:
carousel.scroll(id, false);
Hi,
I tried to compress your plug-in using the same site jquery uses (url –> dean.edwards.name/packer/) and found that your plug-in is missing a couple of semi-colons.
Thus I’ve modified two lines…
before:
var strHref = $(this).attr(“src”)
after:
var strHref = $(this).attr(“src”);
before:
var strHref = $(this).attr(“href”)
after:
var strHref = $(this).attr(“href”);
Now it works compacted.
this can be util…
jQuery.fn.extend({
getAnchor: function(){
if(window.location.href.indexOf(“#”) != -1){
var url = window.location.href;
var uanchor = window.location.href.split(“#”);
if(uanchor[1]){
return uanchor[1];
}
}
}
});
[...] Mathias Bank, der Entwickler des jQuery-Plugins getUrlParam, beschreibt unter dem Titel “Eevent driven programming with jQuery eine interessante Möglichkeit, mit jQuery Funktionen dynamisch an Ereignisse zu binden. [...]
Hello,
1- I find getParam() returning a string or an array of strings depending on the input URL a bit inconvenient, the caller has to expect boths. What about always returning arrays (empty, with a single value or with multiple values) ? or have another version returning only null or a string, taking the first occurence of the given parameter ?
2- What about decoding the values ? Do we really want to get “foo%20bar” instead of “foo bar” ? Can we at least make that an optional parameter ?
Thanks for this plugin !
Hello,
1- well: As a developer, you should know, which parameter is an array and which is not. Of course, it would be possible to always return an array. But this does not make sense. You know, what you expect.
2- that’s a good idea. It will be included in the next version.
> As a developer, you should know, which parameter is an array and which is not.
Exactly and that’s why I am the one who decides to call either getAllParams() or getSingleParam(), and not let getParam() decide for me depending on *external input*. Since I know how I want these parameters to be processed, let getParam() give me what I asked for.
please note that there is an error in your plugin code or a possible change since jquery.1.2.2b
if ($(this).attr(“src”) != “undefined”) {
does not work. It needs to be
if ($(this).attr(“src”)) {
same for the other IF conditions.
HTH,
alexandre
[...] <html> <title>Test</title> <head> <script src="/js/jquery.js" type="text/javascript"></script> <script src="/js/jquery.getUrlParam.js" type="text/javascript"></script> <script type="text/javascript"> jQuery().ready(function() { $("#irgendwas a").click(function() { var test = $(this).getUrlParam(‘vorname’); alert(test); return false; }); }); </script> </head> <body> <div id="irgendwas"><a href="test.pl?vorname=max&nachname=mustermann">Hier klicken</a></div> </body> </html> Hier ist der Link zu getUrlParam(): Mathias Bank jQuery-Plugin – getUrlParam (version 2) [...]
a little bit changed to support getting the params of a child frame. for use with iframes .
//frm is the frame for which you want to examine the params
getUrlParam: function(strParamName, frm){
strParamName = escape(unescape(strParamName));
var returnVal = new Array();
var qString = null;
if ($(this).attr(“nodeName”)==”#document”) {
//document-handler
var loca;
if(frm){
loca = frm.location;
}else{
loca = window.location;
}
if (loca.search.search(strParamName) > -1 ){
qString = loca.search.substr(1,window.location.search.length).split(“&”);
}
Hallo Matthias,
bin gerade auf dein Plugin gestossen. Vielen Dank für die Veröffentlichung!
Anbei eine kürzere Implementierung Deiner Funktion. Wenn Du sie gut findest, kannst Du vielleicht Teile übernehmen, bevor es noch eine weiteres Plugin gibt
Die Funktion basiert auf einem Kommentar von Eli zu deiner ersten Version, dessen Code bei mir jedoch nicht funktionierte. Aus Performancegründen wird der querystring übergeben und nicht über Selektoren nach #document, src oder href gesucht.
BTW, was bewirkt die Anweisung strParamName = escape(unescape(strParamName)); in Deinem Plugin?
Heben sich escape und unescape nicht auf?
$.getUrlParam = function(paramname, querystr){
querystr = (querystr == undefined) ? window.location.search : querystr;
// regexp escape paramname
paramname = paramname.replace(/\\|\^|\$|\*|\+|\?|\.|\(|\)|\[|\]/g, “\\$&”);
// build regexp
var pattern = new RegExp(“(.*)(” + paramname + “=)([^&#]*)(.*)”,”i”);
var result = pattern.exec(querystr)
if(result == null) {
// param not found – returns null to distinguish if the param contains no value and therefore returns an empty string
return null;
} else {
return unescape(result[3]);
}
} // end function getUrlParam
Das hatte ich damals auch gedacht, aber aus irgendeinem Grund hatte ich es dann doch drin gelassen, weil es ein Problem gelöst hatte. Frag mich jetzt aber nicht, was das war. Sollte doch mehr dokumentieren *hrmpf*
[...] forms. FormEXCELLENT Change HTML forms to submit via Ajax. Gallery Viewer JavaScript image gallery. getUrlParam Function to get url parameters. Google Feed Plugin Display any RSS feed to a webpage. Gradient Adds [...]
Hey thanks for your work that you put into this site design.
Richard Ogima
Been looking for something like this for a long time, excellent work!
-Pete
I’m trying to pass a url as a param and this url contains characters which is causing it to lose data from the string. Is there a way around this?
For example, the url string i’m attempting to pass is:
http://some.website.com/somePage.aspx?u=other.website.com&lo=1
When i alert the value of qString i get:
http://some.website.com/somePage.aspx?u
[...] forms. FormEXCELLENT Change HTML forms to submit via Ajax. Gallery Viewer JavaScript image gallery. getUrlParam Function to get url parameters. Google Feed Plugin Display any RSS feed to a webpage. Gradient Adds [...]
Hi,
Thats g8. But I have a script like this “”
If any one paste this code to his or her website then some server information will be loaded on that website from me. But problem is i want to catch param value ‘com_id’ from my script. I used the getUrlParam plugin on the same js file ‘widget_job_board.js’ but an error occurs like this “$(“#script1″) has no properties” . Would u like to help me Mathias.
Well, there is no code, which can be seen, but I think, that your included script file has no id. You have to include the file with an id.
Cool and useful script. Although you should wrap the plugin like this (taken from here: http://docs.jquery.com/Plugins/Authoring):
(function($) {
// plugin code here, use $ as much as you like
})(jQuery);
It’s a minor inconvenience for the user to wrap it, if they want/need to use aliases, but I guess it wouldn’t hurt to provide it wrapped
Thanks for a great script!
This is a useful function, but I note that it doesn’t urldecode parameters, so I need to do an extra step every time I want to process a parameter.
Adding urldecoding to getUrlParam would be a breaking change, but it would be nice to add a function that has urlencode built in… Otherwise (i) I have to write it, and (ii) newbs are going to write programs that get confused about “+” and space.
Well, there have been many good ideas since the second version. I my next free time, I will write the a new version, which will be capable of your comments.
Unfortunatelly, that can take some time, because currently I’m very busy.
I ran into the same problem as Matthewon reported on 2007-08-27. Lines 40 and 47 are missing their trailing semicolons. The library works fine as is, but when minified the library breaks (doesn’t work). I added those two missing semicolons, and everything works fine after minification.
Hi… I’m using your great code for validation routines in a web application. I did a little change to your code for support non english characters (our system are in spanish), using unescape function.
(lines 60-65)
for (var i=0;i<qString.length; i++){
if (escape(unescape(qString[i].split(“=”)[0])) == strParamName){
returnVal.push(unescape(qString[i].split(“=”)[1]));
}
}
Great work
I’ve made some changes to the getUrlParam script, it still works in the same way but you can now query more than one element at a time:
jQuery.fn.extend({
getUrlParam: function(strParamName){
strParamName = escape(unescape(strParamName));
var returnVal = new Array();
this.each(
function()
{
var strHref = $(this).attr(“src”)|| $(this).attr(“href”)|| this.URL||”";
var qString = “”;
if ( strHref.search(“#|\\?”) > -1 ){
var strQueryString = strHref.substr(strHref.search(“#|\\?”)+1);
qString = strQueryString.split(“&”);
}
for (var i=0;i<qString.length; i++){
if (escape(unescape(qString[i].split(“=”)[0])) == strParamName){
returnVal.push(qString[i].split(“=”)[1]);
}
}
}
);
if (returnVal.length==0) return null;
else if (returnVal.length==1) return returnVal[0];
else return returnVal;
}
});
Oh yes and use # or ?
[...] to http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2/ for more [...]
thks a bunch! keep up the good work!
Thanks and that tutorial has me very helped.
[...] jQuery GetURLParam plugin [...]
[...] didn’t take me long to write it, because I embedded both jQuery and the getUrlParam jQuery plugin by Mathias Bank. This made it simple to create Bing Numbered Search Results. In the end, it took [...]
Hi Mathias,
erst einmal: nettes Plugin. Hat mir sehr geholfen. Leider bin ich auf ein Problem gestoßen, wozu mir gerade keine Lösung einfällt. Wie greife ich denn auf sowas hier zu:
alert($(document).getUrlParam(‘tx_mytestshop_pi1[catId]‘));
Hintergrund: TYPO3-Extensions erzeugen immer solche Parameterarrays in den URLs. Ich müsste auf den Wert von catId zugreifen…
Das mit Typo3 und den Extensions würde mich auch mal interessieren, zumal ich sehr viel JQUERY in meinen Typo3-Projekten einsetze.
Nachtrag:
Ich habe jetzt stattdessen jqURL genommen. Das funktioniert auch mit o.g. Problematik.
I love this extension, thanks for posting it,
I did however run into an issue, when I used it on an “a” tag, it always bombed because it did not pass over the “src” attr check.
I was able to fix this by changing the lines
} else if ($(this).attr(“src”) != “undefined”) {
} else if ($(this).attr(“href”) != “undefined”) {
to
} else if (typeof $(this).attr(“src”) != “undefined”) {
} else if (typeof $(this).attr(“href”) != “undefined”) {
… though, I was only using FF3 for the Mac.
Great stuff, thanks for making it available
Will probably use this over and over again!
Zuerst einmal: Schönes PlugIn! Mir stellt sich allerdings ein Problem (ich denke ziemlich einfach zu lösen, oder einfach mit diesem PlugIn nicht möglich):
Ich entwickle eine Seite, die Inhalte mittels AJAX lädt (sprich: FrontEnd besteht aus Navigation und Header und das BackEnd lädt je nach übermittelten GET-Parametern Inhalte dynamisch nach – natürlich angestoßen durch JavaScripts). Da das DOM natürlich schon beim Laden des FrontEnds “ready” ist, muss ich manche JavaScripts im BackEnd “nachladen” (nach der Ausgabe, damit sichergestellt ist, dass alles im DOM steht). Hier lade ich auch ein Skript nach, dass dieses PlugIn verwenden soll (und das PlugIn zuvor selbst). Wenn ich nun versuche GET-Parameter auszulesen bekomme ich immer null zurück. Ich denke das liegt daran, dass dieses PlugIn versucht die Parameter vom FrontEnd zu bekommen, nicht jedoch vom BackEnd. Ich bräuchte also eine explizite Möglichkeit auf die GET-Parameter eines bestimmten PHP-Skriptes zuzugreifen (in meinem Fall: “loader.php”).
@teh_han: Verstehe ehrlich gesagt das Problem nicht: du schickt an den Server eine Anfrage mit GET-Parameter und willst die dann mit diesem Plugin auf dem Client auslesen? Dann weißt du doch die Anfrage schon. Müsste ich mal sehen, was du meinst. Oder verwechselst du jetzt serverseitige Programmierung mit clientseitiger?
Für jQuery kann ich dir http://www.strohhalm.org empfehlen. Da sind ein paar (ich inkl.), die sich mit jQuery auskennen und dir sicherlich – auch mit diesem Plugin – helfen können.
Hallo,
ich wollte nur ein kurzes Dankeschön für das Plugin dalassen… hat mir eine Menge Arbeit erspart. Und mit dem in den Kommentaren angegebenen if-fix läuft es wirklich richtig gut!!
Hi had problems with your scripts for some reasons, this is what for me :
-replaced : all “$” by “jQuery”
-replaced :
} else if (jQuery(this).attr(“src”)!=”undefined”) {
by
} else if (jQuery(this).attr(“src”)) {
-replaced :
} else if (jQuery(this).attr(“href”)!=”undefined”) {
by :
} else if (jQuery(this).attr(“href”)) {
[...] getUrlParam Function to get url parameters. [...]
You are not handling parameters with “=” well:
Instead of:
for (var i=0;i<qString.length; i++){
if (escape(unescape(qString[i].split(“=”)[0])) == strParamName){
returnVal.push(qString[i].split(“=”)[1]);
}
}
You should:
for (var i = 0; i = 0) &&
(escape(unescape(qString[i].substr(0, index))) == strParamName)) {
returnVal.push(qString[i].substr(index + 1));
}
}
My code was altered some way when I submitted. Let’s try again:
for (var i = 0; i = 0) &&
(escape(unescape(qString[i].substr(0, index))) == strParamName)) {
returnVal.push(qString[i].substr(index + 1));
}
}
I don’t know the syntax to post code here so I published the corrected version of your code at
http://code.google.com/p/get-query-string-jquery-plugin/source/browse/trunk/jquery.getUrlParam.js
thanks for your job!
[...] didn’t take me long to write it, because I embedded both jQuery and the getUrlParam jQuery plugin by Mathias Bank. This made it simple to create Bing Numbered Search Results. In the end, it took [...]
I’ve got some improvements to have those parameters case insensitive, because php does not use case sensitive url params.
-strParamName = escape(unescape(strParamName));
+strParamName = escape(unescape(strParamName)).toLowerCase();
-if (window.location.search.search(strParamName) > -1 ){
-qString = window.location.search.substr(1,window.location.search.length).split(“&”);
+if (window.location.search.toLowerCase().search(strParamName) > -1 ){
+qString = window.location.search.toLowerCase().substr(1,window.location.search.length).split(“&”);
[...] getUrlParam Function to get url parameters. [...]
[...] getUrlParam Function to get url parameters. [...]
[...] getUrlParam Function to get url parameters. [...]
[...] getUrlParam Function to get url parameters. [...]
Hiya,
cleaned up your plugin, ran it thru JSLint and compacted with Google Closure compiler
posted here,
http://github.com/johnantoni/jquery.geturlparam
good work btw.
This is great. I look forward to using it in one of my projects.
Thanks
Hi! Great plugin!
I have hrefs that end with an anchor (i.e. href=”?param1=value¶m2=value2#anchorName”)
Currently, if I ask for param2, i get ‘value2#anchorName’. To fix this, instead of using
returnVal.push(qString[i].split(“=”)[1]);
you could strip the trailing anchor name:
var paramValue = qString[i].split(“=”)[1];
returnVal.push(paramValue.substr(0, paramValue.indexOf(“#”)));
also, chekcing for “undefined” as a string doesn’t work:
if ($(this).attr(“src”) != “undefined”)
if ($(this).attr(“href”) != “undefined”)
you need to remove the quotes from ‘undefined’:
if ($(this).attr(“src”) != undefined)
if ($(this).attr(“href”) != undefined)
[...] getUrlParam Function to get url parameters. [...]
[...] getUrlParam Function to get url parameters. [...]
Hi Mathias,
Super Seite wirklich spitze und ich hab andscheinend wirklich auch noch das Plugin gefunden was ich brauch/te…
*happy*
Aber hätte da noch eine Frage… Wie ist es möglich aus der URL nur den letzten verweiß rauszufiltern, nach “/”
mal beispiel damit Du weißt was ich meine…
z.b.
http://www.mathias-bank.de/2007/04/21/— AB HIER>jquery-plugin-geturlparam-version-2/
ich hab es bis jetzt so gelöst das ich immer die ganze URL abgefragt habe mit document.URL das ist aber irgendwie nicht “richtig” funktioniert aber bei manchen browsern
Bin da totaler Anfänger und würde mich über hilfe freuen…
Mit freundlichem Gruß
Christoph
[...] getUrlParam [...]
Hi Mathias,
Sorry but I am quite new to this.
I am trying to use your plugin to capture a query in a url. What I want to do is capture that single query (cp) and enter just the 999 in text input box.
the url string: mysite.com/test.aspx?ID=1194&cp=999
could you possibly give me some guidance on how to do this?
Regards
var cp = $(document).getUrlParam(‘cp’);
Yes, absolutely correct. That should do what you want. Thanks @Michael
Thanks Michael, that worked great.
I know this is probably a very simple solution, but just incase anyone else out there is looking for a similar answer here it this thanks to Michael…
var cp = $(document).getUrlParam(‘cp’);
$(‘input’).attr(‘value’, cp)
There is a error with jQuery 1.4.3 with getUrlParam Version 2.1
Erreur : strHref is undefined
I am seeing the same error as @Rastafa using jQuery 1.4.3 with getUrlParam Version 2.1
Further to the issue if I comment out the following section of code the problem goes away:
} else if ($(this).attr(“src”)!=”undefined”) {
var strHref = $(this).attr(“src”)
if ( strHref.indexOf(“?”) > -1 ){
var strQueryString = strHref.substr(strHref.indexOf(“?”)+1);
qString = strQueryString.split(“&”);
}
Because I am extracting a href value this means my code works now
Hi Everyone,
the Problem in jQuery 1.4.x is caused by this Line:
if ($(this).attr(“nodeName”)==”#document”) {
Use this instead and everything works fine:
if (typeof $(this).attr(“src”)== “undefined” && typeof $(this).attr(“href”)==”undefined”) {
@Dave
Deleting something is not very helpful
@Oliver
Thanks for that
FYI, the above fix does not work in jQuery 1.4.4, but it appears to be due to a bug:
http://bugs.jquery.com/ticket/7500
I’m guessing this will be fixed in 1.4.5
[...] jQuery GetURLParam plugin [...]
[...] jQuery GetURLParam plugin [...]
@Rastafa, @Dave Buchholz
I was able to get it working, by changing;
else if ($(this).attr(”src”)!=”undefined”)
to:
else if ($(this).attr(”src”)!= undefined)
same for the href attr.
great little plugin, save me some time
Great plugin. Thanks
You should replace this line:
returnVal.push(qString[i].split(“=”)[1]);
for
returnVal.push(qString[i].substring(qString[i].indexOf(“=”)+1));
to get parameters with =, for example this: Base64(“Hi there”) -> SGkgdGhlcmU=
It does not works on iframe document
I tried this but it shows the parent window and not iframe’s?
$(window.frames["iframe1"].document).getUrlParam(‘param1′);
Thanks in advance
CSJakharia
Hi, I suggest to use an ID for the iFrame element and to use this ID for selection.
Looks like jQuery 1.6 isn’t compatible with your script. I changed
if ($(this).nodeName == “#document”)
to :
if ($(this).get(0).nodeName == “#document”)
and returned the code to working order on modern browsers. jQuery no longer works around document.attr calls, since content attributes aren’d supported on the document element.
if you have a param like &keyword[]=’foo’&keyword[]=’bar’ for example in a rails app, your script can’t handle that.
Changing the search line in #document to:
if (escape(unescape(window.location.search)).search(strParamName) > -1 ){
qString = window.location.search.substr(1,window.location.search.length).split(“&”);
}
will escape the special characters and find a match for:
$(document).getUrlParam(“keywords[]“);
=> ['foo', 'bar']
[...] http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2/ [...]
[...] getUrlParam jQuery plugin by Mathias [...]
[...] getUrlParam jQuery plugin by Mathias [...]
Hi Mathias,
Congrats for your plugins. But I have a question:
How can I capture random vars of random urls?
Your example shows only predefinied vars.
Thank you.
[...] jQuery GetURLParam plugin [...]
Thanks a lot!
I added the hint from Sailias, added the anonymous function around, cleaned it up with JSLint and made a minified version. => https://github.com/sokai/jquery.getUrlParam/
It works great with jQuery v1.7.1.
[...] in forms. Form Change HTML forms to submit via Ajax. Gallery Viewer JavaScript image gallery. getUrlParam Function to get url parameters. Google Feed Plugin Display any RSS feed to a webpage. Gradient Adds [...]
Hi,
thank you for the great peace of code.
Here is na issue:
Got more than one link. When i try to get other than first link values it always shows first link values.
How can I fix that?
Thank you in advance!
[...] using http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2/ [...]
[...] jQuery GetURLParam plugin [...]