Laravel 419 Error – VerifyCsrfToken issue when using ajax
No idea what is causing this I saw on other posts it has to do something with csrf token but I have no form so I dont know how to fix this
script function check_login_auth(id) {
var email_address = $("input[name=l_email_address]").val(); var password = $("input[name=l_password]").val(); var token = $("meta[name=csrf-token]").attr("content"); $.ajax({ type: "POST", url: baseurl+"route", data: { email:email_address, password:password, _token:token }, dataType: 'json', beforeSend: function() { $('#l_loading_gif').show() $('#l_login_form').hide() }, success: function (data) { // console.log(data) }, }); }else { $('#s_error').append('<p style="color: red">something went wrong.</p>') }
}
You are calling POST method so You need to pass csrf_token
in headers.
headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
Your ajax looks like below.
$.ajax({ type: "POST", url: baseurl+"route", headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' }, data: { email:email_address, password:password, _token:token }, dataType: 'json', beforeSend: function() { $('#l_loading_gif').show() $('#l_login_form').hide() }, success: function (data) { // console.log(data) }, });
If you’re calling it in js file then pass the csrf token in meta tag.
<meta name="csrf-token" content="{{ csrf_token() }}">
And headers like
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
<script> $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); </script>
First you have to get the csrf-token
value in proper way
var CSRF_TOKEN = document.getElementById("csrf_token").value; <input type="hidden" name="_token" id="csrf_token" value="{{ csrf_token() }}">
or
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
or
var CSRF_TOKEN = form.find("input[name='_token']").val(); <input type="hidden" name="_token" value="{{ csrf_token() }}">
Then you have to pass this data in
data: { email:email_address, password:password, _token: CSRF_TOKEN },