Shivam Singh
Shivam Singh

Reputation: 11

CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException

function edit_expense(val){
    var id = val;
    var amount = $('#expense_amount_'+id).val();
    var image = $('#img_file_'+id)[0].files[0];
        
    $.ajax
   ({
    type:'post',
    url:'{{route('edit_expense')}}',
   
    headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
    processData: false,
    contentType: false, 
    data: { "_token": "{{ csrf_token() }}",'id':id, 'amount': amount,'image': image },        
    success:function(data)          
    {          
        $('.revnue_updated').removeClass('d-none');
        $(".revnue_updated").fadeOut(3000);
    }
   });
};

Here it is my code , I am getting csrf token mismatch after adding header also. I want to send image value in data but is showing csrf mismatch

Upvotes: 0

Views: 1669

Answers (2)

Atta Rehman
Atta Rehman

Reputation: 1

Use "Formdata()", below is the working code. I hope it helps.

function edit_expense(val){
  
  var form_data = new FormData();
  var id = val;
  
  var amount = $('#expense_amount_'+id).val();
  form_data.append('id', id);
  form_data.append('amount',amount);
  form_data.append('_token', '{{csrf_token()}}');
  form_data.append('image',$('#img_file_'+id)[0].files);
    $.ajax
   ({
    type:'post',
    url:'{{route('edit_expense')}}',
    mimeType: "multipart/form-data",
    async:true,
    dataType: 'json',
    cache: false,
    processData: false,
    contentType: false, 
    data: form_data,        
    success:function(data)          
    {          
      $('.revnue_updated').removeClass('d-none');
        $(".revnue_updated").fadeOut(3000);
    }
   });
};

Upvotes: 0

Emil Abbasov
Emil Abbasov

Reputation: 11

You have multiple solutions for this problem.

  1. You can add your route to VerifyCsrfToken middleware (Open app/middleware/verifycsrftoken.php and append your route url to $except array
  2. You can add meta tag to your layout blade meta name is "csrf-token" and content is {{ csrf_token() }} and add this code to your ajax request headers: {'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')}

In other hands you can add _token key to your ajax data and use {{csrf_token()}}

Upvotes: 1

Related Questions