Ajax Drop-down Menu

By | September 10, 2015
0
0



First, the JavaScript. Copy this code and save is as request.js

001 /*
002
003     XmlHttpRequest Wrapper
004
005     Version 1.2.2
006
007     29 Jul 2005
008
009     adamv.com/dev/
010
011 */
012
013
014
015 var Http = {
016
017     ReadyState: {
018
019         Uninitialized: 0,
020
021         Loading: 1,
022
023         Loaded:2,
024
025         Interactive:3,
026
027         Complete: 4
028
029     },
030
031
032
033     Status: {
034
035         OK: 200,
036
037
038
039         Created: 201,
040
041         Accepted: 202,
042
043         NoContent: 204,
044
045
046
047         BadRequest: 400,
048
049         Forbidden: 403,
050
051         NotFound: 404,
052
053         Gone: 410,
054
055
056
057         ServerError: 500
058
059     },
060
061
062
063     Cache: {
064
065         Get: 1,
066
067         GetCache: 2,
068
069         GetNoCache: 3,
070
071         FromCache: 4
072
073     },
074
075
076
077     Method: {Get: "GET", Post: "POST", Put: "PUT", Delete: "DELETE"},
078
079
080
081     enabled: false,
082
083     logging: false,
084
085     _get: null, // Reference to the XmlHttpRequest object
086
087     _cache: new Object(),
088
089
090
091     Init: function(){
092
093         Http._get = Http._getXmlHttp()
094
095         Http.enabled = (Http._get != null)
096
097         Http.logging = (window.Logging != null);
098
099     },
100
101
102
103     _getXmlHttp: function(){
104
105     /*@cc_on @*//*@if (@_jscript_version >= 5)
106
107         try { return new ActiveXObject("Msxml2.XMLHTTP"); }
108
109         catch (e) {}
110
111         try { return new ActiveXObject("Microsoft.XMLHTTP"); }
112
113         catch (e) {}
114
115     @end @*/
116
117         try { return new XMLHttpRequest();}
118
119         catch (e) {}
120
121
122
123         return null;
124
125     },
126
127
128
129 /*
130
131     Params:
132
133         url: The URL to request. Required.
134
135         cache: Cache control. Defaults to Cache.Get.
136
137         callback: onreadystatechange function, called when request is completed. Optional.
138
139         method: HTTP method. Defaults to Method.Get.
140
141 */
142
143     get: function(params, callback_args){
144
145         if (!Http.enabled) throw "Http: XmlHttpRequest not available.";
146
147
148
149         var url = params.url;
150
151         if (!url) throw "Http: A URL must be specified";
152
153
154
155         var cache = params.cache || Http.Cache.Get;
156
157         var method = params.method || Http.Method.Get;
158
159         var callback = params.callback;
160
161
162
163         if ((cache == Http.Cache.FromCache) || (cache == Http.Cache.GetCache))
164
165         {
166
167             var in_cache = Http.from_cache(url, callback, callback_args)
168
169
170
171             if (Http.logging){
172
173                 Logging.log(["Http: URL in cache: " + in_cache]);
174
175             }
176
177
178
179             if (in_cache || (cache == Http.Cache.FromCache)) return in_cache;
180
181         }
182
183
184
185         if (cache == Http.Cache.GetNoCache)
186
187         {
188
189             var sep = (-1 < url.indexOf("?")) ? "&" : "?"
190
191             url = url + sep + "__=" + encodeURIComponent((newDate()).getTime());
192
193         }
194
195
196
197         // Only one request at a time, please
198
199         if ((Http._get.readyState != Http.ReadyState.Uninitialized) &&
200
201             (Http._get.readyState != Http.ReadyState.Complete)){
202
203             this._get.abort();
204
205
206
207             if (Http.logging){
208
209                 Logging.log(["Http: Aborted request in progress."]);
210
211             }
212
213         }
214
215
216
217         Http._get.open(method, url, true);
218
219
220
221         Http._get.onreadystatechange =  function() {
222
223             if (Http._get.readyState != Http.ReadyState.Complete) return;
224
225
226
227             if (Http.logging){
228
229                 Logging.log(["Http: Returned, status: " + Http._get.status]);
230
231             }
232
233
234
235             if ((cache == Http.Cache.GetCache) && (Http._get.status == Http.Status.OK)){
236
237                 Http._cache[url] = Http._get.responseText;
238
239             }
240
241
242
243             if (callback_args == null) callback_args = new Array();
244
245
246
247             var cb_params = new Array();
248
249             cb_params.push(Http._get);
250
251             for(var i=0;i<callback_args.length;i++)
252
253                 cb_params.push(callback_args[i]);
254
255
256
257             callback.apply(null, cb_params);
258
259         }
260
261
262
263         if(Http.logging){
264
265             Logging.log(["Http: StartedntURL: " + url + "ntMethod: " + method +"; Cache: " + Hash.keyName(Http.Cache,cache)])
266
267         }
268
269
270
271         Http._get.send(params.body || null);
272
273     },
274
275
276
277     from_cache: function(url, callback, callback_args){
278
279         var result = Http._cache[url];
280
281
282
283         if (result != null) {
284
285             var response = new Http.CachedResponse(result)
286
287
288
289             var cb_params = new Array();
290
291             cb_params.push(response);
292
293             for(var i=0;i<callback_args.length;i++)
294
295                 cb_params.push(callback_args[i]);
296
297
298
299             callback.apply(null, cb_params);
300
301
302
303             return true
304
305         }
306
307         else
308
309             return false
310
311     },
312
313
314
315     clear_cache: function(){
316
317         Http._cache = new Object();
318
319     },
320
321
322
323     is_cached: function(url){
324
325         return Http._cache[url]!=null;
326
327     },
328
329
330
331     CachedResponse: function(response) {
332
333         this.readyState = Http.ReadyState.Complete
334
335         this.status = Http.Status.OK
336
337         this.responseText = response
338
339     }
340
341 }
342
343
344
345 Http.Init()
346
347
348
349 function json_response(response){
350
351     var js = response.responseText;
352
353     try{
354
355         return eval(js);
356
357     } catch(e){
358
359         if (Http.logging){
360
361             Logging.logError(["json_response: " + e]);
362
363         }
364
365         else{
366
367             alert("Error: " + e + "n" + js);
368
369         }
370
371         return null;
372
373     }
374
375 }
376
377
378
379 function getResponseProps(response, header){
380
381     try {
382
383         var s = response.getResponseHeader(header || 'X-Ajax-Props');
384
385         if (s==null || s=="")
386
387             return new Object()
388
389         else
390
391             return eval("o="+s)
392
393     } catch (e) { return new Object() }
394
395 }

