0

First, sorry for the bad english and bad explanation, i already write ajaxsetup in script

 $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

and also the meta tag in the head

meta name="csrf-token" content="{{ csrf_token() }}"

but why the mdata below need _token that contain token to make it run

var token = $('meta[name="csrf-token"]').attr('content');
var mData={ 
  'email' :$('input[name=email]').val(),
  'password' :$('input[name=password]').val(),
  'remember_me' :$('input[name=remember_me]').is(':checked'),
  _token : token    // WHY DO I NEEED THIS
};

$.ajax({
type: "POST",
url :"/login",
data:mData,
Louis Sant
  • 11
  • 4
  • 2
    Does this answer your question? [What is a CSRF token ? What is its importance and how does it work?](https://stackoverflow.com/questions/5207160/what-is-a-csrf-token-what-is-its-importance-and-how-does-it-work) – STA Sep 29 '20 at 06:06
  • If you're asking what a CSRF token is for, then this is a duplicate. If you're asking why you need to include it both in the headers and in the data, that's a trick question because you don't need to include it in both – apokryfos Sep 29 '20 at 06:32
  • @sta so i need to write _token when i useajax? how to make it global? so i dont need to call it evey time in the data – Louis Sant Sep 29 '20 at 06:33
  • @apokryfos so what should i do to just call it in the headers ? because it doesnt work if i dont call it in the data – Louis Sant Sep 29 '20 at 06:35
  • Normally it *should* work (assuming you're using the normal built-in `VerifyCsrfToken` middleware). Personally I recommend not using `ajaxSetup` though and passing it explicitly in each request. – apokryfos Sep 29 '20 at 06:37
  • @apokryfos so, what's the other way ? – Louis Sant Sep 29 '20 at 06:41
  • passing `_token : token` is the way I recommend doing this because `ajaxSetup` affects **all** AJAX requests, even cross-site ones but cross-site requests will break if they receive more headers than they accept and there is no easy way to undo an `ajaxSetup` once it's called as far as I know. – apokryfos Sep 29 '20 at 06:46

0 Answers0