Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include csrf_token() in an external js file in Laravel?

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?

like image 223
Faizuddin Mohammed Avatar asked Jun 06 '15 18:06

Faizuddin Mohammed


1 Answers

  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.

like image 115
Limon Monte Avatar answered Oct 05 '22 06:10

Limon Monte