lat4732's avatar
Level 12

AJAX results pagination problem

Hey, @everyone!

I'm paginating my results which are displayed through AJAX request but I'm facing a problem with the pagination. Here's my pagination logic:

function showReviews(page = 1) {
       return $.get(searchUrl(page)).done(function (reviews) {
       // ....
       });
});
if(reviews.pagination.next_page_url != null || reviews.pagination.current_page != 1) {
    var paginat = "";
    paginat = paginat + '<nav role="navigation" aria-label="Pagination Navigation" class="pagination__wrapper add_bottom_15 flex items-center justify-between"><div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between"><div class="pagination"><span class="d-flex">';
    for (let p = 1; p <= reviews.pagination.last_page; p++) { 
        if (p === reviews.pagination.current_page) {
            paginat = paginat + '<span class="d-inline" aria-current="page"><a class="active">' + p + '</a></span>';
        } else { 
            paginat = paginat + '<a class="d-inline" onclick="showReviews('+p+')">' + p + '</a>';
        }
    }

    paginat = paginat + '</span></div></div></nav>';
    
    $(paginat).appendTo("#reviews-pages");
}

Here is an image what happens when the results are too many. How to minify this with .. (dots) between the page numbers?

This is how I return pagination info:

return response()->json([
    'pagination' => collect($reviews->toArray())->except('data'),
   // ....
]);
0 likes
8 replies
fylzero's avatar

@laralex Add your pagination links to an array, then use slice() to grab the first 3 (or whatever you want) items, then do a slice() using a negative number to grab the last 3 (whatev) items from your pagination. Then just compile as array 1, dot dot dot, array 2.

lat4732's avatar
Level 12

@fylzero Okay, but... look at this. How am I supposed to assign logic to that? I'm so confused.

links = [];
for (let p = 1; p <= reviews.pagination.last_page; p++) {
    links.push(p);
}
paginat = paginat + links.slice(0, 3) + "..." + links.slice(-3, -1);
fylzero's avatar

@Laralex I think what you have is close. Second slice should probably be links.slice(0, -2) based on your image example - assuming you only want 2 results at the end..

lat4732's avatar
Level 12

@fylzero links.slice(0, -2) is not what I expect. links.slice(-3, -1) is very close to what I need but its removing the last page. In my example the pages must be 61 and not 60. I actually expect something like this but without the next and previous buttons.

jlrdw's avatar

A server fetched partial would make things so much easier.

Please or to participate in this conversation.