dimanche 28 février 2021

Laravel 5.4 token mismatch caused by a select field

I am working on an old Laravel project (5.4) and i am not a stranger to Laravel's TokenMismatchException. However, this case is weird and I tried several of the fixes I can do. A certain select field in one view is causing Laravel to throw this exception. This field is dynamically filled using Ajax based on the previous select input. The same combination of fields works perfectly when i am editing but doesn't work when I'm storing. Below is my code from the view:

<form action="" method="post" enctype="multipart/form-data" >
        
    <div class="row">
        <div class="col-12">
            
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <label for="employee_id">Employee</label><span class="required_field"></span>
            <select name="employee_id" id="employee_id" class="form-control">
                <option value="">----</option>
                @foreach($employees as $employee)
                    <option value=""></option>
                @endforeach
            </select>
            <br/>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <label for="period_id"></label>
            <select id="period_id" name="periods_id" class="form-control"></select>
        </div>
    </div>
...

And here is the Ajax function to fill out the period field:

 $('#employee_id').on('change', function () {
            let id = $(this).val();

            if(id == null){
                return;
            }

            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: '/performance/employee-period/'+ id,
                type: 'GET',
                success: function (data) {
                    let select = $('#period_id');
                    select.html(null);
                    select.append(new Option('---', ''));
                    $.each(data, function (key, value) {
                        let option = new Option(value.period.start_date + ' - ' + value.period.end_date, value.period.id);
                        select.append(option);
                    })
                },
            });
        });

The route of the store is protected by the same middleware i use for all the other routes and they are not causing any issues. I have a meta containing the csrf token in the layout i am extending. If I submit without choosing the period, the request passes directly. It is probably something silly but i have wasted around 2 hrs trying to solve it without avail so any help is appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire