<pedrocorreia.net ⁄>
corner
<mySearch ⁄> <mySearch ⁄>

corner
 
corner
<mySnippets order="rand" ⁄> <mySnippets order="rand" ⁄>

corner
 
corner
<myContacts ⁄> <myContacts ⁄>

<email ⁄>


pc@pedrocorreia.net

<windows live messenger ⁄>


pedrojacorreia@hotmail.com

<myCurriculum type="pdf" ⁄>


Download
corner
 
corner
<myBlog show="last" ⁄> <myBlog show="last" ⁄>

corner
 
corner
<myNews show="rand" ⁄> <myNews show="rand" ⁄>

corner
 
corner
<myNews type="cat" ⁄> <myNews type="cat" ⁄>

corner
 
corner
<myQuote order="random" ⁄> <myQuote order="random" ⁄>

A sinceridade é o princípio e o fim de todas as coisas
corner
 
corner
<myPhoto order="random" ⁄> <myPhoto order="random" ⁄>

<pedrocorreia.net ⁄>
corner
 
corner
<myAdSense ⁄> <myAdSense ⁄>

corner
 
corner
<myVisitorsMap ⁄> <myVisitorsMap ⁄>

corner
 
 

<Javascript Get QueryString Variable ⁄ >




clicks: 12777 12777 2009-03-08 2009-03-08 goto mySnippets mySnippets javascript  Download  Bookmark This Bookmark This



Probably this won't be a normal procedure, getting query string variables using a client-script, JavaScript, mainly you use a server-side script, such as PHP, ASP.NET.

But you can, also, easily get variables in GET request (this is, all variables in the url), for example when submitting a form using method="get", as far as I know JavaScript can't handle http post requests.

It's a simple process, you just to look into "document.location.search" and analyze the string content, for example, we know that the 1st variable will be after "?" and consequent (if exists) will be after "&", so we just need to use String.split function.



Basically our query string's just a pair value: Key=>Value, just like an associative array.
In this snippet I created 2 objects: Param and Params; as you can easily guess, Params will be a collection of Param Objects, it all hold all query string content (key=>value).


This is an extensible script, I created a few functions, just like getting a specific key and its value, auto fill a form, fill a specific form field, etc, etc.



Hope this helps you in any manner, I already used it a few projects where server-side scripting wasn't available, but perhaps that won't occur that much.



Here goes the code.

Events.js, this file's responsible for events management, that is, our page has elements and those elements will react to events/ triggers, with this class we'll be able to add or remove events, such as onchange, onload, etc, etc.
  1. /**
  2. * Static Class
  3. * Manage Events
  4. */
  5. Events = function(){}
  6.  
  7. /**
  8. * Add Event
  9. *
  10. * Source and full credits to:
  11. * http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
  12. *
  13. * @param Object
  14. * @param Object
  15. * @param Object
  16. */
  17. Events.AddEvent = function(obj, type, fn){
  18. if(!obj) return;
  19.  
  20. this.RemoveEvent(obj, type, fn);
  21. if (obj.addEventListener) {obj.addEventListener(type, fn, false);}
  22. else {
  23. if (obj.attachEvent) {
  24. obj["e" + type + fn] = fn;
  25. obj[type + fn] = function(){
  26. obj["e" + type + fn](window.event);
  27. }
  28. obj.attachEvent("on" + type, obj[type + fn]);
  29. }
  30. }
  31. }
  32.  
  33. /**
  34. * Remove Event
  35. *
  36. * Source and full credits to:
  37. * http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
  38. *
  39. * @param Object
  40. * @param Object
  41. * @param Object
  42. */
  43. Events.RemoveEvent = function(obj, type, fn){
  44. if (obj.removeEventListener) {
  45. try{obj.removeEventListener(type, fn, false);}catch(e){}
  46. }
  47. else{
  48. if (obj.detachEvent) {
  49. obj.detachEvent("on" + type, fn);
  50. obj[type + fn] = null;
  51. obj["e" + type + fn] = null;
  52. }
  53. }
  54. }




Dom.js, responsible for the DOM operations
  1. /**
  2. * Static Class
  3. *
  4. * A few basic DOM manipulations
  5. *
  6. * @author: pedrocorreia.net
  7. */
  8.  
  9. /**
  10. * Get Html Object reference
  11. *
  12. * @param String Id Object
  13. */
  14. $ = function(id){return document.getElementById(id);};




