0

I have a search form that works well using the pg_search gem. I basically adapted it from Railscast #343.

However, it always reloads the page on search, whatever I try.

I have tried adding :remote => true to the form and put in a respond_to block in the controller with format.js. I have also tried creating a seperate '/search' path in routes that only returns js but my page always reloads with the params in the url.

Here's the relevant bits of code:

Form:

  <div id="search_controls">
    <form class="form-inline">
      <div class="form-group">
        <%= form_tag discover_path, :method => 'get', id: "tapes_search" do %>
          <%= text_field_tag :query, params[:query], :autocomplete => :off, id: 'search_field', class: "form-control" %>
          <%= submit_tag "Search", :name => nil, id: 'search_submit', class: 'btn btn-default' %>
        <% end %>
      </div>
    </form>
  </div>
</div>

Controller:

def index
  if params[:query]
    @tapes = Tape.search(params[:query]).order("release_date DESC", :id).paginate(:page => params[:page], :per_page => 15)
  else
    @tapes = Tape.order("release_date DESC", :id).paginate(:page => params[:page], :per_page => 15)
  end
end

Modal:

include PgSearch
pg_search_scope :search, against: [:album_name, :artist_name], 
    using: {tsearch: {dictionary: "english"}},
    ignoring: :accents

def self.text_search(query)
    search(query)
end

Route

match '/discover', to: 'tapes#index', via: 'get'

This is obviously as it stands without any ajax functionality. Would anyone mind showing me what I'd have to do for the params to be submitted discreetly without a page reload and js to be triggered in response?

I've used ajax all over my site, not sure what's holding me up here :( Thanks!

Chris Butcher
  • 73
  • 1
  • 5

2 Answers2

0

:remote => true option won't help you here and it's actually not very useful at all, but this would be a separate topic.

Generally you can handle this by:

  1. https://github.com/waymondo/turboboost -> quite easy ajax forms in rails
  2. Use ajax method in jquery. Example: http://api.jquery.com/jquery.post/
  3. Use some js framework like Ember or Angular if you are building something bigger.
Piotr Karbownik
  • 201
  • 1
  • 4
0

I recently ran into a similar issue, and had to write the AJAX API call from scratch rather than using remote => true:

jQuery(function() {
  $('form').submit(function(e) {
    var getData = $(this).serialize(); //grabs data from form input
    var formURL = $(this).attr('action'); 
    $.ajax({
      url: formURL,
      type: 'GET',
      data: getData,
      success: function(data, textStatus, jqXHR){
        $('search_controls').append(data); //this is the JS that gets triggered in response to a successful return. Data is what was returned.
      },
      error: function(jqXHR, textStatus, errorThrown){}
    });
    e.preventDefault();
  });
});

$(document).submit();
trosborn
  • 1,658
  • 16
  • 21