Laravel csrf token mismatch for ajax POST Request

You have to add data in your ajax request. I hope so it will be work.

data: {
        "_token": "{{ csrf_token() }}",
        "id": id
        }

I just added headers: in ajax call:

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

in view:

<div id = 'msg'>
     This message will be replaced using Ajax. Click the button to replace the message.
</div>

{!! Form::submit('Change', array('id' => 'ajax')) !!}

ajax function:

<script>
 $(document).ready(function() {
    $(document).on('click', '#ajax', function () {
      $.ajax({
         type:'POST',
         url:'/ajax',
         headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
         success:function(data){
            $("#msg").html(data.msg);
         }
      });
    });
});
</script>

in controller:

public function call(){
    $msg = "This is a simple message.";
    return response()->json(array('msg'=> $msg), 200);
}

in routes.php

Route::post('ajax', 'AjaxController@call');

Laravel 8^

Route::post('ajax', [AjaxController::class, 'call']);

The best way to solve this problem "X-CSRF-TOKEN" is to add the following code to your main layout, and continue making your ajax calls normally:

In header

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

In script

<script type="text/javascript">
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
</script>