简体   繁体   中英

Laravel 5.5 : 419 unknown status with AJAX

I am requesting POST :

Route :

Route::post('/register','CommonController@postRegister')->name('register');

CSRF Meta tag :

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

$("#submitSalonForm").click(function(e) {
  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });
  $.ajax({
      url: "/register",
      type: "post",
      data: new FormData($('form')[1]),
      cache: false,
      contentType: false,
      processData: false,
      success:function(response) {
          return alert('Form 2 submitted');
      }
  });
});

And the exception :

异常截图

The exception comes sometimes and sometimes the code runs smoothly, I have no idea what am i missing here.

Change ajax method from post to get

<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">

Ajx call:

let formData = $('form').serializeArray();
$.ajax({
      url: "/register",
      type: "POST",
      data: {formData, "_token": $('#token').val()},
      cache: false,
      datatype: 'JSON',
      processData: false,
      success: function (response) {
           console.log(response);
         },
         error: function (response) {
           console.log(response);
         }
  });

Your route is get

Route::get('/register','CommonController@showRegister')->name('register');

Ajax call is making a post request, laravel sqwaks with a http exception.

EDIT: Laravel 419 post error is usually related with api.php and token authorization

So try to include the token on ajax body instead like above.


In addition to putting the crsf-token value in the header meta tag you need to pass it through in your AJAX requests like:

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

No need to setup ajax separately. Laravel automatically generates a CSRF "token" for each active user session managed by the application. Get the token with this:

var token = "{{ csrf_token() }}";

Pass the token in data

var token = "{{ csrf_token() }}";
var formData = new FormData($('form')[1])
$.ajax({
    url : '/register',
    data : {_token:token,formData:formData},
    type: 'post',
    ...
})

Well, I know I am too late, but I did face the exact issue you face.

I was 100% sure that the token has been sent with the request, but the issue is still.

So, after too many searches I finally got it fixed by following these steps:

php artisan config:clear          
php artisan view:clear
php artisan route:clear
php artisan cache:clear
php artisan clear-compiled

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM