Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
961 views
in Technique[技术] by (71.8m points)

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

This is my code:

$(document).on('change', '#tblhotel-int_zone_id', function(e){
    var zoneId = $(this).val();
    var form_data = {
        zone: zoneId
    };
    $.ajax({
        url: "state",
        type: "POST",
        data: form_data,
        success: function(response)
        {
            alert(response);
        }
    });
});

This shows:

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

And I already have <?= Html::csrfMetaTags() ?>. How can I fix this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...