skip to Main Content

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?

2

Answers


  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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search