Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: will_paginate "Show next 10" button?

I'm using the will_paginate gem on a rails 3 app. Right now, it paginates correctly, and shows all the page numbers at the bottom for the listing, as well as the previous and next buttons.

Instead of showing page numbers, I want the pagination to behave like the Facebook news feed. That is, if I am displaying 10 items on the page currently, and the user clicks the 'next' button, the page should extend downwards, and display 20 items overall. I'm looking for a way to modify the will_paginate gem or use AJAX to accomplish this.

like image 275
Ankit Soni Avatar asked Feb 23 '23 04:02

Ankit Soni


1 Answers

Follow these for showing more results on click of button:

  • Don't use will_paginate tag in the views
  • Use AJAX for fetching the next set of results on click of "next" link

The following code will remove the page numbers and just show the next and prev buttons:

<%= will_paginate @posts, :page_links => false %>

You can find more styles for pagination here

Edited with sample AJAX:

1.Create a form which has page number as hidden field

<%= form_tag url, :id => :filter, :method => :get do%>
    <%= hidden_field_tag :page, page %>
<% end %>

2.Add a span for "More"

<span class='more-results' >More</span>

3.Javascript functions for binding the clicks and AJAX submit of the form

function  bindMoreResults() {
    jQuery("span.more-results").unbind("click");
    jQuery("span.more-results").click(
        function(e){
            e.preventDefault();
            getMoreResults();
        });
}

function getMoreResults() {
    jQuery('span.more-results').hide();
    var page_value = parseInt(jQuery("form#filter #page").val()) + 1;
    jQuery("form#filter #page").val(page_value);
    var form = jQuery("form#filter");
    jQuery.getJSON(
        form.attr("action") + ".json",
        form.serialize(),
        appendData
    );
}

function appendData(data) {
    jQuery('span.more-results').show();
//parse the data and append it
}

4.Modify the appendData accordingly. Check here for more about getJSON: http://api.jquery.com/jQuery.getJSON/

like image 164
leenasn Avatar answered Mar 04 '23 03:03

leenasn