In Yii, How pass csrf token in ajax request, getting following error
Unable to verify data submission
In Yii, How pass csrf token in ajax request, getting following error
Unable to verify data submission
From the api docs:
In JavaScript, you may get the values of $csrfParam and $csrfToken via yii.getCsrfParam() and yii.getCsrfToken(), respectively. The yii\web\YiiAsset asset must be registered. You also need to include CSRF meta tags in your pages by using yii\helpers\Html::csrfMetaTags().
Within the page:
<?php
use yii\helpers\Html;
use yii\web\YiiAsset;
YiiAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
Please provide an example how to pass csrfToken in ajax request
The example of an ajax request with the csrfToken:
const request = new XMLHttpRequest();
request.open('POST', 'my-url');
request.onload = function () {
if (request.status === 200) {
}
};
request.onerror = function () {
};
const formData = new FormData();
formData.append(yii.getCsrfParam(), yii.getCsrfToken());
formData.append('my_name', myValue);
request.send(formData);