S
S
Stanislav Kim2014-05-25 05:15:06
JavaScript
Stanislav Kim, 2014-05-25 05:15:06

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]');

After that, the ajax request failed. The console writes 500 Internal Server Error. The sources say that you need to include the very token function that we put in the forms.
And the question itself. If necessary? And if so, how?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sintez, 2014-05-25
@cyberS7

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(); ?>">

2. Next, if you are using jQuery, then adding a token to the request will look like this.
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 question

Ask a Question

731 491 924 answers to any question