javascript - Rails: Need help building a basic AJAX search form and displaying results -
i trying build search form , having trouble understanding proper way use ujs in specific situation. main issue have can't figure out how take params selected in form , execute query return results of search.
i able select several "search criteria" models have using dropdown select elements , date fields. upon selecting search items build query want submit post or request , have results returned , displayed in list below search form via ajax without reloading page.
currently, have static page called search route setup as:
match '/search', to: 'search#index'
index.html.erb
<h1>search</h1> <!-- search form --> <div id="search"> <%= render 'form' %> </div> <!-- search results --> <div id="results"> </div>
i have searchcontroller 'index' action handles loading collections of items put search form dropdown menus built using collection_select() methods.
searchcontroller
class searchcontroller < applicationcontroller def index # load items display selectable search parameters build query # collections, categories, names @collections = collection.all @categories = category.all @names = name.all end def create @collection = collection.find(params[:collection][:id]) @category = category.find(params[:category][:id]) @name = name.find(params[:fullname][:id]) respond_to |format| format.html { redirect_to search_url } format.js end end end
the form using in partial: _form.htm.erb
<%= form_tag( {controller: "search"}, class: "search_form", remote: true) %> <%= label_tag("categories: ") %> <%= collection_select(:category, :id, @categories, :id, :name, {}, html_options = { multiple: false }) %> <%= label_tag("collections: ") %> <%= collection_select(:collection, :id, @collections, :id, :title, {}, html_options = { multiple: false }) %> <%= label_tag("names: ") %> <%= collection_select(:name, :id, @names, :id, :fullname, {}, html_options = { multiple: false }) %> <%= submit_tag("submit") %> <% end %>
when submit form in page see ajax request params in chrome console. tried give form_tag action in hash can't seem find route unless specify in routes.rb file.
ex,
<%= form_tag( {controller: "search", action: "create"}, class: "search_form", remote: true) %>
q: need have special route if using ajax?
q: how bring params searchcontroller action of name , it?
i first able display search query items text in results div know how action works. imagine use js/jquery append values of params submitted results div.
q: there way this?
strongly recommend go approach: search, sort, paginate ajax
by way jquery method .live() author using outdated , replaced .delegate() jquery documentation .deleate()
Comments
Post a Comment