Ad

Getting Query String With Ajax Pagination

- 1 answer

I know for a query when you add something like ->appends(['location' => $search]). It holds the search query even to the next page when you use pagination. Now i am using ajax for pagination and i have this js code for it

<script type="text/javascript">

//Pagination part
    $('.main-section').on('click', '.pagination > li > a', function (event) {
    var page = $(this).text();
    event.preventDefault();
    if ($(this).attr('href') != '#') {
        $("html, body").animate({scrollTop: 0}, "slow");
        $.request('onFilterProduct', {
            data: {page: page},

        });
    }
});
</script>

my php block has this

function onFilterProduct(){

$slug = $this->param('slug');
 $search = Input('location');

$this['ads'] = Advert
::withCount(['ratings as rating' => function ($query) {
    $query->select(DB::raw('COALESCE(avg(rating), 0)'));
}])
->whereHas('cats', function ($query) use ($slug){
                  $query->where('slug',$slug);
               })->where('location', 'LIKE', "%{$search}%")
               ->orderBy('created_at','desc')->paginate(1)->appends(['location' => $search]);
                 return [
        '#product-list' => $this->renderPartial('product-filter-partial')
    ]; 


}

It all works fine and get the correct page number when i load the first page, but when i click on the second page, it resets everything and the pagination no longer work with the location query string. How can i fix this please.

Ad

Answer

Well finally found a solution that works using javascript pushState api to update the page url without reload

 history.pushState(null, null, $(this).attr('href')); 

So my js code now looks like this

<script type="text/javascript">

//Pagination part
    $('.main-section').on('click', '.pagination > li > a', function (event) {
    var page = $(this).text();
    event.preventDefault();
    if ($(this).attr('href') != '#') {

        // Update the browser's address bar
        history.pushState(null, null, $(this).attr('href'));  

        $("html, body").animate({scrollTop: 0}, "slow");
        $.request('onFilterProduct', {
            data: {page: page},

        });
    }
});
</script>
Ad
source: stackoverflow.com
Ad