Getting bad request (#400) on Ajax calls using Yii 2

Use:

var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
    url: 'request',
    type: 'post',
    dataType: 'json',
    data: {param1: param1, _csrf : csrfToken},
});

More detail: Yii2: Using csrf token


As the answer from Mihai P. states, your problem is CSRF validation. It is also true that you could disable the validation for your actions, but this is not considered a good solution.

As you have a problem in your Ajax request with the validation, you could also use a Yii JavaScript function to add the CSRF token to your formdata that you send in the Ajax request.

Just try to add the token to your form data as follows:

var form_data = {
    zone: zoneId,
    _csrf: yii.getCsrfToken()
};

I hope this helps and you therefore don't have to disable CSRF validation.

In addition to manually add the CSRF token you can check if there is an X-CSRF header set in the request.


Add this code at the bottom of your layout:

<script>
    $.ajaxSetup({
        data: <?= \yii\helpers\Json::encode([
            \yii::$app->request->csrfParam => \yii::$app->request->csrfToken,
        ]) ?>
    });
</script>

Note: See the answer from Skullcrasher to fix the issue in the correct way as my answer suggests disabling the Cross-Site Request Forgery.


You have a problem with enableCsrfValidation. To read more about it you can read here.

To disable CSRF, add this code to your controller:

public function beforeAction($action) {
    $this->enableCsrfValidation = false;
    return parent::beforeAction($action);
}

This will disable for all actions. You should probably, depending on the $action, disable it only for specific actions.

Tags:

Ajax

Jquery

Yii2