This Question have 3 answers right now.

Ajax save to database in yii2

By : arinze
Source: Stackoverflow.com
Question!

I am trying to insert to database yii2 using ajax, but I have a problem and it does not give me any errors at all. It shows success message like it works but nothing inserts. It does not reflect in the database.

this is my controller:

public function actionThumbs()
{
    $thumbs= new Thumbs; 
    if (Yii::$app->request->isAjax) {
        $data = Yii::$app->request->post();
        $thumbs->user=Yii::$app->user->identity->email;
        $thumbs->topic_id=Yii::$app->getRequest()->getQueryParam('id');
        $my_array = explode(":", $data['rate']);
        $thumbs->rate=$my_array[0];
        $thumbs->load($_POST);
        $thumbs->save();
        return ['blog', 'id' => Yii::$app->getRequest()->getQueryParam('id')];
    }
    return $this->redirect(['blog','id' => Yii::$app->getRequest()->getQueryParam('id')]);
}

this is my ajax file:

$("#mys").click(function() {
    var rate = "up";
    $.ajax({
        type: 'POST',
        url: 'index.php?r=site%2Fthumbs',
        data: {
            rate: rate,
            _csrf: '<?=Yii::$app->request->getCsrfToken()?>'
        },
        success: function(rate) {
            alert("test");
        },
        error: function (exception) {
            console.log(exception);
        }
    });
});

my view file:

<div class="six columns">
    <?= Html::Button('ups', ['class' => 'btn btn-primary', 
 'name' => 'mys' ,'id'=>'mys']) ?> 
</div>
By : arinze


Answers

Try using

  $thumbs->save(false);

if the value are inserted .. then check for your validation .. rule in model ..

the false condition mean no validation .. the value are saved in db without performing any validation rule

By : scaisEdge


This has to do with the fact that and short-circuits, and returns the truthy value instead of True or False.

In:

7 >= 77 and 7

7 >= 77 equates to False, so the second operand of and is never evaluated, so it becomes False.

In:

7 >= 7 and 77

7 is equal to 7 (obviously), so the second operand of and is evaluated. Since 77 is truthy, it's what's returned.



You need a logical condition in the while. Perhaps

program.toUpperCase().equals("Y")
By : nicomp


Video about Ajax save to database in yii2