Wiki source code of Autocomplete mit AJAX
Hide last authors
author | version | line-number | content |
---|---|---|---|
![]() |
4.1 | 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//. |
![]() |
1.1 | 2 | |
![]() |
1.6 | 3 | {{figure image="FCSnapshot32.png"}} |
![]() |
4.1 | 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/]]. |
![]() |
1.6 | 5 | {{/figure}} |
![]() |
1.1 | 6 | |
![]() |
4.1 | 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. |
![]() |
1.1 | 8 | |
9 | {{code language="Javascript"}} | ||
10 | function geonamesCity( request, response ){ | ||
11 | $.ajax({ | ||
![]() |
1.7 | 12 | url: "http://api.geonames.org/searchJSON", |
![]() |
1.1 | 13 | dataType: "jsonp", |
14 | data: { | ||
![]() |
4.1 | 15 | q:"US", |
16 | country:"US", | ||
17 | lang:"EN", | ||
![]() |
1.1 | 18 | username:"ximademo", |
19 | featureClass: "P", | ||
20 | style: "full", | ||
21 | maxRows: 12, | ||
22 | name_startsWith: request.term | ||
23 | }, | ||
![]() |
4.1 | 24 | success: function( data ) { // pre-process the data |
25 | response($.map( data.geonames, function( item ) { | ||
![]() |
1.1 | 26 | return { |
27 | label: item.name + (item.adminName1 ? ", " + item.adminName1 : ""), | ||
28 | value: item.name | ||
29 | } | ||
30 | })); | ||
31 | } | ||
32 | }); | ||
33 | } | ||
34 | {{/code}} | ||
35 | |||
![]() |
4.1 | 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. |
![]() |
1.1 | 37 | |
38 | {{code language="Javascript"}} | ||
![]() |
4.1 | 39 | $("[name=tf1]").autocomplete({ |
40 | source: geonamesCity // tell the autocomplete function where it should get the data from | ||
![]() |
1.1 | 41 | }); |
42 | {{/code}} | ||
43 | |||
![]() |
4.1 | 44 | [[Download a form with the example above.>>attach:autocomplete_geonames.json]] |