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>') } 

}

Add Comment
3 Answer(s)

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') } 
Add Comment
<script> $.ajaxSetup({     headers: {         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')     } }); </script> 
Add Comment

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     }, 
Answered on July 15, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.