Wiki source code of Autocomplete mit AJAX
Show last authors
| author | version | line-number | content |
|---|---|---|---|
| 1 | This examples demonstrates how to setup an input field with autocomplete functionality backed by data from an external web service. Here we use the web service [[Geonames>>url:http://www.geonames.org/]] and bind it to an input field via //AJAX//. | ||
| 2 | |||
| 3 | {{figure image="FCSnapshot32.png"}} | ||
| 4 | Setting up an input field with autocomplete functionality. Here we retrieve a list of cities from the web service //[[Geonames>>url:http://www.geonames.org/]]. | ||
| 5 | {{/figure}} | ||
| 6 | |||
| 7 | First of all, we need to create a function for retrieving the data from the web service and pre-processing it so that it can be used with {{formcycle/}}. For this we make use the //ajax// function provided by jQuery, see their [[help pages>>url:http://api.jquery.com/jquery.ajax/]] for further information. | ||
| 8 | |||
| 9 | {{code language="Javascript"}} | ||
| 10 | function geonamesCity( request, response ){ | ||
| 11 | $.ajax({ | ||
| 12 | url: "http://api.geonames.org/searchJSON", | ||
| 13 | dataType: "jsonp", | ||
| 14 | data: { | ||
| 15 | q:"US", | ||
| 16 | country:"US", | ||
| 17 | lang:"EN", | ||
| 18 | username:"ximademo", | ||
| 19 | featureClass: "P", | ||
| 20 | style: "full", | ||
| 21 | maxRows: 12, | ||
| 22 | name_startsWith: request.term | ||
| 23 | }, | ||
| 24 | success: function( data ) { // pre-process the data | ||
| 25 | response($.map( data.geonames, function( item ) { | ||
| 26 | return { | ||
| 27 | label: item.name + (item.adminName1 ? ", " + item.adminName1 : ""), | ||
| 28 | value: item.name | ||
| 29 | } | ||
| 30 | })); | ||
| 31 | } | ||
| 32 | }); | ||
| 33 | } | ||
| 34 | {{/code}} | ||
| 35 | |||
| 36 | Once the data has been loaded successfully, we can select the input field named //tf1// and setup the autocomplete functionality. jQuery UI offers a function for converting an input field to an autocomplete field, see [[their help pages on autocomplete>>url:http://api.jqueryui.com/autocomplete/]] for further details. The function //geonamesCity// we created for retrieving the data must be passed to the //autocomplete// function. | ||
| 37 | |||
| 38 | {{code language="Javascript"}} | ||
| 39 | $("[name=tf1]").autocomplete({ | ||
| 40 | source: geonamesCity // tell the autocomplete function where it should get the data from | ||
| 41 | }); | ||
| 42 | {{/code}} | ||
| 43 | |||
| 44 | [[Download a form with the example above.>>attach:autocomplete_geonames.json]] |