gavinhewitt
8/6/2013 - 12:03 PM

Laravel AJAX Pagination with JQuery

Laravel AJAX Pagination with JQuery

@foreach ($posts as $post)

    <article>
        <h2>{{ $post->title }}</h2>
        {{ $post->summary }}
    </article>

@endforeach

{{ $posts->links() }}
<!doctype html>
<html lang="en">
<head>

    <meta charset="utf-8">

    <title>Laravel AJAX Pagination with JQuery</title>

</head>
<body>

    <h1>Posts</h1>

    <div class="posts">
        @include('posts')
    </div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script>

    $(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            } else {
                getPosts(page);
            }
        }
    });

    $(document).ready(function() {
        $(document).on('click', '.pagination a', function (e) {
            getPosts($(this).attr('href').split('page=')[1]);
            e.preventDefault();
        });
    });

    function getPosts(page) {
        $.ajax({
            url : '?page=' + page,
            dataType: 'json',
        }).done(function (data) {
            $('.posts').html(data);
            location.hash = page;
        }).fail(function () {
            alert('Posts could not be loaded.');
        });
    }

    </script>

</body>
</html>
<?php

class Post extends Eloquent
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'posts';

    /**
     * Define guarded columns
     *
     * @var array
     */
    protected $guarded = array('id');
}
<?php

class BlogController extends Controller
{
    /**
     * Posts
     *
     * @return void
     */
    public function showPosts()
    {
        $posts = Post::paginate(5);

        if (Request::ajax()) {
            return Response::json(View::make('posts', array('posts' => $posts))->render());
        }

        return View::make('blog', array('posts' => $posts));
    }
}