In this Laravel Tutorial, I will let you know the solution of csrf_token mismatch issue while sending ajax "POST" request to server.
Whenever you send the request to server to modify anything into database then Laravel protect your application from cross-site request forgery (CSRF) attacks. This token is used to authenticate the user that you are actually active user on the web application and sending request from the application.
In Laravel, all request will handle by the Middleware that does not allow any POST request without the correct CSRF token so while sending ajax request, you must supplied the csrf token with request.
data: { "_token": "{!! csrf_token() !!}" }
Complete example with ajax call :
- $.ajax({
- type: "POST",
- data: {"_token": "{{ csrf_token() }}","id": id},
- url: some_url,
- success: function(msg){
- // do whatever you want with the response
- }
- });
If you have defined the javacript functionality in separate file then you can set token in meta element by following way :
- <meta name="csrf-token" content="{!! csrf_token() !!}">
Now you can access this csrf token in ajax call by following way :
- $.ajax({
- type: "POST",
- data: {"_token": $('meta[name="csrf-token"]').attr('content')},
- url: some_url,
- success: function(msg){
- // do whatever you want with the response
- }
- });