Laravel csrf token mismatch for ajax POST Request



PHP Snippet 1:

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

PHP Snippet 2:

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

PHP Snippet 3:

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

PHP Snippet 4:

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

PHP Snippet 5:

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

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

PHP Snippet 6:

<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>

PHP Snippet 7:

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

PHP Snippet 8:

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

PHP Snippet 9:

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

PHP Snippet 10:

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

PHP Snippet 11:

var data = {
        "_token": $('#token').val()
    };

PHP Snippet 12:

@section('head')
<meta name="csrf_token" content="{{ csrf_token() }}" />
@endsection

PHP Snippet 13:

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

PHP Snippet 14:

$('#datatable_users').DataTable({
        "responsive": true,
        "serverSide": true,
        "processing": true,
        "paging": true,
        "searching": { "regex": true },
        "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
        "pageLength": 10,
        "ajax": {
            "type": "POST",
            "headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
            "url": "/getUsers",
            "dataType": "json",
            "contentType": 'application/json; charset=utf-8',
            "data": function (data) {
                console.log(data);
            },
            "complete": function(response) {
                console.log(response);
           }
        }
    });

PHP Snippet 15:

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

PHP Snippet 16:

$.ajax({
  url : "your_url",
  method:"post",
  data : {
    "_token": $('#csrf-token')[0].content  //pass the CSRF_TOKEN()
  },  
  ...
});

PHP Snippet 17:

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

PHP Snippet 18:

data : { 
    _token: @json(csrf_token()), 
}

PHP Snippet 19:

    var xsrfToken = decodeURIComponent(readCookie('XSRF-TOKEN'));
    if (xsrfToken) {
        $.ajaxSetup({
            headers: {
                'X-XSRF-TOKEN': xsrfToken
            }
        });
    } else console.error('....');

PHP Snippet 20:

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

PHP Snippet 21:

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
} 

PHP Snippet 22:

   function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
       }
        return null;
    }

PHP Snippet 23:

$.ajax({
url:url,
data:{
 _token:"{{ csrf_token() }}"
},
success:function(result){
 //success message after the controller is done..
}
})

PHP Snippet 24:

$( document ).on( 'ajaxSend', addLaravelCSRF );

function addLaravelCSRF( event, jqxhr, settings ) {
    jqxhr.setRequestHeader( 'X-XSRF-TOKEN', getCookie( 'XSRF-TOKEN' ) );
}

function getCookie(name) {
    function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };
    var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
    return match ? match[1] : null;
}

PHP Snippet 25:

cache:false,
processData:false,
contentType:false,

PHP Snippet 26:

dataType:"json",

PHP Snippet 27:

$(document).ajaxComplete(function(e, xhr, opt){
  if(xhr.status===419){
    if(xhr.responseJSON && xhr.responseJSON.message=='CSRF token mismatch.') window.location.reload();
  }
});

PHP Snippet 28:

"_token": "{{ csrf_token() }}"

PHP Snippet 29:

      const postFormData = {
            'name'     : $('input[name=name]').val(),
            "_token": "{{ csrf_token() }}"
        }; 
         
      $.ajax({
          url: 'pooling'
          , type: 'post'
          , data: postFormData
          , dataType: 'json'
          , success: function(response) { consolel.log(response) }
        });

PHP Snippet 30:

var request = $.ajax({
    url : "http://localhost/some/action",
    method:"post",
    data : {"_token":"{{ csrf_token() }}"}  //pass the CSRF_TOKEN()
  });

PHP Snippet 31:

var csrf = document.querySelector('meta[name="csrf-token"]').content;

PHP Snippet 32:

var csrf = document.querySelector('meta[name="csrf-token"]').content;
    $.ajax({
        url: 'my-own-url',
        type: "POST",
        data: { 'value': value, '_token': csrf },
        success: function (response) {
            console.log(response);
        }
    });

PHP Snippet 33:

$.ajax({
    url : "url where you want to send data"
    type : "POST", // http method
    data : {
      name:"...",
      csrfmiddlewaretoken: '{{ csrf_token }}' , #this works for me
    },

    // handle a successful response
    success : function(data){
      alert('......');
    },
    error : function() {
     ..............
    }

});

PHP Snippet 34:

protected $middlewareGroups = [
    'web'   => [],
    'api'   => [
        'web',
        'throttle:500,1'
    ],
    'basic' => [
        'auth:basic',
    ]
];

PHP Snippet 35:

<script>
    $(document).ready(function() {
        $("#my-upload-button").click(function() {

            var token = "{{ csrf_token() }}";//here getting token from blade

            $.post('my-url', {
                    _token: token,
                    datra: ...
                },
                function(data) {
                    alert(data); 
                });
        });         

PHP Snippet 36:

$.ajax({
                url: '{{ route('login') }}' ,
                method: 'POST',
                data: {
                    _token : {{ csrf_token() }},
                    data : other_data,
                },
                cache: false,
                //processData: false, // remove this

                ...

                success: function(res){
                   ...
                }
});

PHP Snippet 37:

<script>
    var token = "{{ csrf_token() }}";
</script>

<script src="/path/to/your_file.js"></script>

PHP Snippet 38:

$.ajax({
        type: "post",
        url: "http://your.url/end/point",
        data: {
                _token:token,
                data:your_data,
              },
        dataType: "json",
        success: function (response) {
            // code some stuff
        }
    });

PHP Snippet 39:

            $('#deleteMeal').click(function(event) {
                var theId = $(event.currentTarget).attr("data-mealId");
                  $(function() {
                    $( "#filler" ).dialog({
                      resizable: false,
                      height:140,
                      modal: true,
                      buttons: {
                      "Are you sure you want to delete this Meal? Doing so will also delete this meal from other users Saved Meals.": function() {
                           $('#deleteMealLink').click();
//                         jQuery.ajax({
//                              url : 'http://www.mealog.com/mealtrist/meals/delete/' + theId,
//                              type : 'POST',
//                              success : function( response ) {
//                                  $("#container").replaceWith("<h1 style='color:red'>Your Meal Has Been Deleted</h1>");
//                              }
//                          });
                        // similar behavior as clicking on a link
                           window.location.href = 'http://www.mealog.com/mealtrist/meals/delete/' + theId;
                          $( this ).dialog( "close" );
                        },
                        Cancel: function() {
                          $( this ).dialog( "close" );
                        }
                      }
                    });
                  });
                });

PHP Snippet 40:

  <p><a href="http://<?php echo $domain; ?>/mealtrist/meals/delete/{{ $meal->id }}" id="deleteMealLink" data-mealId="{{$meal->id}}" ></a></p>