Laravel csrf token mismatch for ajax POST Request

652
November 21, 2016, at 6:17 PM

I am trying to delete data from database via ajax.

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 my query to fetch data from database...

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

But when i click on Delete link data not deleted and show csrf_token mismatch...

Answer 1

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

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

I think is better put the token in the form, and get this token by id

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

And the JQUery :

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

this way, your JS don't need to be in your blade files.

Answer 3

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');
Rent Charter Buses Company
READ ALSO
each function jquery don&#39;t work

each function jquery don't work

hi I've this html code.

398
JQuery - Loop through each case of a class from a point

JQuery - Loop through each case of a class from a point

I am creating a self scrolling, auto updating table and need to search through through elements of a class from a certain point. [nnn]My code currently is this:.

307
Get text from outer span without text of inner elements

Get text from outer span without text of inner elements

I want to extract some text from an HTML element in Selenium and Javascript. .

410
Combobox on ajax returned fields

Combobox on ajax returned fields

Alright, I'm developing a system in which you add rows to a table, then enter data into it and save it. [nnn]I'm using ajax to return the complete table (which has the input tags).

543