AUTOCOMPLETE WITH AJAX IN RAILS

Autocomplete with Ajax in rails

index.html.erb page:-

 <%= f.text_field :store_name, id: "store_shop" %>

controller :-

class StaticController < ApplicationController
  def index; end

  def search
    if params['search'].size > 2
        result = search_shop(params['search'])
      found  = result.present? ?  result.map{|x| x["name"]} : result
      render :json => found
    else
      render :json => []
    end
  end
end

javascript :-

// calling the third api from autocomplete
<script>
  $(function() {
    function log( message ) {
      $( "<div>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );
    }

    $( "#
store_shop" ).autocomplete({
      source: function( request, response ) {
       $.ajax({
          type: "get",
          url: "/static/brewery/",
          data: { search: request.term },
          dataType: "json",
          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>

or we can also use keyup for getting the data from api :-

<script>
  $(document).ready(function(){
    $("#
store_shop").keyup(function(){
      var text = this.value
      if (text.length >= 2 ) {
       $.ajax({
          type: "get",
          url: "/static/search/",
          data: { search: text },
          success: function(response) {
            show_data(response)
            $("#ui-id-1").css("display", "block");
          }
        });
      }
    });
    function show_data(tags) {
       $( "#store_shop" ).autocomplete({
        source: tags
      });
    }
  });
</script>


https://stackoverflow.com/questions/9656523/jquery-autocomplete-with-callback-ajax-json
https://jqueryui.com/autocomplete/




Comments

Popular posts from this blog

psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

CARRIERWAVE - UPLOAD ANY MEDIA (AUDIO , VIDEO AND IMAGE ) FILE IN RAILS

SELECT COUNTRY WITH STATE AND IT'S CITIES RAILS

RAILS: UPLOADING PHOTOS VIA AMAZON S3 AND PAPERCLIP (UPLOADING FILES TO S3 IN RUBY WITH PAPERCLIP)

SEARCHING USING AJAX IN RAILS

UPLOAD ANY MEDIA FILE IN RAILS USING PAPERCLIP

UNINITIALIZED CONSTANT PAPERCLIP::STORAGE::S3::AWS

CURL COMMAND ON RUBY ON RAILS

CHECK PASSENGER RUBY PATH