Cascade Data Load by jQuery AJAX


/ Published in: jQuery
Save to your folder(s)

/* author : MD. MUZAHIDUL ISLAM ([email protected])
* file name : cascade-load.js
* This segment of code uses jQuery(jquery-1.7.2.js) that helps to load cascade data from sever.
* To use this code, 'div' element should contains a 'select' html element and
* needs following attributes of div element:
* class : class attribute must contain 'geo'
* load-data-container : selector of an element that will contain the response that comes from server
* url : server url to load data
*
*/


Copy this code and paste it in your HTML
  1. /**
  2.  * author : MD. MUZAHIDUL ISLAM ([email protected])
  3.  * file name : cascade-load.js
  4.  * This segment of code uses jQuery(jquery-1.7.2.js) that helps to load cascade data from sever.
  5.  * To use this code, 'div' element should contains a 'select' html element and
  6.  * needs following attributes of div element:
  7.  * class : class attribute must contain 'geo'
  8.  * load-data-container : selector of an element that will contain the response that comes from server
  9.  * url : server url to load data
  10.  *
  11.  * Sample code :
  12.  * <!-- action div -->
  13.  * <div id="parentDivId" class="geo" url="/loadGeoDistrict" load-datacontainer="#childDivId" >
  14.  * <select> <option>1</option><option>1</option></select>
  15.  * </div>
  16.  * <!-- load div -->
  17.  * <div id ="childDivId">
  18.  * </div>
  19.  * */
  20. $("document").ready(function(){
  21. $(".geo").on("change", function() {
  22. var currElement = $(this);
  23. var loadDataContainer = $(currElement.attr("load-data-container"));
  24. loadDataContainer.empty();//to clear data container element
  25. loadDataContainer.trigger("change");//to clear all child needs a trigger
  26. var url = currElement.attr("url");
  27. var firstSelectElement = currElement.find("select:first");
  28. var geoId = $(firstSelectElement).find(":selected").attr("value");
  29.  
  30. if(geoId) {
  31. loadData(url, "get", geoId).done(function(data) {
  32. loadDataContainer.html(data);
  33. });
  34. }
  35. });
  36. /**
  37.   * return data from successful AJAX request
  38.   * */
  39. function loadData(url, type, geoId) {
  40. return $.ajax(
  41. {
  42. url : url,
  43. type : type,
  44. data : {id : geoId}
  45. }
  46. );
  47. }
  48. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.