简体   繁体   中英

Save to database in yii2

I am trying to save to a database in yii2 using ajax but I am getting errors. I just want to insert the value or rate which is "up" into the database and I don't want to use a form, just on-click of a button.

This is my controller

      public function actionThumbs()
      {
          $thumbs = new Thumbs; 

          $thumbs->user = Yii::$app->user->identity->email;
          $thumbs->topic_id = Yii::$app->getRequest()->getQueryParam('id');
          $thumbs->rate = $_POST["rate"];

          if ($thumbs->load(Yii::$app->request->post()) ) {
              $thumbs->load($_POST);
              $thumbs->save();
              return $this->redirect(['blog', 'id' => Yii::$app->getRequest()->getQueryParam('id')]);
          }

          return $this->redirect(['blog','id' => Yii::$app->getRequest()->getQueryParam('id')]);
      }

This is my this is my ajax file

$("#mys").click(function() {

   var rate = "up";

   $.ajax({
       type: 'POST',
       url: 'vot/frontend/web/index.php?r=site%2Fthumbs',
       data: 'rate='+rate,
       success: function (rate) {
           alert("test");
       },
       error: function (exception) {
           alert(exception);
       }
   });
});

the view

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

I get this alert error

The page at localhost says":
 "[object Object]"

By default Yii2 controller doesn't accept POST request without _csrf protection, so there are 2 ways here:

1 - disable csrf:

public function actionThumbs() {
    $this->enableCsrfValidation = false;
    //your code here
}

2 - Send post request via ajax with _csrf token: In your layout/main.php file, put this: <?= Html::csrfMetaTags() ?>

Before your "ajax" code, call this:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
    }
});
//Your ajax code here

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