I am new to the Laravel framework, and I am trying to use AJAX for my first time.
I am trying to do a program that has multiple icons, according to the DB number of entries, that when you click on one of them changes it visually, without reloading the page, as well as send its id into a controller, to change a value of the DB.
Here is where I print the icons:
@foreach ($checklists as $checklist)
<div class="project-title text-dark mt-1 py-1 px-2 d-flex task">
<div class="col-md-10">
<b>{{ $checklist->title }}</b>
</div>
<div class="col-md-2 d-flex justify-content-end">
<i class="fas fa-check-square check-button"></i>
<p class="check-button-id" style="display: none;">{{ $checklist->id }}</p>
</div>
</div>
@endforeach
The $checklists
variable is the one that I am using to store the data that I am fetching from the database to my controller, and then to my view.
Here is my jQuery:
$(document).ready(function () {
$('.check-button').click(function (e) {
e.preventDefault();
let classesArray = $(this).attr("class").split(" "); // Here I am getting the element's classes and splitting them into an array
let relevantClasses = classesArray[0].concat(" ", classesArray[1]); // Here I am selecting only the classes that I need to turn the i tag into the icon that I want
let checkButtonId = $('.check-button-id').text(); // Here I am storing the id that I need to use to find a specific entry in my DB (in the HTML I used a hidden paragraph to display the value)
$.ajax({
type: "POST",
url: "/checklists/" + checkButtonId, // putting the id in the url to retrieve it in the controller
data: {relevantClasses: relevantClasses},
dataType: "json",
success: function (response) {
if(response.success) {
$(this).removeClass(relevantClasses); // remove the classes that define the icon that I had
switch(response.checked) {
case true:
$(this).addClass("fas fa-check-square"); // change it to the classes to the icon that I want, based on the checked variable that I return from my controller
break;
case false:
$(this).addClass("far fa-square");
break;
}
}
}
});
});
});
Here is the part of my Controller that handles the AJAX request
public function checklistHandler (Request $req, $checkButtonId) {
$checklist = Checklist::find($checkButtonId);
if($req->relevantClasses === 'far fa-square')
$checklist->checked = true;
else if($req->relevantClasses === 'fas fa-check-square')
$checklist->checked = false;
$checklist->save();
return response()->json(['success' => true, 'checked' => $checklist->checked]);
}
This code does not work :( Can anybody please tell me how to fix it?