Search code examples
jqueryruby-on-railsajaxsunspot

Using Ajax to return Sunspot search results


My goal here is to have my search form automatically update after search without page reload. I am using the Sunspot gem in my rails application. Any thoughts?

This is my search form search.html.haml

    - if current_user
     = link_to "Post New Job", new_job_path, class: "btn btn-primary"

    .pull-right
      =form_tag jobs_path, method:  :get, class: "form-search", id: "job-search" do
      %p
       =text_field_tag :search, params[:search], placeholder: "Job Listings", class: "input-medium search-query"
       =submit_tag "Search", :name => nil, class: "btn btn-default"

    .jobs
     =render 'jobs'

This is the jobs table that is rendered

    %table.table.table-striped
     %thead
      %tr
       %th Title
       %th Posted By
       %th Active Until

    %tbody
     - @jobs.each do |job|
      %tr
       %td= link_to job.title, job
       %td= job.author.email
       %td= job.end_date

This is the Jquery I am using in the application.js

    $(function () {

     $('#job-search').submit(function () {
      $.get(this.action, $(this).serialize(), null, 'script');
     return false;
     });
    });

My controller as it stand looks like this

      def index
       @jobs = Job.active

       @search = @jobs.search do
        fulltext params[:search]
       end
       @jobs = @search.results
      end

Even when remote is set to true after I enter the search params the results are not displayed. I am using the 'jquery-rails' gem.


Solution

  • I fixed it by adding this line of code in a file called search.js.erb

        $('#jobs').html('<%= escape_javascript(render("jobs")) %>');