Search code examples
jqueryruby-on-railssunspot

How should I use jQuery with Sunspot in Rails?


I just want to display the search result in the same page without redirecting to default search link like ".....search=&commit=Search". My original intention is use jQuery to render the same form with the search result. And the remote option is set below

>   <%= form_tag index_by_dvp_path,:method => :get do %>
>        <p>
>           <%= text_field_tag :search, params[:search] %>
>           <%= submit_tag "Search",remote: true %>
>        </p>
>        <% end %>

But when I click the search button, the page still redirects to the default link as I mentioned.

I'm not sure where it the problem.


Solution

  • You can use the :remote => true option for the search form

    <%= form_tag index_by_dvp_path,:method => :get, :remote => true do %>
      <p>
       <%= text_field_tag :search, params[:search] %>
       <%= submit_tag "Search",remote: true %>
      </p>
    <% end %>
    

    and submit the form to an action that will fetch the results of your search in controller. Also respond with format.js in the same method

    def index_by_dvp
      @values = Model.where(params[:search])
    
      respond_to do |format|
        format.js
      end
    end
    

    in index_by_dvp.js.erb

    $('#your_div_for_search_result').html("<%= escape_javascript(render :partial => 'your_search_partial')%>")