This Question have 3 answers right now.

Ajax save to database in yii2

By : arinze

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();
        $my_array = explode(":", $data['rate']);
        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";
        type: 'POST',
        url: 'index.php?r=site%2Fthumbs',
        data: {
            rate: rate,
            _csrf: '<?=Yii::$app->request->getCsrfToken()?>'
        success: function(rate) {
        error: function (exception) {

my view file:

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


Try using


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.


7 >= 77 and 7

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


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

By : nicomp

Video about Ajax save to database in yii2