How To Automatically Add X-CSRF-TOKEN With JQuery Ajax Request In Laravel
How can I add csrf token with my ajax requests (GET or POST) of my Laravel application automatically without adding it manually to each and every request.
My ajax Request
$.ajax({
type:'post',
url: "/email/unique",
data: { "_token": "{{ csrf_token() }}", "email": email }
success: function(data) {
console.log(data);
}
});
Answer
In Laravel the value of the csrf-token meta tag registers by default with the Axios HTTP library. But If you are not using this library, you will need to manually configure this behavior for your application.
To do this, store the token in a HTML meta tag
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, once you have created the meta tag, you can instruct the jQuery library to automatically add the token to all the request headers.
For that add the code to the resources/js/bootstrap.js
file for Laravel 5.7
and resources/assets/js/bootstrap.js
for Laravel 5.6
and below versions.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Ajax without csrf token as it will get added automatically
$.ajax({
type:'post',
url: "/email/unique",
data: { "email": email }
success: function(data) {
console.log(data);
}
});
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM