Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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() }}
@rginnow

This comment has been minimized.

Copy link

@rginnow rginnow commented Sep 1, 2014

Works great! Thanks! Added some animations myself to make it look like the information would silde out and slide in.

@cozzbie

This comment has been minimized.

Copy link

@cozzbie cozzbie commented Oct 12, 2014

I cant see any routes defined. How does your url know that it should reference BlogController??

@Abusufiyan28

This comment has been minimized.

Copy link

@Abusufiyan28 Abusufiyan28 commented Dec 1, 2014

Thanks!

@flythecoopcom

This comment has been minimized.

Copy link

@flythecoopcom flythecoopcom commented Jan 19, 2015

This is great! Any idea on how to change the 'page' parameter in the url instead of adding a hash at the end?

@sunand

This comment has been minimized.

Copy link

@sunand sunand commented Feb 5, 2015

Thanks @tobysteward, you saved my day!! :)

@yusren

This comment has been minimized.

Copy link

@yusren yusren commented Feb 10, 2015

Already tested and its work! Thanks

@umbacclifford

This comment has been minimized.

Copy link

@umbacclifford umbacclifford commented Feb 16, 2015

Thanks @tobysteward :)

@adanluna

This comment has been minimized.

Copy link

@adanluna adanluna commented Mar 9, 2015

Yes!!! Thanks awesome response! I take your idea to make my solution :)

@infoshahin

This comment has been minimized.

Copy link

@infoshahin infoshahin commented Apr 7, 2015

Url not found!

Route::get('/ajax/pagination',array('before' =>'auth' ,
'uses'=>'CampaignsController@showPostspag'));

function getPosts(page) {
console.log(page);
$.ajax({
url : '/ajax/pagination?page=' + page,
dataType: 'json',
}).done(function (data) {
$('.posts').html(data);
location.hash = page;
})
}

Laravel 4.2, ajax url problem How can I solve it ?

@imink

This comment has been minimized.

Copy link

@imink imink commented Apr 17, 2015

Save my day. Thanks.

@infoshahin check the jQuery ajax documentation, your relative url here might be wrong.

@sushantaryal

This comment has been minimized.

Copy link

@sushantaryal sushantaryal commented Jul 23, 2015

This is great. Thanks

@JCarlosR

This comment has been minimized.

Copy link

@JCarlosR JCarlosR commented Aug 24, 2015

Thanks a lot.
I just have a few basic questions about how it works.

  1. Without ajax, using a regular pagination I use ->render() to show the links. In this case you are using ->links(), are both the same?
  2. On the success result... you use the "data" received and set it into the div with class "posts" using "html" method. How is it possible if you are using json format from the controller?
  3. Why you use render() over the View::make and again json to cover all?

I hope that someone can help me to clarify my doubts. Thanks again.

@velrino

This comment has been minimized.

Copy link

@velrino velrino commented Nov 9, 2015

Good!

Thanks :D

@mudasirsyed93

This comment has been minimized.

Copy link

@mudasirsyed93 mudasirsyed93 commented Dec 14, 2015

any one guide me i have an error how can i solve it ?
FatalErrorException in BlogController.php line 17:
Class 'App\Http\Controllers\Post' not found

@ikasuryani

This comment has been minimized.

Copy link

@ikasuryani ikasuryani commented Jan 2, 2016

@mudasirsyed93
try add a path to the Post class
like: 'use App\Post;'

@Rexeh

This comment has been minimized.

Copy link

@Rexeh Rexeh commented Feb 14, 2016

This works great, the only issue I'm having is that the currentPage doesn't go back to the front-end. So when using pagination controls to go to page 2, page 1 stays the active link.

Any solution?

@qaiserjaffri

This comment has been minimized.

Copy link

@qaiserjaffri qaiserjaffri commented Mar 17, 2016

This really great thanks :)

But i have an issue my request on next or page number click makes ajax request twice for same page number and results are same for both requests. Any One help Me please thanks in advance.

@dokicro

This comment has been minimized.

Copy link

@dokicro dokicro commented Mar 23, 2016

@Rexeh you should put {{ $posts->link }} to posts.blade.php to generate pagination again too...

@qaiserjaffri remove

$(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); } } });

@juljul98

This comment has been minimized.

Copy link

@juljul98 juljul98 commented Apr 18, 2016

when I clicked page 2 . the result will display when I clicked back to 1 it doesn't display the page 1

@umairbscs1

This comment has been minimized.

Copy link

@umairbscs1 umairbscs1 commented May 20, 2016

Thanx

@jaazee

This comment has been minimized.

Copy link

@jaazee jaazee commented May 20, 2016

anyone help me to write route for this ? i am using Laravel i am having problem when click on link it gave error

@JorenRapini

This comment has been minimized.

Copy link

@JorenRapini JorenRapini commented Jun 27, 2016

If you're getting an error after clicking a pagination link, it's possible you need to include View and Response in your controller at the top. That's what I forgot to put in initially.

use View;
use Response;

@JaviPedrera

This comment has been minimized.

Copy link

@JaviPedrera JaviPedrera commented Nov 2, 2016

Thanks, really useful.

@mohamedaimann

This comment has been minimized.

Copy link

@mohamedaimann mohamedaimann commented Nov 7, 2016

This is working in Laravel 5.3. Thank you very much. @mohamedaimann

@AndyHulme

This comment has been minimized.

Copy link

@AndyHulme AndyHulme commented Nov 24, 2016

Nice colours!

@robinbentley

This comment has been minimized.

Copy link

@robinbentley robinbentley commented Nov 24, 2016

g8 m8 i r8 8/8, no h8

@compworkmail

This comment has been minimized.

Copy link

@compworkmail compworkmail commented Feb 8, 2017

super! Thanks for this example!

@milanchheda

This comment has been minimized.

Copy link

@milanchheda milanchheda commented May 16, 2017

Excellent stuff.

@lgugliotta

This comment has been minimized.

Copy link

@lgugliotta 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

This comment has been minimized.

Copy link

@kc28 kc28 commented Oct 30, 2017

Thank You Very Much

@Tungquantedge

This comment has been minimized.

Copy link

@Tungquantedge Tungquantedge commented Nov 22, 2017

image
I have problems help me

@bezhanSalleh

This comment has been minimized.

Copy link

@bezhanSalleh bezhanSalleh commented Dec 9, 2017

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

@AhsanMalikGit

This comment has been minimized.

Copy link

@AhsanMalikGit AhsanMalikGit commented Dec 14, 2017

Thnkew very much Dear.

@manprajapat

This comment has been minimized.

Copy link

@manprajapat manprajapat commented Jul 27, 2018

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

@Hasnaakhalf

This comment has been minimized.

Copy link

@Hasnaakhalf Hasnaakhalf commented Sep 4, 2018

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

This comment has been minimized.

Copy link

@notridan notridan commented Oct 26, 2018

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

@sarabksidhu

This comment has been minimized.

Copy link

@sarabksidhu sarabksidhu commented Apr 6, 2020

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

This comment has been minimized.

Copy link

@ZawHtettnaing ZawHtettnaing commented May 26, 2020

Thank you very much dear.

@sodmond

This comment has been minimized.

Copy link

@sodmond sodmond commented Feb 4, 2021

Thanks for this, worked fine

@terremoth

This comment has been minimized.

Copy link

@terremoth 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

This comment has been minimized.

Copy link

@Mustafa535152 Mustafa535152 commented May 24, 2021

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

@princewillopah

This comment has been minimized.

Copy link

@princewillopah princewillopah commented Jul 10, 2021

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

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