Question : auto-populate multiple select boxes

Hi everyone,

I made an application that have the following:
Master Categories
Categories
Products

The user is able to pick a Master Category and a dynamic page of Products (drop down list)  under their Categories shows up in the browser. There are configurations for each product that is assign by the administrator of the site. The user picks product 2 from category 1 and based on the configuration(s) of that product the next category change accordingly and show only the product(s) with the same configuration(s). I manage to make this application to work but with static data using multiple steps and forms but that way every time the client need to add a master category->categories->products, I have to create new steps with forms for the new master category->categories->products. So the clients want it dynamic and that leaves me with only one option, to use ajax that i'm not very familiar with. I have found a ajax code and trying to adapt it to the current application but without luck.

The trick to get the configuration of the product select and use it to get the products based on that configuration from the next category.
But it does not works as indented and I cant think anything more. Can someone please help?
The ajax code is using jquery 1.1.1 and is as follows:
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
select-chain.js
 
(function ($) {
    $.fn.selectChain = function (options) {
        var defaults = {
            key: "id",
            value: "label"
        };
        
        var settings = $.extend({}, defaults, options);
        
        if (!(settings.target instanceof $)) settings.target = $(settings.target);
        
        return this.each(function () {
            var $$ = $(this);
            
            $$.change(function () {
                var data = null;
                if (typeof settings.data == 'string') {
                    data = settings.data + '&' + this.name + '=' + $$.val();
                } else if (typeof settings.data == 'object') {
                    data = settings.data;
                    data[this.name] = $$.val();
                }
                
                settings.target.empty();
                
                $.ajax({
                    url: settings.url,
                    data: data,
                    type: (settings.type || 'get'),
                    dataType: 'json',
                    success: function (j) {
                        var options = [], i = 0, o = null;
                        
                        for (i = 0; i < j.length; i++) {
                            // required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
                            o = document.createElement("OPTION");
                            o.value = typeof j[i] == 'object' ? j[i][settings.key] : j[i];
                            o.text = typeof j[i] == 'object' ? j[i][settings.value] : j[i];
                            settings.target.get(0).options[i] = o;
                        }
 
                        // hand control back to browser for a moment
                        setTimeout(function () {
                            settings.target
                                .find('option:first')
                                .attr('selected', 'selected')
                                .parent('select')
                                .trigger('change');
                        }, 0);
                    },
                    error: function (xhr, desc, er) {
                        // add whatever debug you want here.
                        alert("an error occurred");
                    }
                });
            });
        });
    };
})(jQuery);
 
 
the page that show the categories and the products
show_all.php
    
 
	foreach ($queryA->result() as $row3)
	{
		echo "
$row3->desc
\n"; echo ""; $queryC = $this->db->query("SELECT * FROM products_config where id='$row4->id'"); foreach ($queryC->result() as $row5) { echo "id[]\" value=\"$row5->cid\">\n"; } } The file that is called by show_all.php get_data.php db->query('SELECT * FROM products WHERE mastcat_id='. $_GET['mastcat_id'].' and products.id='.$_REQUEST['category'] .''); $json = array(); foreach ($results->result() as $row) { $json[] = '{"id" : "' . $row->cid . '", "label" : "' . $row->desc . '"}'; $json[] = '"' . $row->cid . '"'; } echo '[' . implode(',', $json) . ']'; die(); // filthy exit, but does fine for our example. ?> Mysql is as follows: This table holds the categories. Each category have a unique id, the master category it belongs to and the category description. categories id(unique) mastcat_id desc 1 2 category1 2 2 category2 3 2 category3 4 3 category4 5 3 category5 6 3 category6 This table holds the configurations Each configuration have a unique id and the configuration description. configurations id(unique) desc 4 None 5 Config1 6 Config2 7 Config3 8 Config4 9 Config5 10 Config6 11 Config7 This tables holds master categories Each master category have a unique id and the master category description. master_categories mastcat_id(unique) mastcat_desc 1 None 2 MastCat1 3 MastCat2 4 MastCat3 5 MastCat4 6 MastCat5 This table holds the products Each product have a unique id, the product description the category it belongs to and the master category it belongs to. products id(unique) desc cat_id mastcat_id 1 Description 1 2 2 Description 1 2 3 Description 2 2 4 Description 2 2 5 Description 3 2 6 Description 3 2 7 Description 4 3 8 Description 4 3 9 Description 5 3 10 Description 5 3 11 Description 6 3 This tables holds the products and the configurations of each product The field id is the product id and it's not unique, a product will have more 2,3 or more configurations attached to it. The field cid is the configuration id of the product products_config id cid 1 4 1 5 1 6 2 7 2 7 2 8 2 9 3 4 3 7 3 9 3 5 4 4 4 5 4 6 4 10
Open in New Window Select All

Answer : auto-populate multiple select boxes

See if this is anywhere near what you need.

Included 3 files.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
FILE-----formHandler.js
 
var xmlHttp = createXmlHttpRequestObject();
 
function createXmlHttpRequestObject() {
   var xmlHttp;
   try {
      xmlHttp = new XMLHttpRequest();
   } catch(e) {
      xmlHttp = false;
   }
   if(!xmlHttp) {
      alert("Error creating the xmlHttpRequest object");
   } else {
      return xmlHttp;
   }
}
 
function getMaster() {
   if(xmlHttp) {
      try{
         xmlHttp.open("GET", "formEvents.php?action=getmaster", true);
         xmlHttp.onreadystatechange = handleMasterResponse;
         xmlHttp.send(null);
      } catch(e) {
         alert("Can't connect to server:\n"+e.toString());
      }
   } else {
      alert("problem connecting to formEvents.php")
   }
}
 
function handleMasterResponse() {
   if(xmlHttp.readyState == 4) {
      if(xmlHttp.status == 200) {
         try {
	    var masterHTML = '';
            document.getElementById('masterSelect').innerHTML = masterHTML
         } catch(e) {
            alert("Error reading the response: "+e.toString());
         }
      } else {
         alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
      }
   }
}
 
function requestCategories() {
   var masterCatId = document.products.masterCats.options[document.products.masterCats.selectedIndex].value;
   if(xmlHttp) {
      try{
         xmlHttp.open("GET", "formEvents.php?action=getcategories&id="+masterCatId, true);
         xmlHttp.onreadystatechange = handleCategoriesResponse;
         xmlHttp.send(null);
      } catch(e) {
         alert("Can't connect to server:\n"+e.toString());
      }
   } else {
      alert("problem connecting to formEvents.php")
   }
}
 
function handleCategoriesResponse() {
   if(xmlHttp.readyState == 4) {
      if(xmlHttp.status == 200) {
         try {
	    var categoriesHTML = xmlHttp.responseText;
            document.getElementById('categories').innerHTML = categoriesHTML
         } catch(e) {
            alert("Error reading the response: "+e.toString());
         }
      } else {
         alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
      }
   }
}
 
function requestProducts(cat) {
   var masterCatId = document.products.masterCats.options[document.products.masterCats.selectedIndex].value;
   var productId = document.getElementById('category'+cat).options[document.getElementById('category'+cat).selectedIndex].value;
   if(xmlHttp) {
      try{
         xmlHttp.open("GET", "formEvents.php?action=getproducts&prod_id="+productId+"&cat_id="+(cat+1)+"&mast_cat_id="+masterCatId, true);
         xmlHttp.onreadystatechange = function() {
	    handleProductsResponse(cat);
	 };
         xmlHttp.send(null);
      } catch(e) {
         alert("Can't connect to server:\n"+e.toString());
      }
   } else {
      alert("problem connecting to formEvents.php")
   }
}
 
function handleProductsResponse(cat) {
   if(xmlHttp.readyState == 4) {
      if(xmlHttp.status == 200) {
         try {
	    var nextCat = document.getElementById('category'+(cat+1));
	    for(var i = nextCat.options.length - 1; i >= 0; i--) {
	       nextCat.remove(i);
	    }
	    var productsSelectBox = xmlHttp.responseText;
            eval(productsSelectBox);
         } catch(e) {
            alert("Error reading the response: "+e.toString());
         }
      } else {
         alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
      }
   }
}
 
 
 
FILE    form.htm





   
      


FILE formEvents.php '.$rwMasterCats['mastcat_desc'].''; } } function getCategories($master_id) { global $dbcon; $sqlSelectCatsAndProducts = "SELECT products.id AS product_id, products.desc AS product_desc, categories.id AS cat_id, categories.desc AS cat_desc FROM products, categories WHERE categories.mastcat_id = ".$master_id. " AND products.cat_id = categories.id"; $rsSelectCatsAndProducts = mysqli_query($dbcon, $sqlSelectCatsAndProducts); $categories = array(); while($rwCatsAndProducts = mysqli_fetch_assoc($rsSelectCatsAndProducts)) { $categories[$rwCatsAndProducts['cat_id']][0]['product_desc'] = $rwCatsAndProducts['cat_desc']; $categories[$rwCatsAndProducts['cat_id']][0]['product_id'] = 0; $categories[$rwCatsAndProducts['cat_id']][$rwCatsAndProducts['product_id']]['product_desc'] = $rwCatsAndProducts['product_desc']; $categories[$rwCatsAndProducts['cat_id']][$rwCatsAndProducts['product_id']]['product_id'] = $rwCatsAndProducts['product_id']; } foreach($categories as $cat_id => $value){ echo ''; } } function getProducts($productId, $categoryId, $masterCatId){ global $dbcon; $sqlSelectProducts = 'SELECT DISTINCT products_config.id AS id, products.desc AS description FROM products_config, products WHERE cid IN (SELECT products_config.cid FROM products_config WHERE products_config.id = '.$productId.') AND products.cat_id = '.$categoryId.' AND products.mastcat_id = '.$masterCatId.' AND products.id = products_config.id'; $rsSelectProducts = mysqli_query($dbcon, $sqlSelectProducts); $productsSelectBox = ''; $i=0; while($rsProducts = mysqli_fetch_assoc($rsSelectProducts)){ $productsSelectBox .= 'var optn'.$i.' = document.createElement("option");'. 'optn'.$i.'.text = "'.$rsProducts['description'].'";'. 'optn'.$i.'.value = "'.$rsProducts['id'].'";'. 'document.getElementById("category'.$categoryId.'").options.add(optn'.$i.');'; $i++; } echo $productsSelectBox; } switch ($_GET['action']) { case 'getmaster': getMaster(); break; case 'getcategories': $master_id = mysqli_real_escape_string($dbcon, $_GET['id']); getCategories($master_id); break; case 'getproducts': $product_id = mysqli_real_escape_string($dbcon, $_GET['prod_id']); $category_id = mysqli_real_escape_string($dbcon, $_GET['cat_id']); $master_cat_id = mysqli_real_escape_string($dbcon, $_GET['mast_cat_id']); getProducts($product_id, $category_id, $master_cat_id); break; }
Open in New Window Select All
Random Solutions  
 
programming4us programming4us