Building AJAX Based Pagination Using JavaScript Calls
​This guide walks through how to implement AJAX based pagination in a Ruby on Rails application while using the Kaminari gem.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

One of the biggest advantages of Kaminari is that it allows you to use AJAX or JavaScript to implement your pagination, and in this video, we are going to do exactly that.

For this, I'm going to open my guide.

Let's create a new file called pagination.js and put in our /Javascript folder. I'm going to copy the entire code from my guide and paste it in this file. This guide is available at "https://rails.devcamp.com/ruby-gem-walkthroughs/view-template-tools/kaminari-pagination-example"

Next, go to index.html.erb in views/posts, and add remote: true to the paginate code and put it all inside a div, like this:

<!-- app/views/posts/index.html.erb -->

<div id="paginator">
  <%= paginate @posts, remote: true %>
</div>

Let's also make this change to the index file of posts.

Now, we have to create a view file that you don't get to see on the browser, but is essential for JavaScript to work. Go to /views/posts and create a new file called index.js.erb, and have this code inside it:

<!-- app/views/posts/index.js.erb -->

$('#posts').html('<%= escape_javascript render(@posts) %>');
$('#paginator').html('<%= escape_javascript(paginate(@posts, remote: true).to_s) %>');

Let's see if this works on the browser.

large

If you see, the URL remains the same and does not change from page to page.

However, the posts are not changing, so we need to fix that. If you go back to the index.js.erb file, you'll see that there are two ids, but we are using only paginator. So, let's also use posts in our code, like this:

<!-- app/views/posts/index.html.erb -->

<tbody id="posts">
  <%= render @posts %>
</tbody>

Now, it's working fine in the browser.

large

We're going to do the same for audit logs, except we're going to replace posts with audit_logs in our index.html.erb page. Also, we have to create a file called index.js.erb and have the same code in this file too, except we'll have to change to audit_logs here as well.

Now, test it in the browser, and everything should look great!

Resources