Ajax + Controller Action in Yii2

前端 未结 3 1312
终归单人心
终归单人心 2020-12-25 15:42

I\'m new to programming, and I\'m trying to call a function when the user inputs data and clicks submit button. I\'m using Yii2 and I\'m not familiar with Ajax. I tried deve

相关标签:
3条回答
  • 2020-12-25 15:56

    This is sample you can modify according your need

    public function actionSample()
    {
    if (Yii::$app->request->isAjax) {
        $data = Yii::$app->request->post();
        $searchname= explode(":", $data['searchname']);
        $searchby= explode(":", $data['searchby']);
        $searchname= $searchname[0];
        $searchby= $searchby[0];
        $search = // your logic;
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return [
            'search' => $search,
            'code' => 100,
        ];
      }
    }
    

    If this will success you will get data in Ajax success block. See browser console.

      $.ajax({
           url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
           type: 'post',
           data: {
                     searchname: $("#searchname").val() , 
                     searchby:$("#searchby").val() , 
                     _csrf : '<?=Yii::$app->request->getCsrfToken()?>'
                 },
           success: function (data) {
              console.log(data.search);
           }
      });
    
    0 讨论(0)
  • 2020-12-25 16:00

    The correct way to get the CSRF param is this:

    data[yii.getCsrfParam()] = yii.getCsrfToken()
    
    0 讨论(0)
  • 2020-12-25 16:04

    you have to pass _csrf tokin as a parameter

    _csrf: yii.getCsrfToken()
    

    or you can disable csrf valdation

    0 讨论(0)
提交回复
热议问题