ajax pagination in laravel

0

How could I make an adaptation of my code to make paging work without updating the page with ajax?

My functional paging code looks like this:

route set

Route::get('/home',   'HomeController@main');

HomeController.php

public function main()
{
   //Pega os ultimos usuarios atualiza para criar a paginação
    $users = DB::table('cache_users')->orderBy('timestampOld')->paginate(30);
    return \View::make('Home')->with('users', $users)
}

home.blade.php

@foreach($users as $U)
   <b>$U->name</b>
@endforeach
   {{ $users->links() }}

How would I adapt this code for ajax pagination?

    
asked by anonymous 01.12.2017 / 11:09

1 answer

0

A practical example that I found some time ago and saved because I knew it could be useful, sorry for not passing the code already with its variables, I answered here in the rush :( but I believe you will not have problems implementing it.

home.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Paginação AJAX</title>
</head>
<body>
    <h1>Usuários</h1>
    <div class="users">
        @include('users')
    </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 {
                getUsers(page);
            }
        }
    });
    $(document).ready(function() {
        $(document).on('click', '.pagination a', function (e) {
            getUsers($(this).attr('href').split('page=')[1]);
            e.preventDefault();
        });
    });
    function getUsers(page) {
        $.ajax({
            url : '?page=' + page,
            dataType: 'json',
        }).done(function (data) {
            $('.users').html(data);
            location.hash = page;
        }).fail(function () {
            alert('Falha ao carregar usuarios.');
        });
    }
    </script>
</body>
</html>

HomeController.php

<?php
classHomeController extends Controller
{
    public function main()
    {
        $users = DB::table('cache_users')->orderBy('timestampOld')->paginate(30);
        if (Request::ajax()) {
            return Response::json(View::make('users', array('users' => $users))->render());
        }
        return View::make('home', array('users' => $users));
    }
}

users.blade.php

@foreach ($users as $user)

    <article>
        <h2>{{ $user->nome}}</h2>
        {{ $user->telefone }}
    </article>

@endforeach

{{ $users->links() }}
  

Useful link

     

How to Create an Ajax Pagination Using Laravel

    
01.12.2017 / 12:03