Currently, I am trying to implement voting system so users can like or dislike uploaded images, however, I'm trying to do it with an ajax call which makes it a bit confusing for me. I am not sure how to pass the id of the image the user is liking ( there are gonna be plenty of images on the page ) to the ajax call. In the JavaScript file, the data: imageId is currently empty since I don't know how exactly to determine and pass the id of the image.
Home view:
@extends('layouts.app')
@section('content')
@foreach($images as $image)
<div class='imageContainer'>
<div class="stickyContainer blackGradient">
<h1 class='imageTitle'>{{$image->name}}</h1>
<img class='uploadedImg' src='{{url("storage/uploads/images/".$image->file_name)}}' alt='Random image'/>
<a class='specialA' href='{{url("image/".$image->id)}}'></a>
<div class='votingContainer'>
<a href='#'><div class='like'></div></a>
<a href='#'><div class='dislike'></div></a>
</div>
</div>
</div>
@endforeach
<script>
var token = '{{ Session:token() }}';
var urlLike = '{{ route('like') }}';
</script>
@endsection
JavaScript File:
$('.like').on('click', function(event){
event.preventDefault();
var isLike = event.target.previousElementSibling == null;
console.log(isLike);
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike, imageId: , _token: token}
})
});
Assign image's id to the like button in the view:
<a href='#'><div class='like' id={{$image->id)}}></div></a>
Then, in javascript use image's id to the ajax call.
imageId= event.target.id;
On a side note: In javascript I don't understand why you are nulling the previousSibling with this:
var isLike = event.target.previousElementSibling == null;
Add Data attribute with attribute value as image Id to image element like data-imgId="1"
.It should be unique for each image element.
<img class='uploadedImg' src='{{url("storage/uploads/images/".$image->file_name)}}' data-imgId="{{$image->id)}}" alt='Random image'/>
Then get the image Id by using below script
var imgId = $(this).parents('.stickyContainer').find('.uploadedImg').attr('data-imgId');