Skip to content Skip to sidebar Skip to footer

Ajax Call Unable To Send A Request Yii2

I have an AJAX call in my view. The code of it looks like this: registerJs(' $(document).on('click','.btn-block',function(){ var id = $(

Solution 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);

Post a Comment for "Ajax Call Unable To Send A Request Yii2"