i make ajax call for method using ajax and laravel so i put the token on the head of my blade file and send it with the form but i get an error 219 ‘csrf token mismatch " i can’t find way i’m getting the error
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<form id="formId">
<input id="news_letter_mail"
name="email"
class="form-control"
placeholder="Entrez votre E-mail *" />
<div class="call_to_action mb-4">
<a href="#" id="newsletter"> <button >Envoyer un Message</button> </a>
<span><i class='bx bx-right-arrow-alt'></i></span>
</div>
</form>
<script>
$("#newsletter").click(function(event){
event.preventDefault();
var name="moussa";
var email="[email protected]";
var message="ok";
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
console.log(CSRF_TOKEN);
$.ajax({
url: '/newsletter',
type: 'POST',
dataType: 'json',
// headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data:{_token: CSRF_TOKEN,name: name,email: email,message: message}, // the value of input having id vid
success: function(response){ // What to do if we succeed
console.log(response);
},
error: function (error) {
}
});
});
</script>
4
Answers
thanks to anyone who had post an answer the problem was that laravel 9 add middelware VerifyCsrfToken wish manage the csrf-tokens so i had to add my route to the middelware
There many way to add updated CSRF token in your ajax request.
Add following hidden field inside your form
inside you js file
It will work fine.
Add the following meta tag in your layout header
Then in ajax call, include this headers
Hope, it will solve your problem
You can generate csrf while sending AJAX call like this.
Most effective one I have been using this.