Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  200] [ 7]  / answers: 1 / hits: 27813  / 9 Years ago, sat, june 6, 2015, 12:00:00

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?


More From » php

 Answers
12

  1. add <meta> tag with the token to the blade layout:



<meta name=_token content={{ csrf_token() }}>



  1. setup ajax requests:



$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
});
});


Now you can use $.post() without providing _token each time.


[#66301] Thursday, June 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
faithemilys

Total Points: 418
Total Questions: 100
Total Answers: 114

Location: North Korea
Member since Fri, Nov 4, 2022
2 Years ago
faithemilys questions
Wed, Mar 31, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Tue, Sep 22, 20, 00:00, 4 Years ago
Sun, Feb 9, 20, 00:00, 4 Years ago
Fri, Dec 6, 19, 00:00, 5 Years ago
;