Initially, I wrote all the JavaScript code right in my HTML page using the <script>
tag.
A post call in jQuery in the JavaScript was something like this.
$.post('store',{'_token':'{{csrf_token()}}'}, function(data){ /*a bunch of code*/ });
The code worked fine. But, later I put all my script into an external js file. And the code is not working anymore.
I have the problem with the {{csrf_token()}}
, the error being
TokenMismatchException in compiled.php
What should I do if I want to external js files with Laravel?
<meta>
tag with the token to the blade layout:<meta name="_token" content="{{ csrf_token() }}">
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
}
});
});
Now you can use $.post()
without providing _token
each time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With