I have created a system where you can visit a place and have all the code that allows for an entry to be posted to the database and deleted from the database on button click with ajax but i am struggling to work out how to make the button change with ajax when its clicked depending on whether the record exists or not. At the moment the button only changes if the page is refreshed albeit the AJAX code works for adding or deleting from the database. How would i get my buttons to change and respond to the if statement with AJAX? here is what i have so far:
Html:
@if(Auth::user()->visitors()->where('place_id', $place->id)->first())
<a class="btn btn-visited visit" data-id="{{ $place->id }}">I've Visited <i class="fas fa-check"></i></a>
@else
<a class="btn btn-not-visited visit" data-id="{{ $place->id }}">Visited?</a>
@endif
AJAX JS:
var token = '{{ Session::token() }}';
var urlVisit = '{{ route('visitss') }}';
$('.visit').on('click', function (event) {
event.preventDefault();
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
}
}).done(function() {
//
});
});
php:
$place_id = $request['place_id'];
$place = place::find($place_id);
$visited = Auth::user()->visitors()->where('place_id', $place_id)->first();
if($visited == null) {
$visited = new Visit();
$visited->user_id = Auth::user();
$visited->place_id = $place->id;
$visited->save();
return null;
}
else{
$visited->delete();
return null;
}
How do i get the buttons to respond with AJAX?