Ajax Post to Laravel - CSRF Token Mismatch
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 ); } });
Comments
-
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 over 7 yearsI 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 over 7 yearsWhy don't you try to exclude this route from your Middleware ?
-
Nour over 7 yearsTry to add this to your ajax request beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); },
-
senty over 7 yearsCan you add it in answer part above please? I didn't get how to implement it here
-
Nour over 7 yearsI am sorry I've modified it please take a look
-
senty over 7 yearsStill getting the Token Mismatch Error :/
-
Nour over 7 yearsPlease check the last update I've tried it right now and I believe the problem is because we should connect the url with _token