<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" ⁄>

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

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

corner
 
corner
<myVisitorsMap ⁄> <myVisitorsMap ⁄>

corner
 
 

<Update/ Populate DropDown using Ajax ⁄ >




clicks: 13861 13861 2008-06-21 2008-06-21 goto mySnippets mySnippets php  Download  Bookmark This Bookmark This



I won't get in detail about Ajax, nowadays almost everyone know what Ajax (Asynchronous JavaScript And XML) stands for, basically it's a technology that allow us to refresh some parts of our webpage without making a full postback. It saves resources in the "pipes", because less information's transferred. However if it's misused, for sure, it will bring some serious issues to our application. You can get more detailed information in this link.



I'll focus more in the "J" of Ajax. I'll try to give a few examples on how we can OOP JavaScript, such as: private methods; public methods; private attributes; static classes, etc.

One other thing that it'll be used is JSON (JavaScript Object Notation), quoting from Wiki: "... JavaScript Object Notation - is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate ...". In this snippet all the servers answers to our requests will be in JSON format, but we'll see it later.



Unobtrusive JavaScript's also an important part in this snippet.



But let's code and forget all this buzzwords ^_^''


Going back to the snippet, this example will try to show a possible way to update dropdowns without loading the page completely, if we just want to change some dropdown items, why take a full postback?


A fairy simple example. We have various countries and each country has some martial arts, so, by selecting a country we want to know its martial arts, can't get simpler than that. Only martial arts dropdown will be constantly updated.


