Q
Q
QQbit2018-12-19 17:37:18
AJAX
QQbit, 2018-12-19 17:37:18

Yii2 ajax implementation?

I'm trying to create a button using ajax. Clicking on which will decrease the value of max_drink by one unit. But since I'm new to this business, I can't figure out how to get this request in the controller (and should I receive it in the controller?) and how to send it to the database and change the entry in the user's max_drink column?
View Code

<?php

use yii\helpers\Html;

use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Privil */
/* @var $form yii\widgets\ActiveForm */
?>

<br>

    <?php $form = ActiveForm::begin([

        'layout' => 'horizontal',
        'fieldConfig' => [
            'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
            'labelOptions' => ['class' => 'col-lg-1 control-label'],
        ],
    ]); ?>
<div  >
    <?= $form->field($model, 'client_id')->textInput() ?>
</div>
    Напиток:<?= $model->max_drink ?><br>
    <?= Html::submitButton($model->max_drink, ['update']);

    ?>
    <button class="btn btn-lg btn-success" >Еда:<?= $model->max_food ?></button>

<!--        --><?//= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>


    <?php ActiveForm::end(); ?>

</div>
<?php
$js = <<<JS
        $('form').on('beforeSubmit', function(){
        var data = $model->max_drink-1;
        $.ajax({
            url: 'update?id='+$model->client_id,
            type: 'POST',
            data: {'id':data},
            success: function(res){
                console.log("tratata" +data);
            },
            error: function () {
                alert("atata");
            } 
        });
        return false;
    });
JS;
$this->registerJs($js);
?>

controller
public function actionUpdate($id='')
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->get()) ) {
            return $this->redirect(['update', 'id' => $model->client_id]);
        }





        return $this->render('update', [
            'model' => $model,
        ]);

        if(\Yii::$app->request->isAjax){
            return 'alert("Запрос принят!")';
            return $this->redirect(['update', 'id' => $model->client_id]);
        }

        if($model->load(\Yii::$app->request->post())){

            return $this->redirect(['update', 'id' => $model->client_id]);
        }
        return $this->render('update', compact('model'));
    }
    public function actionCreate()
    {
        $model = new Privil();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->client_id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question