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

后端 未结 8 454
北恋
北恋 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:01

    Although it is an old post with alot of answers but there is something missing from all the answers posted, all of them addressed the correct point but when calling the ajax POST request along with your data you should use the yii.js functions provided

    • yii.getCsrfParam() to get the parameter name of the token
    • yii.getCsrfToken() to get the token or actual value of the csrf-token

    As if you have different param name for front-end defined inside the config.php or web.php under the request components configurations

    components=>[
    .......
    .......
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
    .......
    .......
    ]
    

    then you need to get that name dynamically and the above function help you out.

    You should

    var form_data = {
        zone: zoneId
    };
    form_data[yii.getCsrfParam()]=yii.getCsrfToken();
    

提交回复
热议问题