Reputation: 2661
On my site's user pages, there's a section called "Reviews". In reviews, as you can imagine, there's a list of reviews for that user.
In the controller:
$reviews = Review::where('artist_id', $user->id)->orderBy('created_at', 'desc')->simplePaginate(5);
in the markup:
@if ($reviews->count())
<div class="artistContain">
<h3>Reviews</h3>
<div class="reviews endless-pagination" data-next-page="{{ $reviews->nextPageUrl() }}">
@foreach ($reviews as $review)
<div class="review">
{{ $review->body }}
</div>
@endforeach
<div class="pagerHolder">{!! $reviews->render() !!}</div>
</div>
</div>
@endif
Cool. It lists 5 reviews, then you have to click the pagination button which will refresh the page and show the next set of reviews.
However, I don't want users to have to refresh the page, so I'm trying out ajax.
JS:
$('body').on('click', '.pagination a', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.get(url, function(data){
$('.reviews').html(data);
});
});
Now this works. Kinda. Problem is, it'll inject the ENTIRE NEW PAGE into the reviews div. But hey, at least it brings up the right results.
How would I fix this so that the .html()
method ONLY brings me the next set of results?
Upvotes: 1
Views: 337
Reputation: 7992
You could use the load() method to load page fragments and avoid loading the entire page
// container is the id of the returned reviews container
// Change it to your returned review container id
$( ".reviews" ).load( url +" #container" );
Upvotes: 2
Reputation: 1260
You can fix this by doing following steps;
In Controller
$reviews = Review::where('artist_id', $user->id)->orderBy('created_at', 'desc')->simplePaginate(5);
if(request()->ajax())
{
return $reviews; // in case of ajax, return only data instead of view
}
else
{
return view('name-of-your-view', ['reviews' => $reviews])
}
JavaScript
$('body').on('click', '.pagination a', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.get(url, function(data){
$('.reviews').empty(); // make it empty first
$.each(data, function(i, review){
$('.reviews').append('<div class="review">'+review.body+'</div>');
});
});
});
Explanation
Controller: We need to modify the controller that when request is ajax then it will return only $reviews collection instead of complete view.
JavaScript: When data is recieved, we will first empty the $('.reviews') div and then append new reviews divs.
Note
Above code may have syntax error because I did not type it on Code Editor and I also did not test it. But this is the correct method to solve your problem.
Upvotes: 0