MHF
MHF

Reputation: 221

Changing Yii2 API actions

I use yii2 (2.0.13). when i send data with ajax, the return response includes an error.

my code:

namespace frontend\controllers;

use Yii;
use yii\rest\ActiveController;    

class CityController extends ActiveController
{
    public $modelClass = 'frontend\models\City';

    public function actions()
    {
        $actions = parent::actions();
         unset($actions['create']);
        return $actions;
    }    

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        // remove authentication filter
        $auth = $behaviors['authenticator'];
        unset($behaviors['authenticator']);

       // add CORS filter
        $behaviors['corsFilter'] = [
            'class' => \yii\filters\Cors::className(),
        ];

        // re-add authentication filter
        $behaviors['authenticator'] = $auth;
        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;
    }    

    public function actionCreate()
    {
      echo 'Hi i\'m create!!';
    }
}    

And ajax request:

$.ajax({
            url: "http://blog.dev/city", // our php file
            type: 'POST',
            contentType: false,
            cache: false,
            processData: false,
            data: {x: 'data_text'},
            success: function(data){
                console.log(data);
            },
            error: function (request) {
                console.log(request);
            }
        });    

When in the actionCreate I add exit() the problem is fixed.
Where is the problem and exactly how should I change actionCreate?
Help me, please.

Upvotes: 0

Views: 52

Answers (1)

Alejandro
Alejandro

Reputation: 856

The client is send a ajax request, so Yii2 should process the request like a ajax request too. You need change the code like this:

<?php
...
public function actionCreate()
{
  if (Yii::$app->request->isAjax) {
      // DO SOMETHING
      \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
      return [
          'message' => 'Hi i\'m create!!'
      ];
  }
}

The client side you can have something like this:

$.ajax({
   url: '<?php echo Yii::$app->request->baseUrl. '/ads' ?>',
   type: 'post',
   data: {
              x: 'data_text', 
             _csrf : '<?=Yii::$app->request->getCsrfToken()?>'
         },
   success: function (data) {
      console.log(data.message);
   }

});

Important! You need send the CSRF token if you have enableCsrfValidation in TRUE

Upvotes: 1

Related Questions