Ajax (POST) Laravel

Asked

Viewed 3,569 times

0

I am having the famous error 419, that for a certain moment I was able to solve, but after restarting the server, it stopped working.

Route:

Route::post('ajax/Register', 'Ajax@Register');

Controller:

public static function Register()
{
    $input = request()->all();

    return $input;
}

META TAG:

<meta name="_token" content="{{ csrf_token() }}">

JS:

var _token = $('meta[name="_token"]').attr('content');

$.ajaxSetup({

    headers: {

        'X-CSRF-TOKEN': _token

    }

});

$('#formRegister').submit(function() {
    $.ajax({
        url: 'ajax/Register',
        type: 'POST',
        data: {
            'user': 'oi'
        },
        dataType: 'JSON',

        success: function(data){
            console.log(data);
        }
    });
    return false;
});

Network:

Status Code: 419 unknown status
Request Headers > X-CSRF-TOKEN: oAiZm9n8xByExejoRVT3Yv2WKxkmoN1uZHkzHuAR

That is, ajax actually sends the token, but I am not successful in POST operation.

  • If you register the route in the Middleware VerifyCsrfToken (inside the array $except), it will no longer present the error for this route.

  • Could you elaborate better on the answer by asking why you believe these modifications will solve the problem? This will help other people better understand their reasoning :)

1 answer

0

Solving your problem of falling into error 419... First change your route to:

Route::post('ajaxRegister', ['as' => 'ajax.register', 'uses' => 'Ajax@Register']);

Soon after update in ajax to:

...
$.ajax({
    url:"{{ route('ajax.register') }}",
    data: {
        'user': 'oi'
    },   
...

At first your Controller is correct, a hint I can give is about the method of Controller is the following:

public function Register(Request $request)
{
    $dados = $request->all(); // ou
    $dados = $request->except('_token');
         ......
}

Your question is similar to another recent one here on the forum, from a look here:

Complete form without giving Reload on page

Browser other questions tagged

You are not signed in. Login or sign up in order to post.