Coder Perfect

For an ajax POST request, there is a csrf token mismatch in Laravel.

Problem

Ajax is used to access the m database.

HTML:

@foreach($a as $lis)
  //some code
  <a href="#" class="delteadd" id="{{$lis['id']}}">Delete</a>
  //click action perform on this link                  
@endforeach

My ajax code:

$('body').on('click', '.delteadd', function (e) {
e.preventDefault();
//alert('am i here');
if (confirm('Are you sure you want to Delete Ad ?')) {
    var id = $(this).attr('id');
    $.ajax({
        method: "POST",
        url: "{{url()}}/delteadd",
        }).done(function( msg ) {
        if(msg.error == 0){
            //$('.sucess-status-update').html(msg.message);
            alert(msg.message);
        }else{
            alert(msg.message);
            //$('.error-favourite-message').html(msg.message);
        }
    });
} else {
    return false;
}
});

This is the query I’m using to get data from the database…

$a = Test::with('hitsCount')->where('userid', $id)->get()->toArray();

However, when I click Delete link, the data is not removed, and a csrf token mismatch appears…

Asked by Ashish Singh

Solution #1

The best method to overcome the “X-CSRF-TOKEN” problem is to add the following code to your main layout and keep making ajax calls as usual:

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>

Answered by zarpio

Solution #2

In your ajax request, you must include data. I’m hoping it will work out.

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

Answered by Deepak saini

Solution #3

I just added headers: 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');

Answered by lewis4u

Solution #4

I believe it is preferable to place the token in the form and retrieve it by id.

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

And then there’s the JQUery:

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

This eliminates the need for your JS to be in your blade files.

Answered by cmnardi

Solution #5

If you’re working with template files, you may add your meta tags in the head section (or whatever you want to call it).

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

The headers attribute must then be added to your ajax (in my example, I’m using a datatable with server-side processing:

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

The complete datatable ajax sample may be seen here:

$('#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);
           }
        }
    });

After doing this, you should get 200 status for your ajax request.

Answered by Brane

Post is based on https://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request