Skip to content

Instantly share code, notes, and snippets.

@arcanoix
Forked from tobysteward/BlogController.php
Created September 7, 2017 16:33
Show Gist options
  • Save arcanoix/d412534dfd57016ab95482544000b95e to your computer and use it in GitHub Desktop.
Save arcanoix/d412534dfd57016ab95482544000b95e to your computer and use it in GitHub Desktop.
Laravel AJAX Pagination with JQuery
<!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 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));
}
}
<?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');
}
@foreach ($posts as $post)
<article>
<h2>{{ $post->title }}</h2>
{{ $post->summary }}
</article>
@endforeach
{{ $posts->links() }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment