user12073145
user12073145

Reputation:

Rails Ajax: Search still refreshing the page after click

I am working on the search app using jquery ui rails gem.

Here's my set up.

HTML:

 <%= form_tag(contacts_path, class: "form-inline", role: "search", method: :get, remote: true) do %>
           <%= text_field_tag :term, params[:term], class: "form-control search-input", id: "term", placeholder: "Search..", autocomplete: "off" %>
           <%= hidden_field_tag :category_id, params[:category_id] %>
           <button class="btn btn-primary btn-lg main-btn search-btn" type="submit">Search</button>
      <% end %>

Notice that I place remote:true in the form. And then on my contacts controller:

 def autocomplete
    if params[:category_id] && !params[:category_id].empty? 
      category_find = Category.find(params[:category_id])
      @contacts = category_find.contacts.search(params[:term]).order(created_at: :desc).page params[:page]
      render json: @contacts.map { |contact| { id: contact.id, value: contact.name }}
    else 
      @contacts = Contact.search(params[:term]).order(created_at: :desc).page params[:page]
      render json: @contacts.map { |contact| { id: contact.id, value: contact.name }}
    end
  end

Then on my routes:

scope '/dashboard' do
    resources :contacts do
      collection do
        get 'autocomplete'
      end
    end
  end 

I've added an index.js.erb file to re-render my contacts list via my kaminari pagination gem:

$('#contacts').html('<%= j(render @contact) %>');
$('#paginator').html('<%= j(paginate(@contacts, remote: true)) %>');

What I am expecting to happen here is that since I place a remote:true on my search bar I expect when I click in an autocomplete item it will not refresh the page but right now it is still refreshing the page:

enter image description here

Any idea why is this so?

Upvotes: 4

Views: 85

Answers (1)

Bui Duy
Bui Duy

Reputation: 46

Your render method will refresh your page

Upvotes: 1

Related Questions