AJAX call unable to send a request Yii2

妖精的绣舞 提交于 2020-01-16 09:43:10

问题


I have an AJAX call in my view. The code of it looks like this:

<?php 
        $this->registerJs("
        $(document).on('click','.btn-block',function(){
        var id = $(this).parents('.user-tr').attr('id');
        $.ajax({
            url: '" . Yii::$app->request->baseUrl . "admin/block-users',
            type: 'POST',
            data: {id : id,_csrf : " . Yii::$app->request->getCsrfToken() . "},
            success: function (data) {
                console.log(data);
                },
            });
        })"); 
    ?>

I need to send a request to my actionBlockUsers function of AdminController, which looks like this:

public function actionBlockUsers()
    {
        if (Yii::$app->request->isAjax) {
            print("success");
        }
    }

The problem is that I can't send a request. The inspect XHR doesn't show anything either. How can I fix this problem?


回答1:


You need to wrap the Yii::$app->request->getCsrfToken() into quotes as it would normally contain == in the string which will break the script if not inside qutotes, a better way when working with javascript is to use the yii.js to get the csrf token and the param name using yii.getCsrfParam() and yii.getCsrfToken(), rather than hard coding _csrf.

Also you should try using hereDOC syntax for better readability.

So replace your code with the following in your view

$baseUrl=\yii\helpers\Url::base(true);
$js=<<<JS
 $(document).on('click','.btn-block',function(e){
    var id = $(this).parents('.user-tr').attr('id');
    let data={id : id};
    data[yii.getCsrfParam()]=yii.getCsrfToken();

    $.ajax({
        url: '{$baseUrl}/admin/block-users',
        type: 'POST',
        data: data,
        success: function (data) {
            console.log(data);
            },
        });
    })
JS;
$this->registerJs($js, View::POS_READY);


来源:https://stackoverflow.com/questions/57506614/ajax-call-unable-to-send-a-request-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!