I've reproduced the code from RailsCasts episode 240. I have no idea why with this code the Ajax requests don't work. The search function works with the normal method (reload page) sadly not through Ajax. The sort function works not at all.
I've included following JavaScript libraries:
If you need more information please let me know. I hope really you can help me to solve the problems.
users_controller.rb
def index
@users = User.search(params[:search]).order(sort_column + " " + sort_direction)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
end
end
def sort_column
User.column_names.include?(params[:sort]) ? params[:sort] : "lastname"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
index.html.erb
<h1>Listing users</h1>
<%= form_tag users_path, :method => 'get', :id => "users_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<div id="users">
<%= render 'users' %>
</div>
<% end %>
_users.html.erb
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<table class="pretty">
<tr>
<th><%= sortable "Last name" %></th>
<th><%= sortable "First name" %></th>
</tr>
<% for user in @users %>
<tr>
<td><%= user.lastname %></td>
<td><%= user.firstname %></td>
</tr>
<% end %>
</table>
index.js.erb
$("#users").html("<%= escape_javascript(render("users")) %>");
users_helper.rb
def sortable(column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}
end
application.js
$(function() {
$("#users th a").live("click", function() {
$.getScript(this.href);
return false;
});
$("#users_search input").keyup(function() {
$.get($("#users_search").attr("action"), $("#users_search").serialize(), null, "script");
return false;
});
});
Thank you for your help!
For the above code to work, you have to delete the following lines of code.
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
end
Now it works. :-)