0

I'm using Laravel 7.2.0, trying to send an ajax request but I have a problem.

I'm trying to pass the csrf token from the meta but it give me 419 error.

It only works if I add @csrf on the form as below, but the controller dont get an ajax request.

The form:

<form id="formto" method="POST" action="{{ route('selectedtodolist') }}">
    @csrf
    <p>{{$Todo->name}}</p>
    <br>
    <input id="id_todolist" name="id_todolist" value="{{$Todo->id}}" type="hidden">
    <input type="submit">
</form>

Head:

@push('head')
<!-- Scripts ajax -->
<script src=" {{ asset('js/components/Selectedtodolist.js') }} "></script>
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

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

Jquery ajax:

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

$(() => {


            $("#formto").submit((e) => {
                        let that = e.currentTarget;
                        e.preventDefault();

                        $.ajax({
                                type: $(this).attr('method'),
                                url: $(this).attr('action'),
                                data: $(this).serialize(),
                                dataType: 'json',
                                cache: false,
                                success: function() {
                                    alert("work");
                                }
                            })
                            .done((data) => {
                                console.log(data);
                            })

And the controller: (give me 404 error cause of this 'if'):

public function __invoke(Request $request)
{
    if ($request->ajax()) {

        $this->validate($request, [
           'id_todolist' => 'bail|required|email'
        ]);

        return response()->json ();
    }
    abort(404);
}

route: Route::post('selectedtodolist', 'SelectedlistController')->name('selectedtodolist');

Thank you in advance

JSON C11
  • 11,272
  • 7
  • 78
  • 65
sharkmax
  • 1
  • 1
  • Try two things: **1.** move ajaxSetup code block into invoked function before submit form block; **2.** use regular JS function instead arrow function because of `this` scope difference. – Tpojka Mar 28 '20 at 20:31
  • What have you tried to spot the root cause of that error? And why do you send an error 404 (which means: page not found) when a validation fails instead of a proper error code for that situation? – Nico Haase Apr 07 '20 at 20:59

0 Answers0