AUTOCOMPLETE WITH AJAX IN RAILS
Autocomplete with Ajax in rails
index.html.erb page:-
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>
<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