简体   繁体   中英

Ajax Post to Laravel - CSRF Token Mismatch

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM