neflictus's avatar

Ajax issue

Hello

I have 2 tables: Children and Media (Spatie MediaLibrary) When I edit the child, there are 2 tabs displayed: one with the child's information, the other - a list of pictures associated with the child.

I would like to paginate those pictures, as users might tend to upload too many photos. I would like to use Ajax, and use another method to display the records.

public function edit(Child $child, Request $request)
{
    $edit = true;
    $images = Child::find($child->id)->media('images')->paginate(1);
    return view('child.add-edit', compact('edit', 'child', 'images'));
}



public function photos(Child $child, Request $request) {
        $images =  Child::find($child->id)->media('images')->paginate(1);
        return view('child._photos', ['images' => $images, 'child' => $child])->render();
}

Main children view:

<div class="pictures">
    @include('child._photos')
</div>


<script type="text/javascript">

    $(function() {
        $('body').on('click', '.pagination a', function(e) {
            e.preventDefault();

            //var url = $(this).attr('href');
            var url = '{{route('child.photos',$child)}}';
            getPhotos(url);
        });

        function getPhotos(url) {
            $.ajax({
                url : url
            }).done(function (data) {
                $('.pictures').html(data);
            }).fail(function () {
                alert('Some sort of error.');
            });
        }
    });

</script>

_photos.blade.php

@if (count($images)>0)
    @foreach ($images as $media)
        <div class="col-md-2">
            {{$media->name}}
        </div>
@endforeach
{!! $images->links() !!}
@endif 

It always gets the first photos, never displaying the 2nd page. If I use the edit method to display the recods (var url = $(this).attr('href');), it works like a charm.

I'm missing something.

0 likes
3 replies
BezhanSalleh's avatar
return view('child._photos', compact('images', 'child'));
Snapey's avatar

you are not doing anything to get the url from the pagination link. How do you know which page is requested?

neflictus's avatar

Solved it. Thanks

var page=$(this).attr('href').split('page=')[1];
var url = '{{route('child.photos',$child)}}' + '?page=' + page;

Please or to participate in this conversation.