Skip to content

Instantly share code, notes, and snippets.

@rorymcdaniel
Forked from tobysteward/BlogController.php
Last active November 23, 2016 18:27
Show Gist options
  • Save rorymcdaniel/5cbc3d5ecae3321433b3e11eff0fd8bf to your computer and use it in GitHub Desktop.
Save rorymcdaniel/5cbc3d5ecae3321433b3e11eff0fd8bf 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>
<table class="posts">
@include('posts')
</table>
<div class="dynamicLinks">
{{ $posts->links() }}
</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.posts);
$('.dynamicLinks').html(data.links);
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(['posts' => View::make('posts', array('posts' => $posts))->render(),
'links' => $posts->links()->toHtml()]);
}
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)
<tr>
<td>{{ $post->title }}</td>
<td>{{ $post->created_at }}</td>
</tr>
@endforeach
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment