Kiran Muralee Kiran Muralee - 6 months ago 47
JSON Question

Not able to get Yii2 object data returned as Json

I am new to Yii 2 framework and PHP.When I try to retrieve a model data from the server as Json,I am getting empty data.But when I use var_dump I am getting the result.The code at the controller is given below.

//function inside class ClientController
public function actionIndex()
{

$client=new Client();
$client->name="ajith";
echo json_encode($client);


}


The model class code is given below

/**
* This is the model class for collection "client".
*
* @property \MongoId|string $_id
* @property mixed $name
* @property mixed $age
* @property mixed $sex
* @property mixed $phoneno
* @property mixed $email
* @property mixed $address
* @property mixed $location
*/
class Client extends \yii\mongodb\ActiveRecord
{
/**
* @inheritdoc
*/
public static function collectionName()
{
return ['gym', 'client'];
}

/**
* @inheritdoc
*/
public function attributes()
{
return [
'_id',
'name',
'age',
'sex',
'phoneno',
'email',
'address',
'location',
];
}

/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'], 'safe']
];
}

/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'_id' => 'ID',
'name' => 'Name',
'age' => 'Age',
'sex' => 'Sex',
'phoneno' => 'Phoneno',
'email' => 'Email',
'address' => 'Address',
'location' => 'Location',
];
}
}


When I use the URL path "path to server/web/client",I am getting result echoed as {}.Why is it so.I use Mongo DB as the database.

Answer

Add use statement to the top of your controller to use yii\web\Response class:

use yii\web\Response;

Then, use this class in your action by telling Yii what format do you want to return as a result and just return the result:

public function actionYourActionName() {

    Yii::$app->response->format = Response::FORMAT_JSON;

    $result = ['success' => true, 'message' => '...']; // whatever

    ...

    return $result;
}

More here.

Comments