style.css, nothing new in here... just to beautify the screenshots a little :)
  1. body{font-family: Tahoma, Verdana, Arial;font-size: 11px;color: #000;}
  2.  
  3. #div_main{float: left}
  4.  
  5. h3{font-family: Consolas, Tahoma, Arial;font-size: 14px;font-weight: bold;}
  6.  
  7. select{background-color: #FFFFD4;color: #000;border: 1px solid #004080;}





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 Events
  3. * Manage Events
  4. */
  5. Events = function(){}
  6.  
  7. /**
  8. * Add Event
  9. *
  10. * Full credits to (I just made a few mods):
  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) {
  22. obj.addEventListener(type, fn, false);
  23. }
  24. else {
  25. if (obj.attachEvent) {
  26. obj["e" + type + fn] = fn;
  27. obj[type + fn] = function(){
  28. obj["e" + type + fn](window.event);
  29. }
  30. obj.attachEvent("on" + type, obj[type + fn]);
  31. }
  32. }
  33. }
  34.  
  35. /**
  36. * Remove Event
  37. *
  38. * Full credits to (I just made a few mods):
  39. * http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
  40. *
  41. * @param Object
  42. * @param Object
  43. * @param Object
  44. */
  45. Events.RemoveEvent = function(obj, type, fn){
  46. if (obj.removeEventListener) {
  47. try{obj.removeEventListener(type, fn, false);} catch(e){}
  48. }
  49. else{
  50. if (obj.detachEvent) {
  51. obj.detachEvent("on" + type, fn);
  52. obj[type + fn] = null;
  53. obj["e" + type + fn] = null;
  54. }
  55. }
  56. }
  57.  





Misc.js - Static Class (remember Javascript OOP?:) Events.js is a static class also) that contains some common actions
  1. /**
  2. * Static Class Misc, contains some
  3. * miscellaneous methods/ settings
  4. */
  5. Misc = function(){}
  6.  
  7. //file that will process our requests
  8. Misc.ServerFile = "ajax.php";
  9.  
  10. /**
  11. * Hack IE to avoid HTTP Get cache problems
  12. *
  13. * @param String
  14. */
  15. Misc.AntiCacheRand = function(aurl){
  16. var rnd = encodeURI(Math.random());
  17. aurl += (aurl.indexOf("?") >= 0) ? "&foo=" + rnd : "?foo=" + rnd;
  18.  
  19. return aurl;
  20. };
  21.  
  22. /**
  23. * Activate/Deactive loading indicator that will
  24. * be shown while communication between client-server-client
  25. * is in process/ progress
  26. *
  27. * @param String Div Name
  28. */
  29. Misc.MsgLoading = function(div_name){
  30. var div = $(div_name);
  31.  
  32. if (div.style.display != "block") {
  33. var msg_loading = "Loading ...";
  34. var img = new HTMLControl("loading_animation");
  35. div.innerHTML = img.DoImage("loading.gif", msg_loading, 16, 16);
  36. div.style.display = "block";
  37. }
  38. else {
  39. div.style.display = "none";
  40. }
  41. };
  42.  
  43. /**
  44. * Create HttpRequest.
  45. * This request allow us to communicate with the server
  46. *
  47. * @return HttpRequest
  48. */
  49. Misc.CreateHttpRequest = function(){
  50. if (window.XMLHttpRequest) { // Mozilla, Safari,...
  51. http_request = new XMLHttpRequest();
  52.  
  53. if (http_request.overrideMimeType) {
  54. http_request.overrideMimeType('text/html');
  55. }
  56. }
  57. else
  58. if (window.ActiveXObject) { // IE
  59. try {http_request = new ActiveXObject("Msxml2.XMLHTTP");}
  60. catch (e) {
  61. try {http_request = new ActiveXObject("Microsoft.XMLHTTP");}
  62. catch (e) {}
  63. }
  64. }
  65.  
  66. if (!http_request) {
  67. alert('Giving up :( Cannot create an XMLHTTP instance');
  68. return false;
  69. }
  70.  
  71. return http_request;
  72. };





HtmlControl.js - It'll allow us to create/ update some HtmlControls. Here's a few examples on Private Methods (OOP Encapsulation)
  1. /**
  2. * This Class's responsible for building HtmlControls
  3. *
  4. * note: only a few HtmlControls are implemented
  5. */
  6.  
  7. /**
  8. * @author pedrocorreia.net
  9. * @param String Object Name
  10. */
  11. function HTMLControl(id){
  12. this.id = id;
  13.  
  14. /**
  15. * Private Method
  16. * Generate attribute markup for "id" and "name"
  17. *
  18. * @return String
  19. */
  20. var _GenerateID = function(){return " name='" + id + "' id='" + id + "' ";};
  21.  
  22. /**
  23. * Private Method
  24. * Add element (option) to dropdown
  25. *
  26. * @param String
  27. * @param String
  28. *
  29. */
  30. var _DropdownListAddOption = function(value, description){
  31. $(id).options.add(_DropdownListCreateOption(value, description));
  32. }
  33.  
  34. /**
  35. * Private Method
  36. * Create dropdown element (option)
  37. *
  38. * @param String
  39. * @param String
  40. */
  41. var _DropdownListCreateOption = function(value, description){
  42. var ddlOption = document.createElement("option");
  43. ddlOption.value = value;
  44. ddlOption.text = description;
  45.  
  46. return ddlOption;
  47. }
  48.  
  49. /**
  50. * Private Method
  51. * Clear dropdown itens
  52. */
  53. var _DropdownListClear = function(){$(id).options.length = 0;}
  54.  
  55. /**
  56. * Build Image
  57. *
  58. * @param String Source
  59. * @param String Title
  60. * @param int Width
  61. * @param int Height
  62. * @return String
  63. */
  64. this.DoImage = function(src, title, width, height){
  65. title = " title='" + title + "' alt='" + title + "' ";
  66. return "<img src='" + src + "' width='" + width + "' height='" + height + "' " + _GenerateID() + title + " />";
  67. };
  68.  
  69. /**
  70. * Build Dropdown
  71. *
  72. * @param Object
  73. *
  74. */
  75. this.DoDropdownList = function(arrOptions){
  76. var arr = eval(arrOptions);
  77.  
  78. _DropdownListClear();
  79. var ddl = $(this.id);
  80. var i, value, description;
  81. var count = arr.options.length;
  82.  
  83. for (i = 0; i < count; i++) {
  84. value = arr.options[i].value;
  85. description = arr.options[i].description;
  86.  
  87. _DropdownListAddOption(value, description);
  88. }
  89. }
  90. };
  91.  
  92. /**
  93. * Get HtmlControl reference
  94. *
  95. * note: this is a static method, HtmlControl class
  96. * doesn't have to be instantiated
  97. *
  98. * @param String
  99. */
  100. $ = function(element){return document.getElementById(element);};
  101.  





ajax.js -This class will trigger the server events and will process its answers for our requests. As I already said the server answer will be in JSON format, we'll use "eval" so that JavaScript understands the answer and process it as we want
  1. /**
  2. * Class Ajax's responsible for request and
  3. *
  4. * @author: pedrocorreia.net
  5. */
  6. Ajax = function(){};
  7.  
  8. //Div that contains the loading indicator
  9. Ajax.DivLoadingName="div_loading";
  10.  
  11. /**
  12. * Update Dropdown
  13. */
  14. Ajax.UpdateDropdownList = function(ddListName,ddSubListName){
  15. Misc.MsgLoading(this.DivLoadingName); //show loading indicator
  16.  
  17. var ddListValue = $(ddListName).value;
  18. var url = Misc.AntiCacheRand(Misc.ServerFile + "?action=get_options&value=" + ddListValue);
  19.  
  20. var http_request = Misc.CreateHttpRequest();
  21.  
  22. http_request.onreadystatechange = function(){
  23. var state = http_request.readyState;
  24.  
  25. //request completed and answered sucessfully
  26. if (state == 4 && http_request.status == 200) {
  27. var result = http_request.responseText;
  28.  
  29. var ddSubList = new HTMLControl(ddSubListName);
  30.  
  31. ddSubList.DoDropdownList(eval(result));
  32.  
  33. //add event onchange to the dropdown, so that can be triggered next time
  34. //we select another option
  35. Events.AddEvent(ddListName, "change", function (){Ajax.UpdateDropdownList(ddListName,ddSubListName);});
  36. Misc.MsgLoading(Ajax.DivLoadingName); //hide loading animation
  37. }
  38. }
  39.  
  40. http_request.open("GET", url, true);
  41. http_request.send(null);
  42. }
  43.  








ajax.php - the server-side file that we'll take care of our requests. In this case I just used a hard-coded solution, but normally we'll retrieve the data from a database or do other operations. Please just take a note about the answers Json format
  1. <?php
  2. $action=$_GET["action"];
  3.  
  4. if($action=="get_options"){
  5. $value=$_GET["value"]; //get the country we'll process
  6.  
  7. if($value=="japan"){
  8. $result = "
  9. ({
  10. 'options': [
  11. {'value': '','description': '(pick an item)'},
  12. {'value': 'aikido','description': 'Aikido'},
  13. {'value': 'kendo','description': 'Kendo'},
  14. {'value': 'sumo','description': 'Sumo'},
  15. {'value': 'shurikenjutsu','description': 'Shurikenjutsu'}
  16. ]
  17. });
  18. ";
  19. }
  20.  
  21. else if($value=="china"){
  22. $result = "
  23. ({
  24. 'options': [
  25. {'value': '','description': '(pick an item)'},
  26. {'value': 'tai_chi_chuan','description': 'Tai chi chuan'},
  27. {'value': 'shaolin_kung_fu','description': 'Shaolin kung fu'},
  28. {'value': 'shuai_jiao','description': 'Shuai Jiao'},
  29. {'value': 'wing_chun','description': 'Wing Chun'}
  30. ]
  31. });
  32. ";
  33. }
  34.  
  35. else if($value=="korea"){
  36. $result = "
  37. ({
  38. 'options': [
  39. {'value': '','description': '(pick an item)'},
  40. {'value': 'taekwondo','description': 'Taekwondo'},
  41. {'value': 'hapkido','description': 'Hapkido'},
  42. {'value': 'taekyon','description': 'Taekyon'},
  43. {'value': 'soobak','description': 'Soobak'}
  44. ]
  45. });
  46. ";
  47. }
  48. else{
  49. $result = "
  50. ({
  51. 'options': [
  52. {'value': '','description': '(please, pick a country)'}
  53. ]
  54. });
  55. ";
  56. }
  57. }
  58.  
  59. echo $result; //return answer
  60. ?>





Init.js, well this is where all begins. In this snippet it has some functionalities, for example it'll fill the countries dropdown (we could do this manually by adding the options directly in the dropdown, however we'll use HtmlControl class); it'll add the startup Events; and so on
  1. init = function (){
  2. var arrOptions = {
  3. "options": [
  4. {"value": "","description": "(please, pick a country)"},
  5. {"value": "japan","description": "Japan"},
  6. {"value": "china","description": "China"},
  7. {"value": "korea","description": "Korea"}
  8. ]
  9. };
  10.  
  11. var dropdownlist = "ddList";
  12. var dropdown_sublist = "ddSubList";
  13.  
  14. var ddList = new HTMLControl(dropdownlist);
  15. ddList.DoDropdownList(arrOptions);
  16. Events.AddEvent($(dropdownlist), "change", function (){Ajax.UpdateDropdownList(this.id,dropdown_sublist);});
  17. }
  18.  
  19. Events.AddEvent(window, "load", init);





index.htm
  1. <html>
  2. <head>
  3. <script type="text/javascript" src="Misc.js"></script>
  4. <script type="text/javascript" src="HtmlControl.js"></script>
  5. <script type="text/javascript" src="Events.js"></script>
  6. <script type="text/javascript" src="Ajax.js"></script>
  7. <script type="text/javascript" src="Init.js"></script>
  8. <link rel="stylesheet" type="text/css" href="style.css" media="all" />
  9. </head>
  10. <body>
  11. <h3>Please pick a country and get to know some of its Martial Arts.</h3>
  12.  
  13. <div id="div_main">
  14. Country: <select name="ddList" id="ddList"></select>
  15. Martial Art:
  16. <select name="ddSubList" id="ddSubList">
  17. <option>(please, pick a country)</option>
  18. </select>
  19. </div>
  20. <div id="div_loading"></div>
  21. </body>
  22. </html>






Here's 2 screenshots:








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









clicks: 13861 13861 2008-06-21 2008-06-21 goto mySnippets mySnippets php  Download  Bookmark This Bookmark This