Let's say you are sending a json-encoded object to your create action, and want to save it in your database. here's how:
public function actionCreate() {
//read the post input (use this technique if you have no post variable name):
$post = file_get_contents("php://input");
//decode json post input as php array:
$data = CJSON::decode($post, true);
//contact is a Yii model:
$contact = new Contact();
//load json data into model:
$contact->attributes = $data;
//this is for responding to the client:
$response = array();
//save model, if that fails, get its validation errors:
if ($contact->save() === false) {
$response['success'] = false;
$response['errors'] = $contact->errors;
} else {
$response['success'] = true;
//respond with the saved contact in case the model/db changed any values
$response['contacts'] = $contact;
}
//respond with json content type:
header('Content-type:application/json');
//encode the response as json:
echo CJSON::encode($response);
//use exit() if in debug mode and don't want to return debug output
exit();
}
$post = file_get_contents("php://input"); returns null in my case but i have an argument in actionCreate() named $data and it represents an array so how do i map that
ReplyDeleteplease select the type post then after check..
ReplyDeleteThanks.. You save my time.
ReplyDeleteit is better to use:
ReplyDelete$post = Yii::app()->request->rawBody
instead of
$post = file_get_contents("php://input");
Thank you..
ReplyDelete