Laravel csrf token mismatch for ajax POST Request

November 21, 2016, at 6:17 PM

I am trying to delete data from database via ajax.


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

My ajax code:

$('body').on('click', '.delteadd', function (e) {
//alert('am i here');
if (confirm('Are you sure you want to Delete Ad ?')) {
    var id = $(this).attr('id');
        method: "POST",
        url: "{{url()}}/delteadd",
        }).done(function( msg ) {
        if(msg.error == 0){
} 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.
{{ Form::submit('Change', array('id' => 'ajax')) }}

ajax function:

 $(document).ready(function() {
    $(document).on('click', '#ajax', function () {
         headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},

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
each function jquery don&#39;t work

each function jquery don't work

hi I've this html code.

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

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

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