0

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?

NickOlder
  • 37
  • 1
  • 3
  • "_This code does not work_" What does that mean? Wrong icon loaded? Wrong classes sent? Blank page? Have you made sure that `checkButtonId` contains what it should? There will be multiple `$('.check-button-id')` on the page. Better to use a `data`-attribute on every `` that contains the `$checklist->id` – brombeer Feb 18 '22 at 11:20
  • @brombeer Nothing happens. In the console the state appears as "419 unknown status". The `checkButtonId` does not contain what it should. I had only tried with one `$('.check-button-id')`. But nothing happens at the DB and to the icon class regardless. – NickOlder Feb 18 '22 at 11:29
  • @brombeer is it required? The pop-ups that I am using do not work when I use csrf – NickOlder Feb 18 '22 at 11:34

2 Answers2

0

Based on your comments, error 419 mean that the csrf token is invalid.

Since you're using AJAX, you can try the solution posted here https://stackoverflow.com/a/41867849/5649969

To summarize, you need to put

<meta name="csrf-token" content="{{ csrf_token() }}"/>

into your blade, then on the js part of the page, you add in

$.ajaxSetup({
    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
})

before you make the AJAX call itself.

Tom
  • 25
  • 7
-1

did you check any errors are coming in console , or did you put debugger and debugged it line by line , you can do it from any browser like chrome inspect element , console for watching error etc and for debugging sources then openfile and find your code and put debugger by mouse over on line and on click on it, then press f10 for line by line debugging and press f8 for jump to next break point,by this way you can easily identify ,why button click is not working

  • I get the error 'Failed to load resource: the server responded with a status of 419 (unknown status)' on chrome – NickOlder Feb 18 '22 at 11:33