102

I'm trying to find a way to use jQuery autocomplete with callback source getting data via an ajax json object list from the server.

Could anybody give some directions?

I googled it but couldn't find a complete solution.

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
RollRoll
  • 8,133
  • 20
  • 76
  • 135

6 Answers6

142

Perfectly good example in the Autocomplete docs with source code.

jQuery

<script>
  $(function() {
    function log( message ) {
      $( "<div>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );
    }

    $( "#city" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          url: "http://gd.geobytes.com/AutoCompleteCity",
          dataType: "jsonp",
          data: {
            q: request.term
          },
          success: function( data ) {
            response( data );
          }
        });
      },
      minLength: 3,
      select: function( event, ui ) {
        log( ui.item ?
          "Selected: " + ui.item.label :
          "Nothing selected, input was " + this.value);
      },
      open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });
  });
</script>

HTML

<div class="ui-widget">
  <label for="city">Your city: </label>
  <input id="city">
  Powered by <a href="http://geonames.org">geonames.org</a>
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
  Result:
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
Michel Ayres
  • 5,891
  • 10
  • 63
  • 97
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • 14
    this is a jquery ui example. – Rafael Herscovici Jul 16 '13 at 10:43
  • 4
    @RNKushwaha If you notice, there's a function at the top for logging called `log`. – corsiKa Mar 06 '16 at 20:34
  • I can't understand how `success: function( data ) {response( data );} works inside the ajax call. I mean, what is that `response()` function? It creates some `
  • `elements according to data but if I want to customize that `
  • ` elements, what should I do? I would like to add a pair of attributes...
  • – SagittariusA Mar 10 '16 at 11:22
  • 2
    I am working in Rails, and my controller returns, format.json { render json: @products.map(&:name).to_json }, and i had to remove the datatype: "jsonp" in the example above in order for it to work. – frank Jun 04 '16 at 22:31
  • 1
    @michel , please remove the word "p" from dataType: "jsonp" – selvan Dec 24 '20 at 06:34