Reputation: 612
When I use $.ajaxsetup and trigger $.post, its not adding the default data to the post. or is it only meant for default data if not data supplied?
<script>
window.csrf = { csrf_token: '<?php echo $_SESSION['csrf_token']; ?>' };
$.ajaxSetup({
data: window.csrf
});
$(document).ready(function() {
// CSRF token is now automatically merged in AJAX request data.
$.post('/awesome/ajax/url', { foo: 'bar' }, function(data) {
console.log(data);
});
});
</script>
Upvotes: 1
Views: 496
Reputation: 663
You are passing data in post method which is overriding the one in ajaxSetup
jQuery.post( url [, data ] [, success ] [, dataType ] )
$.post('/awesome/ajax/url', { foo: 'bar' }, function(data)
Instead, you should pass it in headers, Refer How can I add a custom HTTP header to ajax request with js or jQuery?.
HTH
Upvotes: 0
Reputation:
Move
$.ajaxSetup({
data: window.csrf
});
in document.ready()
.
And like other answers point out, if you want to send csrf-token
, you have to use headers
key in ajaxSetup
.
Upvotes: 1
Reputation: 1540
Here is the method binding the csrf token if you are using laravel
In head of app.blade.php
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
In JS.
// CSRF Token
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Upvotes: 0