Ajax Post to Laravel - CSRF Token Mismatch
Asked Answered
P

3

6

I am trying to post data to Laravel backend with ajax, however I am getting 'CSRF token mismatch' error.

First, I've placed token in html (in body but outside its form because it's not the whole form, its only 2 elements to be posted):

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

Then in 'document ready', I try to post the data with ajax.

data["_token"] = jQuery('#token').val();  

// Also tried this:
jQuery.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': jQuery('#token').val()
       }
})

console.log(data) // returns the array with _token: "esOKmY8Tpr4UvhTYMhWcWui0rpvYEjJ3es7ggics"

jQuery.ajax({
     type: "POST",
     url: '/my-route',
     data: data,
     success: function() {
          console.log("A");
     }
});

The data which I want to post are little chunk of a bigger form, and with using this approach, I can autocomplete form. The little chunk of html inputs are not inside any other sub-form. Maybe this can be the case?

- Form:
- A: bla // to be posted
- B: hello  // to be posted
- C: smt else // no post

but getting the values are working okay

Route:

Route::post('/my-route', 'AdminController@theFunction')->middleware('admin');


Edit: I changed <input> to <meta> tag

Pulmonary answered 16/9, 2016 at 20:9 Comment(5)
can you show us your route?Franni
The issue looks like Origin Policy is wrong. Laravel CSRF should work out of the box without any tricks, under the normal circumstances.Ingot
Is the admin middleware doing a redirection?Woodman
I eventually cancelled the csrf for admin page.Pulmonary
Check this : #53685428Ask
I
12

I had the same problem try to put include CSRF tag in your meta like so

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

and read it in your ajax code like so :

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

Last Update

Please modify your url variable like so :

jQuery.ajax({
    type: "POST",
    url: '/my-route'+'?_token=' + '{{ csrf_token() }}',
    data: data,
    success: function() {
         console.log("A");
    }
  });
Inconformity answered 16/9, 2016 at 20:16 Comment(7)
I tried exactly what you said. It's csrf token mismatch error again. I logged $('meta[name="csrf-token"]').attr('content') and it successfully logs the token but Token Mismatch Error persists. Unfortunately, this is not the answer :/Pulmonary
Why don't you try to exclude this route from your Middleware ?Inconformity
Try to add this to your ajax request beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); },Inconformity
Can you add it in answer part above please? I didn't get how to implement it herePulmonary
I am sorry I've modified it please take a lookInconformity
Still getting the Token Mismatch Error :/Pulmonary
Please check the last update I've tried it right now and I believe the problem is because we should connect the url with _tokenInconformity
R
5

Try This


    var formData = new FormData();
    formData.append("_token", "{{ csrf_token() }}");
    $.ajax({
    headers: {
    'X-CSRF-TOKEN': "{{ csrf_token() }}"
    },
    url: 'save_search',
    data: formData,
    processData: false,
    type: 'POST',
    success: function ( data ) {
    alert( data );
    }
    });

Renewal answered 4/6, 2018 at 10:2 Comment(0)
O
0

I encountered an issue with my Laravel 8 where I noticed that the token was being sent in the URL through my AJAX request and the URL was correct.

However, despite this, I was still receiving an error. Upon further investigation, I realized that I had changed the value of 'same_site' in my session.php file to none.

After changing it back to 'same_site' => "lax", I was able to resolve the issue.

Overtime answered 12/2 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.