'Add to cart button Yii2

I want to make a button that when it's pressed insert data into table name 'cart' This is my button in index

'cart' => function ($url, $model, $key) {
                        $modelId = $model->id;
                        return Html::button('<i class="fas fa-shopping-cart"></i>',
                            [
                                'class' => 'btn btn-xs btn-outline-success',
                                'style' => 'width:80px; margin-top: 5px',
                                'data-toggle' => 'tooltip',
                                'title' => Yii::t('app', 'Cart'),
                                'onClick' => 'addProduct('. "{$modelId}" . ');'
                            ]);
                    },

And this is my function

public function addProduct($id)
{
    $product = Product::find()->where(['id' => $id])->one();
    if (isset($product)) {
        Yii::$app->db->createCommand()->insert("cart", [
            "product_id" => $product->id,
            "name" => $product->name,
            "price" => $product->price,
            "image" => $product->image,
        ])->execute();
        Yii::$app->session->setFlash('success', 'Item added successfully');
    }
}

And I have this error

Uncaught ReferenceError: addProduct is not defined at HTMLButtonElement.onclick



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source