5

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

senty
  • 12,385
  • 28
  • 130
  • 260

2 Answers2

9

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");
    }
  });
Nour
  • 1,458
  • 1
  • 18
  • 27
  • 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 :/ – senty Sep 16 '16 at 20:21
  • Why don't you try to exclude this route from your Middleware ? – Nour Sep 16 '16 at 20:27
  • Try to add this to your ajax request beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); }, – Nour Sep 16 '16 at 20:35
  • Can you add it in answer part above please? I didn't get how to implement it here – senty Sep 16 '16 at 20:39
  • I am sorry I've modified it please take a look – Nour Sep 16 '16 at 20:43
  • Still getting the Token Mismatch Error :/ – senty Sep 16 '16 at 20:45
  • Please check the last update I've tried it right now and I believe the problem is because we should connect the url with _token – Nour Sep 16 '16 at 21:22
4

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 );
    }
    });