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

后端 未结 8 512
北恋
北恋 2020-12-29 08:39

This is my code:

$(document).on(\'change\', \'#tblhotel-int_zone_id\', function(e){
    var zoneId = $(this).val();
    var form_data = {
        zone: zoneI         


        
8条回答
  •  鱼传尺愫
    2020-12-29 09:06

    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.

提交回复
热议问题