Skip to content

Instantly share code, notes, and snippets.

@tobysteward
Last active March 4, 2024 23:11
Show Gist options
  • Save tobysteward/6163902 to your computer and use it in GitHub Desktop.
Save tobysteward/6163902 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() }}
@lgugliotta
Copy link

lgugliotta commented Aug 9, 2017

I do this function for use in laravel, it's run perfectly

function ajaxPagination(){
                    $('.pagination a').on('click', function(e){
                        e.preventDefault();
                        var url = $(this).attr('href');
                        $.ajax({
                            type: 'GET',
                            url: url,
                            dataType: "html",
                            beforeSend: function(){
                                $('.selector').html("<div class='pt-sm text-center'><i class='fa fa-cog fa-spin fa-4x fa-fw' aria-hidden='true'></i>")
                             
                            },
                            success: function(dataHtml){
                                setTimeout(function(){
                                    $('.selector').html(dataHtml);
                                    ajaxPagination();
                                }, 2000);
                            },
                            error: function(){
                                $('.selector').html("<div class='pt-sm text-center'><p>Error al carga. Intente mas tarde</p></div>");
                            }
                        })
                    })
                }

@kc28
Copy link

kc28 commented Oct 30, 2017

Thank You Very Much

@Tungquantedge
Copy link

image
I have problems help me

@bezhanSalleh
Copy link

@Tungquantedge, Change line 17. if(Request::ajax()){ to 17. if(request()->ajax()){ you will be good to go.

@AhsanMalikGit
Copy link

Thnkew very much Dear.

@manishprajapatidev
Copy link

@flycoop Did you found any idea to remove #1, #2.... in the URL?

@Hasnaakhalf
Copy link

thanks worked well
but i have two paginations at the same view when i run the first one returns correct results and when run the second pagination return the results of first request ..note the two queries at the same function ..any idea to add 2 pagination with same function and same view

@notridan
Copy link

This work well, just need to put the correct url and the div you want to load data. Thanx

@sarabksidhu
Copy link

Hi,
its working properly. i have one doubt the landing page/first page shows proper result but cant see api call in network area if inspection. but when i click 2nd page or 3rd page or back to 1st page then the api calls work properly. is it possible to call api on landing page. if it is then how?
Thank you

@ZawHtettnaing
Copy link

Thank you very much dear.

@sodmond
Copy link

sodmond commented Feb 4, 2021

Thanks for this, worked fine

@terremoth
Copy link

terremoth commented Mar 21, 2021

I CONSIDER YOU A FUCK1NG GENIUS

Why we didn't think about make() views than render() it and send to JSON?
GENIUS

FUCK1NG LOVE LARAVEL TOO ❤️

@Mustafa535152
Copy link

Me Like pagination Next page click but current page checkbox checked in continue not a unchecked after next page Plz solutions ...

@princewillopah
Copy link

Thank you guy. it worked perfectly
However, i have another issue. when i clicked any of the items in the list on page 5(for example) and click the "browser Back Button", it takes me to page 1 insteady of page 5.
this is only happening in chrome. it is working well in firefox. pls help

@MotalibHossain
Copy link

Hi there! I seem to be encountering an issue with the browser buttons in my Laravel Ajax pagination. I've detailed my problem below the link. Would you be able to help me out with this? Thank you!
Issue with browser buttons in Laravel Ajax pagination

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment