Attempting to encode json and receive 400: Bad Request
in yii2
. I am trying to encode in Rest client but it is not working properly.
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\TblUserRegistration;
class UserController extends Controller
{
public function actionRegister()
{
$model = new TblUserRegistration();
$username = $_POST['username'];
echo json_encode($username);
}
}
?>
Solution 1: In case if all your controller's actions will deliver json you may also consider extanding yii\rest\Controller instead of yii\web\Controller :
NOTE: you may also use ActiveController which extends yii\rest\Controller (see rest docs) if you need to handle CRUD operations.
Solution 2: A different approach when extending yii\web\Controller is by using yii\filters\ContentNegotiator. Note that setting
$enableCsrfValidation
to false may be mandatory here as it is explained in its related docs :The above code may be rewritten this way :
i think 400 have nothing to do with json_encode
google "yii2 csrf" for more information.
or add scrf in view: form:
meta: