Wilianto Indrawan
Wilianto Indrawan

Reputation: 2404

yii2 - How to solve Bad Request (#400) Unable to verify your data submission?

I have a controller generated by Gii. I modify the behaviors to be like this:

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['post'],
            ],
        ],
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
    ];
}

When I fill the form and submit it, sometimes I get an error

Bad Request (#400) Unable to verify your data submission

But if I click on back button in my browser and re-submit again the form with the same value it will be okay an submitted successfully.

I have been searching in google and stackoverflow, many of them say that the problem is on CSRF Token. But in my layout I've put <?= Html::csrfMetaTags() ?> and in my form there is <input type="hidden" name="_csrf" value="...">

Anyone here can help me to solve this? And explain this why does it happen?

Upvotes: 7

Views: 13110

Answers (2)

Knase
Knase

Reputation: 1274

add in form in view

<input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />

Upvotes: 6

Marios Frixou
Marios Frixou

Reputation: 233

I had the same issue and ended up disabling csrf validation.

public function actionCreate() {
    Yii::$app->controller->enableCsrfValidation = false;
}

That seemed to do it for me.

Upvotes: -3

Related Questions