Keep getting the error "CSRF token mismatch"

So I created a new cakephp app with composer, and tried to do a XMLHttpRequest, but keeps getting the error message “CSRF token mismatch”.

I have the routes.php set to:
$routes->connect(’/booking/*’, [‘controller’ => ‘Booking’]);

javascript code:

    var form_data, xml_http;

    form_data = new FormData();
    xml_http = new XMLHttpRequest();

    form_data.append('test', 'test');

    xml_http.onreadystatechange = function() {
        if (xml_http.readyState === 4 && xml_http.status === 200) {
    };'post', '/booking/test', true);

Disable CSRF or send the token with the ajax request

Do not disable csrf. Get that token and pass it along with the Ajax request.

Also not to have to re write code I did this guide in laravel:

I use

$post._token = document.getElementsByName("_token")[0].value

in laravel, so will be similar in cake.
Replace _token with the name of token in cake.

Don’t disable csrf.

Really if you are new to JS and ajax, you should study it first via some tutorials and maybe Youtube videos. The forums keep getting these questions, where all it takes is a couple of tutorials first.

Ok, thanks for the link to the tutorial on CSRF.
The strange thing is, even if I’m disabling CSRF, I still get the “CSRF token mismatch” error message.

I tried disabling it in the controller with:

function beforeFilter(Event $event) {

Also, I tried creating a cookie in AppController with:

$this->Cookie->write('csrfToken', 'my-csrf-token');

But I’m not sure how to fetch it with javascript.
Also, tried creating a token in javascript:

    var token = 'test';
    xml_http.setRequestHeader('X-CSRF-Token', token);

Still no luck.


By removing CsrfProtectionMiddleware from Application.php, the error disappears. Still need to figure out how to have it enabled and get the cookie-token-value by javascript I guess…

I showed how to get it. But in the controller adapt to take cakephp request.

I wish this forum had a guides section I would post a guide.