Ajax (POST) Laravel

-1

I am having the famous error 419, which for a certain moment I managed 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;
}

TARGET 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'm not successful in the POST operation.

    
asked by anonymous 02.10.2018 / 22:56

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 updating in ajax to:

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

At first your Controller is correct, a tip I can give is about the Controller method is as follows:

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

Your question is similar to a recent one here in the forum, at a glance   here:

     

Complete form without giving reload to page

    
22.10.2018 / 19:00