I have this view called posts.blade.php
which gets included in home.blade.php
:
<div id="posts">
@foreach ($posts as $post)
<div class="list-item clearfix">
<div class="content">
<img src="{{ URL::to($post->thumbnail) }}" alt="" />
<h1>{{{ $post->title }}}</h1>
</div>
<div class="score">{{ $post->rating }}</div>
</div>
@endforeach
<div id="pagination">{{{ $posts->links() }}}</div>
</div>
When a user searches for certain posts, the controller's postSearch()
function returns a JSON response:
function postSearch()
{
$posts = $posts->select(...)->where(...)->orderBy(...)->paginate(5); //Search posts
return Response::json(View::make('includes.posts', ['posts' => $posts])->render());
}
And jQuery appends the HTML on the #posts
div:
$('#search').submit(function(e) {
e.preventDefault();
var form = $(this);
$.post(form.attr('action'), form.serialize(), function(data) {
$('#posts').html(data);
});
});
This works perfect. But now when I click on a pagination link, the page reloads and my search results are gone (obvious). How do I paginate these posts? I've read this, this and this article, but I don't understand how to implement it.
Edit
This is my jQuery for the pagination so far:
$('#posts').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href'),
page = url.split('page=')[1],
data = $('#search').serializeArray();
data.push({page: page}); // Add page variable to post data
console.log(data);
$.post($('#search').attr('action'), data, function(data) {
$('#posts').html(data['posts']);
});
});
This is data is being send when I click on a pagination link (page 2):
Unfortunately nothing happens, the posts from page 1 keep showing.