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?