1

I'm not sure if this happens due to the Blitz cache. In Craft CMS 5: In the head:

<meta name="csrf-token" content="{{ craft.app.request.getCsrfToken() }}">
<meta name="csrf-param" content="{{ craft.app.config.general.csrfTokenName }}">

When executing the ajax call:

...
const csrfTokenMeta = document.head.querySelector('meta[name="csrf-token"]');
const csrfParamMeta = document.head.querySelector('meta[name="csrf-param"]');
...
formData.append(csrfTokenName, csrfToken);
...

    fetch(`/ajax/my-request`, {
        method: 'POST',
        body: formData,
        headers: {
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
        .then(response => {
            ...
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                ...
            } else {
                console.error('Failed to load.', data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            ...
        })
        .finally(() => {
            ...
        });

From the storage/logs I can see:

[web.ERROR] [yii\web\HttpException:400] yii\web\BadRequestHttpException: Unable to verify your data submission. in /craft/vendor/yiisoft/yii2/web/Controller.php

Could it be that this error occurs when the posted CSRF token param doesn't match the one in the CSRF cookie?

When I clear the cache the problem is resolved. But that is just a temporary solution. What can I do to resolve that issue so that the ajax calls keeps working? What am I missing here?

1 Answer 1

2

I think the token needs to be refreshed with each request. When Blitz caches the page, you will have always the same token as the meta tags will include the token that was assigned at the time.

If you want to keep caching the page with Blitz, you can for example use one of Blitz's functions to get a new one via Javascript. See the Documentation on CSRF Controller Actions

2
  • Thank you. That is correct. I had already looked at the documentation. I should have seen it. Sorry. Commented Jun 27 at 11:59
  • Happens to the best :) Commented Jun 28 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.