QueryStringParameters.js, as I said earlier, we'll have two objects: Param and Params; Param Object will have two properties: key and value; Params Object will act like a container, will save all Param Objects and will allow us to get a specific Param information.
  1. /**
  2. * QueryString Parameters container
  3. *
  4. * @author: pedrocorreia.net
  5. */
  6.  
  7.  
  8. /**
  9. * QueryString Parameter
  10. *
  11. * @param String Key
  12. * @param String Value
  13. **/
  14. var Param = function(k, v) {
  15. var self = this;
  16.  
  17. /**
  18. * Will hold each parameter in our query string
  19. * QueryString Pair - Key=>Value
  20. *
  21. * @param String Key
  22. * @param String Value
  23. * @return Object
  24. **/
  25. var _pair = (function() {
  26. self.key = k;
  27. self.value = decodeURI(v);
  28. return self;
  29. })(k, v);
  30.  
  31. /**
  32. * Get QueryString Key
  33. *
  34. * @return String
  35. **/
  36. var _key = function(){return _pair.key;};
  37.  
  38. /**
  39. * Get QueryString Value
  40. *
  41. * @return String
  42. **/
  43. var _value = function(){return (_pair.value || "");};
  44.  
  45. /**
  46. * toString overload
  47. *
  48. * @return String
  49. */
  50. var _output = function(){
  51. return (_pair.key)?"Key: "+_pair.key+"; Value: "+_pair.value+";":"";
  52. };
  53.  
  54. return {
  55. Key: _key,
  56. Value: _value,
  57. toString: _output
  58. };
  59. };
  60.  
  61. /**
  62. * This object will hold all our Param objects.
  63. *
  64. * We'll use an associative array, this is, our array index will be
  65. * our query string variable (key), so if you specify the same key
  66. * twice, or more, the last specified will override the current.
  67. *
  68. */
  69. var Params = function() {
  70.  
  71. var _ps = {}; //our container, will hold "Param" objects
  72.  
  73. /**
  74. * Add Parameter
  75. *
  76. * @param Param QueryString Parameter
  77. */
  78. var _addParam = function(param){ _ps[param.Key()] = param;};
  79.  
  80. /**
  81. * Get Parameter
  82. *
  83. * @return Param
  84. */
  85. var _getParam = function(k){return (_ps[k] || "");};
  86.  
  87. /**
  88. * Get all query string Keys
  89. *
  90. * @param Array
  91. */
  92. var _getKeys = function(){
  93. var _keys=[]
  94. for (var p in _ps){if(p){_keys[_keys.length] = p;}}
  95. return _keys;
  96. }
  97.  
  98. /**
  99. * Get the size of our Params collection
  100. *
  101. * @return Int
  102. */
  103. var _numElements = function() {
  104. var count = 0;
  105. for (var p in _ps) { if(p) {count++;} }
  106. return count;
  107. };
  108.  
  109. /**
  110. * toString overload
  111. */
  112. var _output = function() {
  113. if (_numElements() === 0) {return "";} //nothing to output
  114.  
  115. var str = "";
  116. for (var p in _ps) { str += _ps[p].toString() + "<br/>"; }
  117. return str;
  118. };
  119.  
  120. return {
  121. Add: _addParam,
  122. Count: _numElements,
  123. Get: _getParam,
  124. GetKeys: _getKeys,
  125. toString: _output
  126. };
  127. };








