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/




Post a Comment

Popular posts from this blog

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

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

SELECT COUNTRY WITH STATE AND IT'S CITIES RAILS

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

Building native extensions. This could take a while... ERROR: Error installing mysql: ERROR: Failed to build gem native extension.

HOW TO CALL RAILS API FROM SIMPLE HTML PAGE.

CREATE API FOR USER SIGN UP, LOGIN AND CREATE PUBLISHER WITH CURRENT USER