In this tutorial, i will tell you the use of ajax for Laravel Pagination.
Ajax makes your application more flexible, you don't need to reload or refresh the whole body for small changes, you can made changes in any part without loading page.
Step1: Add Route
- Route::get('laravel-ajax-pagination',array('as'=>'ajax-pagination','uses'=>'FileController@productList'));
In this step, i am creating a function for product listing and check if there will be ajax request then pass data without templates.
- public function productList(Request $request){
- $products = Product::paginate(5);
- if ($request->ajax()) {
- return view('presult', compact('products'));
- }
- return view('productlist',compact('products'));
- }
- <?php
- namespace App;
- use Illuminate\Database\Eloquent\Model;
- class Product extends Model
- {
- public $fillable = ['name','details'];
- }
- <div class="row">
- <div class="col-lg-12 margin-tb">
- <div class="pull-left">
- <h2>Laravel AJAX Pagination with JQuery</h2>
- </div>
- </div>
- </div>
- <div id="product_container">
- @include('presult')
- </div>
- <script>
- $(window).on('hashchange', function() {
- if (window.location.hash) {
- var page = window.location.hash.replace('#', '');
- if (page == Number.NaN || page <= 0) {
- return false;
- }else{
- getData(page);
- }
- }
- });
- $(document).ready(function()
- {
- $(document).on('click', '.pagination a',function(event)
- {
- $('li').removeClass('active');
- $(this).parent('li').addClass('active');
- event.preventDefault();
- var myurl = $(this).attr('href');
- var page=$(this).attr('href').split('page=')[1];
- getData(page);
- });
- });
- function getData(page){
- $.ajax(
- {
- url: '?page=' + page,
- type: "get",
- datatype: "html",
- // beforeSend: function()
- // {
- // you can show your loader
- // }
- })
- .done(function(data)
- {
- console.log(data);
- $("#product_container").empty().html(data);
- location.hash = page;
- })
- .fail(function(jqXHR, ajaxOptions, thrownError)
- {
- alert('No response from server');
- });
- }
- </script>
- <table class="table table-bordered">
- <tr>
- <th>Name</th>
- <th>Details</th>
- </tr>
- @foreach ($products as $product)
- <tr>
- <td>{{ $product->name }}</td>
- <td>{{ $product->details }}</td>
- </tr>
- @endforeach
- </table>
- {!! $products->render() !!}
Laravel has make very simple way to render pagination in application.
When i am working with this code then i noticed that url is same because i don't need to refresh or reload page while working with ajax so its very difficult to understand on which page i am that's why i used hashes in url and update page number on click.