Reputation: 69
So i'm trying to make a simple ajax call in rails 3 but can't get the ajax to return properly. I think I'm missing something obvious but I've been trying for the past 3 hours so I figured it's time to ask.
I'm attempting the ajax call on the index page of the post model which is supposed to return search results.
My posts_controller.rb for the index action looks like this.
def index
@posts = Post.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.js #ajax call
format.json { render json: @posts }
end
end
My index.html.erb (which contains the search text field and div where (ajax) results are to be returned looks like this
<%= form_tag posts_path, :method => "get", :remote => true do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :class => "btn", :name => nil %>
<% end %>
<div id="posts">
<%= render @posts %>
</div>
My _post.html.erb looks like this
<table>
<tr>
<td class="well well-small"><%= post.title %></td>
<td class="well"><%= post.content %></td>
<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<br />
<br />
</table>
My index.js.erb looks like this
$("#posts").html("<%= escape_javscript(render :partial => "new" ) %>");
and my post.rb model page looks like this
class Post < ActiveRecord::Base
attr_accessible :content, :title
def self.search (search)
if search
find(:all, :conditions => ['title LIKE ?', "%#{search}%"])
else
find(:all)
end
end
end
Sorry there has to be so much code just wanted to show everything relevant. For some reason my search results aren't being updated with ajax. When I remove the :remote => true from the form in index.html.erb and remove the index.js.erb file, the search results are returned fine(without ajax) so my search functionality is not the problem.
Thanks in advance for your help. As always if you give me a good answer, I will accept it as the right one.
Upvotes: 0
Views: 140
Reputation: 783
The problem is that you're not re-rendering your new collection of posts, you're rendering the 'new' partial!
Try this instead on your index.js.erb file:
$("#posts").html("<%= j(render :collection => @posts ) %>");
Do not change anything else from what you posted and it should work.
Upvotes: 1
Reputation: 163
If I understand your problem, after your ajax request you want update your view: so I would try something like this in your posts_controller.rb:
format.js do
render :update do |page|
page.replace_html 'id_of_your_refreshed_element', :partial => 'partial_content_refreshed'
end
end
It should work. Your partial_view will take in consideration your new @posts variable.
I hope It will help you.
Upvotes: 0