Answer the question
In order to leave comments, you need to log in
Do I need to use CSRF token in Ajax Post requests without forms and data input?
The Laravel 4 documentation and third-party sources talk a lot about csrf token. But as far as I understand, it is included only in forms. And if you use AJAX content loading without using a form? In routes.php I set
Route::post('test', array('before'=>'csrf', 'uses'=>'[email protected]');
Answer the question
In order to leave comments, you need to log in
I don’t know how specifically in Laravel, but in principle, the CSRF token should be transmitted with any POST requests to the server.
I read the documentation for Laravel, everything is clearly written there. You can get a token using <?php echo csrf_token(); ?>. Because if you don't have forms, you can do it like this:
1. Add the header tag
<meta name="_token" content="<?php echo csrf_token(); ?>">
var csrftoken = $('meta[name=_token]').attr('content');
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken)
}
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question