QueryString.js, this is our main object, basically what we'll use more often;
  1. /*
  2. * This class's responsible for all QueryString operations
  3. * and user interaction
  4. *
  5. * @author: pedrocorreia.net
  6. */
  7. var QueryString = function() {
  8.  
  9. var _qry = document.location.search; //our query string
  10. var params = new Params(); //Params collection, will hold Param objects
  11.  
  12. /**
  13. * This function will "grab" the current query string and
  14. * will save it to our Params Collection
  15. *
  16. * It's a anonymous function, will be executed each time
  17. * we create a new QueryString instance
  18. */
  19. var _load = (function() {
  20. var arrQryString = _qry.split("&");
  21. arrQryString[0] = arrQryString[0].replace("?", ""); //remove "?"
  22.  
  23. for (var i = 0, count = arrQryString.length; i < count; i++) {
  24. var qryPairValue = arrQryString[i].split("=");
  25. params.Add(new Param(qryPairValue[0], qryPairValue[1]));
  26. }
  27. })();
  28.  
  29. /*
  30. * Get a specific Value
  31. *
  32. * @param String Key
  33. * @return String Value
  34. */
  35. var _getValue = function(k){return params.Get(k).Value();};
  36.  
  37. /**
  38. * Get a specific Param
  39. *
  40. * @param String Key
  41. * @return Param
  42. */
  43. var _getParam = function(k){return params.Get(k);};
  44.  
  45. /**
  46. * Get Params collection
  47. *
  48. * @return Params
  49. */
  50. var _getParams = function(){return params;};
  51.  
  52. /**
  53. * Get number of parameters in our collection
  54. *
  55. * @return Int
  56. */
  57. var _count = function(){return params.Count();};
  58.  
  59. /**
  60. * toString overload
  61. *
  62. * @return String
  63. */
  64. var _output = function(){return params.toString();};
  65.  
  66. /**
  67. * Print our QueryString
  68. *
  69. * @param String Html Object
  70. */
  71. var _console = function(id){if($(id)){$(id).innerHTML = _output();}};
  72.  
  73. /**
  74. * Autocomplete all form fields
  75. */
  76. var _autoCompleteForm = function(){
  77. for (var i=0, _keys=params.GetKeys(), count=_keys.length; i<count;i++){_fillFormField(_keys[i]);}
  78. }
  79.  
  80. /**
  81. * Fill a field with its correspondent Param value
  82. *
  83. * @param String Query String Key
  84. * @param Optional String Form Field, if not specified it will be equal to Key
  85. */
  86. var _fillFormField = function(key /**, field */){
  87. var field=$(arguments[1] || key);
  88. if(field) {field.value = _getValue(key);}
  89. }
  90.  
  91. /**
  92. * Create DropdownList
  93. *
  94. * @param String DropdownList
  95. * @param String Label
  96. * @param String Label
  97. */
  98. var _fillDropDownList = function(ddl, k, v){
  99. var ddList=$(ddl);
  100. if(ddList){
  101. var _keys=params.GetKeys();
  102.  
  103. ddList.options.add(_createDDListOption("","(pick a key)"));
  104. for (var i=0, count=_keys.length; i<count;i++){
  105. ddList.options.add(_createDDListOption(_keys[i],"Key: "+_keys[i]));
  106. }
  107.  
  108. //add event onchange to our DropDownList
  109. Events.AddEvent(ddList,"change",function(){
  110. var key="", value="";
  111. if (this.value){
  112. key=this.value;
  113. value=_getValue(this.value);
  114. }
  115. else {
  116. key="";
  117. value="";
  118. }
  119.  
  120. if($(k)){$(k).innerHTML=key;}
  121. if($(v)){$(v).innerHTML=value;}
  122. }
  123. );
  124. }
  125. };
  126.  
  127. /**
  128. * Create a DropDownList Option
  129. *
  130. * @param String Value
  131. * @param String Text
  132. */
  133. var _createDDListOption = function(value, text){
  134. var ddlOption = document.createElement("option");
  135. ddlOption.value = value;
  136. ddlOption.text = text;
  137. return ddlOption;
  138. };
  139.  
  140. return {
  141. GetValue: _getValue,
  142. GetParam: _getParam,
  143. GetParams: _getParams,
  144. Count: _count,
  145. AutocompleteForm: _autoCompleteForm,
  146. FillField: _fillFormField,
  147. FillDropDownList: _fillDropDownList,
  148. ToString: _output,
  149. Verbose: _console
  150. };
  151. };
  152.  




Init.js, where it all begins ^_^''; we'll had the onload window event, that will trigger our Init function, see the comments in this file, it explains what it's doing;
  1. /**
  2. * Init function
  3. *
  4. * @author pedrocorreia.net
  5. */
  6. Init = function() {
  7. var q = new QueryString();
  8.  
  9. //print the query string
  10. q.Verbose("console");
  11.  
  12. //fill dropdown list with query string keys
  13. q.FillDropDownList("ddListKeys","lbl_key","lbl_value");
  14.  
  15. //check if we submitted the form
  16. if(q.Count()>0){
  17.  
  18. //fill our field "name"
  19. var FillTxtName = (function(field) {
  20. var param = q.GetParam(field);
  21. $(field).value = param.Value();
  22. }) ("name");
  23.  
  24. //fill our field "soccer_team"
  25. q.FillField("soccer_team");
  26.  
  27. //or we can simply use
  28. q.AutocompleteForm();
  29. }
  30. }
  31.  
  32. Events.AddEvent(window,"load",Init);




HttpGetVar.htm, our static html file;
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5.  
  6. <title>Http Get Query String Variables</title>
  7.  
  8. <script type="text/javascript" src="Events.js"></script>
  9. <script type="text/javascript" src="Dom.js"></script>
  10. <script type="text/javascript" src="QueryStringParameters.js"></script>
  11. <script type="text/javascript" src="QueryString.js"></script>
  12. <script type="text/javascript" src="Init.js"></script>
  13.  
  14. </head>
  15. <body>
  16. <span id="console"></span>
  17. <br />
  18. <label for="ddListKeys">QueryString Keys</label> <select id="ddListKeys"></select>&nbsp;
  19. <span id="lbl_key"></span> <span id="lbl_value"></span>
  20.  
  21. <br /><br /><br />
  22. <form method="get" id="my_form" action="">
  23. <label for="name">Name</label> <input type="text" name="name" id="name" />
  24. <label for="age">Soccer Team</label> <input type="text" name="soccer_team" id="soccer_team" />
  25. <input type="submit" value="Test Javascript Http Get Var" />
  26. </form>
  27. </body>
  28. </html>






Here's a short video of this script working:










If you have any doubt or found any error, please drop me an email.








clicks: 12777 12777 2009-03-08 2009-03-08 goto mySnippets mySnippets javascript  Download  Bookmark This Bookmark This