ID received from post - send via ajax

454 Views Asked by At

I would like to read the post id from html and send it via AJAX to the controller. How can I get the post ID ($post->id) and transfer it via AJAX? Or is there a better solution to save the post seen by the user?

@foreach ($posts as $post)
    <div id="post_container_{{$post->id}}" class="row waypoint">
    </div>
@endforeach

This is my AJAX code:

$('.waypoint').waypoint(function() {
        $.ajax({
            url: '/posts/view',
            type: "post",
            data:
            success: function(request){
                console.log(request);
            },
            error: function(response){
                console.log(response);
            },
            headers:{
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    }, {
        offset: '100%'
});
2

There are 2 best solutions below

3
On BEST ANSWER

Get the id from the focused waypoint.

let waypoint_id = this.getAttribute('id'); // something like 'post_container_1'

Get only the string after the _

let post_id = waypoint_id.split("_").pop(); // something like '1'

in ajax() function

data: {
    post_id: post_id
}
1
On

You could add a data-id attribute like so:

@foreach ($posts as $post)
    <div id="post_container_{{$post->id}}" data-id="{{$post->id}}" class="row waypoint">
    </div>
@endforeach

And then access it using the attr()

$('.waypoint').waypoint(function() {
    let post_id = $(this).attr('data-id');   //this specifies the particular post row in focus.
    $.ajax({
        url: '/posts/view',
        type: "post",
        data: {post_id: post_id}
        //and so on. 
    });
}, {
offset: '100%'
});