0

Form in Laravel that is interactive with Javascript - Works fine until I submit.

I got this error:

error 419 session expired.

So I add @csrf in my form and Javascript doesn't work.

I want my Javascript form works in Laravel

I try this:

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

And this at the end of body tag(put in script tag):

var xhttp = new XMLHttpRequest();
xhttp.open("POST", url , true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content );
xhttp.send(params);

Also try other things. nothing seems to work. I am really frustrated.

Rot-man
  • 18,045
  • 12
  • 118
  • 124
sylvie
  • 1
  • 1

1 Answers1

0

1.add tag with the token to the blade layout:

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

2.setup ajax requests:

$(function() {
  $.ajaxSetup({
    headers: {
      'X-CSRF-Token': $('meta[name="_token"]').attr('content')
    }
  });
});
Shadiqur
  • 490
  • 1
  • 5
  • 18