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) {
        } 
    };

    xml_http.open('post', '/booking/test', true);
    xml_http.send(form_data);

Disable CSRF or send the token with the ajax request

https://book.cakephp.org/3.0/en/controllers/components/csrf.html#csrf-protection-and-ajax-requests

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:

https://laracasts.com/discuss/channels/guides/jquery-ajax-post-example

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) {
    $this->getEventManager()->off($this->Csrf);
}

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.

Update

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.