Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dionarap's avatar

Pagination with Ajax/Jquery

I'm trying to create a pagination of my comments with Ajax and Jquery so i can swap the pages without reloading the whole page. Unfortunately i encounter a 500 error using my current code. Can anyone where i've gone wrong and how i'd rectify the issue?

Controller:

public function getSingle($slug, Request $request)
{
//fetch from the database based on slug.
$product = Product::where('slug', '=', $slug)->first();
$comment = Comment::where('product_id', '=', $product->id)->paginate(2);

if($request->ajax())
{
    $comment = Comment::where('products_id', '=', $product->id)->paginate(2);
    return view('products.single', compact('comment'))->render();
}


//return view
return view('products.single')->withProduct($product)->withComment($comment);

} HTML:

<div class="comment-holder">
@foreach($comment as comments)
<div class="comment">
<h1>{{$comments->title}}</h1>
<p>{{$comments->comment}}</p>
</div>
@endforeach
<div class="text-center">{{$comment->links('partials.pagination')}}</div>
</div>

JS(Ajax, Jquery):

$('.container').on('click', '.pagination a', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
    url: url,
    success:function(data)
    {
        $('.comment-holder').html(data);
    }
});
});
0 likes
1 reply
Cronix's avatar
Cronix
Best Answer
Level 67
if($request->ajax())
{
    $comment = Comment::where('products_id', '=', $product->id)->paginate(2);
    return response()->json([
        'view' => view('products.single', compact('comment'))->render()
    ]);
}
    success:function(data)
    {
        $('.comment-holder').html(data.view);
    }

products.single should only return the view partial, not an entire html page (like shouldn't include the master layout with <html> tags, etc).

Please or to participate in this conversation.