Have you looked at the API? https://api.jquery.com/click/
A click event starts out like:
$("#myTable td:nth-child(1)").click(function(event)
{
/// your code
Here I am clicking a table cell, but a button would be similar.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
Well it looks like there are only 2 options. So if you want to toggle back and forth.
$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
},
success: function(){
// Change the button here
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('An unvisited button');
}
else{
// Do the opposite
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html('A visited button');
}
},
});
Please or to participate in this conversation.