Ajax Post to Laravel - CSRF Token Mismatch

18,289

Solution 1

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

Solution 2

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

Share:
18,289
senty
Author by

senty

Harder, Better, Faster, Stronger...

Updated on June 12, 2022

Comments

  • senty
    senty almost 2 years

    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
    senty over 7 years
    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 :/
  • Nour
    Nour over 7 years
    Why don't you try to exclude this route from your Middleware ?
  • Nour
    Nour over 7 years
    Try to add this to your ajax request beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); },
  • senty
    senty over 7 years
    Can you add it in answer part above please? I didn't get how to implement it here
  • Nour
    Nour over 7 years
    I am sorry I've modified it please take a look
  • senty
    senty over 7 years
    Still getting the Token Mismatch Error :/
  • Nour
    Nour over 7 years
    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