Next, save each of these three bits of text as their own txt files.

Save this one as France.txt

1 |Valery Giscard d'Estaing|Francois Mitterrand|Jacques Chirac

Save this one as Germany.txt

1 |Helmut Kohl|Gerhard Schroder|Angela Merke

And save this one as Spain.txt

1 |Felipe Gonzalez Marquez|Jose Maria Aznar Lopez|Jose Luis Rodriguez Zapatero

Finally, the HTML to tie it all together. Copy and paste this code and save it as an HTML document, then place all five files into the same directory and run the HTML file in your browser to see it work.

001 <html>
002
003 <head>
004
005 <script src="request.js"></script>
006
007 <script>
008
009 function handleOnChange(dd1)
010
011 {
012
013   var idx = dd1.selectedIndex;
014
015   var val = dd1[idx].text;
016
017   var par = document.forms["frmSelect"];
018
019   var parelmts = par.elements;
020
021   var prezsel = parelmts["prez"];
022
023   var country = val;
024
025   if (country != "Select country")
026
027   {
028
029     Http.get({
030
031         url: "./" +  country + ".txt",
032
033         callback: fillPrez,
034
035         cache: Http.Cache.Get
036
037     }, [prezsel]);
038
039   }
040
041 }
042
043
044
045 function fillPrez(xmlreply, prezelmt)
046
047 {
048
049   if (xmlreply.status == Http.Status.OK)
050
051   {
052
053     var prezresponse = xmlreply.responseText;
054
055     var prezar = prezresponse.split("|");
056
057     prezelmt.length = 1;
058
059     prezelmt.length = prezar.length;
060
061     for (o=1; o < prezar.length; o++)
062
063     {
064
065       prezelmt[o].text = prezar[o];
066
067     }
068
069   }
070
071   else
072
073   {
074
075     alert("Cannot handle the AJAX call.");
076
077   }
078
079 }
080
081
082
083 </script>
084
085 </head>
086
087 <body>
088
089
090
091 <form name="frmSelect">
092
093 <p>
094
095 <select name="country" onChange="handleOnChange(this);">
096
097 <option>Select country</option>
098
099
100
101 <option>France</option>
102
103 <option>Germany</option>
104
105 <option>Spain</option>
106
107 </select>
108
109 </p><p>
110
111
112
113 <select name="prez">
114
115 <option>Select head of government</option>
116
117 </select>
118
119 </p>
120
121 </form>
122
123
124
125 </body>
126
127 </html>

Leave a Reply

Your email address will not be published. Required fields are marked *