简体   繁体   中英

yii2 call controller action from view and debug process

In a datagrid view I have a textinput field and I want to call a controller function if the field gets updated. Therfore I included a script into my form and prepared a controller function.

$this->registerJs(
    "$('#product_qty').on('click', function() { 
        alert('Button clicked!'); 
        $.ajax({
            url: '".Yii::$app->request->baseUrl . '/suppliers_orders/changequantity' . "',
            type: 'post',
            data: {
                 id: '5' , 
                 _csrf : '" . Yii::$app->request->getCsrfToken() . "'
             },
            success: function (data) {
                console.log(data.search);
                },
            });
    });",
    \yii\web\View::POS_READY,
    'my-button-handler'
);

The alert function will be called and shows 'Button clicked'. Then nothing happens.

The controller of Suppliers_orderController function is:

public function actionChangequantity(){

        if (Yii::$app->request->isAjax) {
            $data = Yii::$app->request->post();
            $id = $data['id'];
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return [
            'search' => $id,
        ];
}

Furthermore I want to trace the activity with phpstorm and xdebug, but the debug process don't stop at the first breakpoint in the controller. What is missing, or is my JS function wrong?

Above all, in Yii2 you have \\yii\\helpers\\Url::base(); to get the baseurl rather than Yii::$app->request->baseUrl; that is the reason of wrong url printing in the console without the baseUrl, so change your line

url: '".Yii::$app->request->baseUrl . '/suppliers_orders/changequantity' . "',

to the following

url: '".\yii\helpers\Url::base(). '/suppliers_orders/changequantity' . "',

Secondly, if you are using localhost path instead of virtual hosts for the frontend and backend and for accessing the controller/action you have to use index.php along with the path after web like below

http://localhost/myproject/backend/web/index.php/suppliers_orders/changequantity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM