TokenMismatchException in VerifyCsrfToken.php line 67 on laravel using ajax

扶醉桌前 提交于 2019-12-06 03:31:14

You should add csrf_field to your main blade :

{{ csrf_field() }}

Then add _token to your request :

var _token = $('input[name="_token"]').val();

function eliminar(id){
  $.ajax({
    type: "DELETE",
    url: "task/"+id,
    data: { _token : _token },
    success: function (data) {
      console.log(data);
    },
    error: function (data) {
      alert('Error:', data);
    }
  });
}

Or you could add it one time in ajaxSetup and it will affect all calls to $.ajax or Ajax-based derivatives such as $.get() :

$.ajaxSetup(
{
    headers:
    {
        'X-CSRF-Token': $('input[name="_token"]').val()
    }
});

Take a look to CSRF Protection.

Hope this helps.

jipino1

This is what worked for me. I found several answers online and none of them alone worked; however, after combining all, I got the Ajax call to go through.

  1. In the head of your view file, add the following line:

    <meta name="csrf-token" content="<?php echo csrf_token() ?>"> // This will retrieve the necessary token.
    
  2. Then, retrieve the value of the token and place it on a variable (optional step):

    var currentToken = $('meta[name="csrf-token"]').attr('content');
    
  3. On your ajax call, include the value of the token in the 'data:' field:

    $.ajax({type: 'POST', data: {_token:currentToken},....});
    

You may avoid the optional step of creating a new variable to it on the 'data:' field; however, I find this step easier to understand.

Hope this helps.

You need to add the token input field when passing the 'DELETE' method.

Html:

<input class="token" value="{{ csrf_field() }}"/>

Code:

function eliminar(id){
  var formData = '_token=' + $('.token').val();
  $.ajax({
           type: "DELETE",
           url: "task/"+id,
           data: formData,
           success: function (data) {
               console.log(data);
           },
           error: function (data) {
               alert('Error:', data);
           }
    });
}

You could also remove that route from the verification process by adding it to the except array in the Middleware.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!