Using will_paginate with AJAX live search with jQuery in Rails
Posted
by Mark Richman
on Stack Overflow
See other posts from Stack Overflow
or by Mark Richman
Published on 2010-03-27T19:04:04Z
Indexed on
2010/03/27
19:13 UTC
Read the original article
Hit count: 529
I am using will_paginate to successfully page through records. I am also using AJAX live search via jQuery to update my results div. No problem so far. The issue I have is when trying to paginate through those live search results. I simply get "Page is loading..." with no div update. Am I missing something fundamental?
# index.html.erb
<form id="searchform" accept-charset="utf-8" method="get" action="/search">
Search: <input id="search" name="search" type="text" autocomplete="off" title="Search location, company, description..." />
<%= image_tag("spinner.gif", :id => "spinner", :style =>"display: none;" ) %>
</form>
# JobsController#search
def search
if params[:search].nil?
@jobs = Job.paginate :page => params[:page], :order => "created_at desc"
elsif params[:search] and request.xhr?
@jobs = Job.search params[:search], params[:page]
end
render :partial => "jobs", :layout => false, :locals => { :jobs => @jobs }
end
# Job#search
def self.search(search, page)
logger.debug "Job.paginate #{search}, #{page}"
paginate :per_page => @@per_page, :page => page,
:conditions => ["description LIKE ? or title LIKE ? or company LIKE ?",
"%#{search}%", "%#{search}%", "%#{search}%"],
:order => 'created_at DESC'
end
# search.js
$(document).ready(function(){
$("#search").keyup(function() {
$("#spinner").show(); // show the spinner
var form = $(this).parents("form"); // grab the form wrapping the search bar.
var url = form.attr("action"); // grab the URL from the form's action value.
var formData = form.serialize(); // grab the data in the form
$.get(url, formData, function(html) { // perform an AJAX get, the trailing function is what happens on successful get.
$("#spinner").hide(); // hide the spinner
$("#jobs").html(html); // replace the "results" div with the result of action taken
});
});
});
© Stack Overflow or respective owner