Wednesday, November 23, 2011

How to read a JSON POST with Yii, and save it to the database

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();
}

5 comments:

  1. $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

    ReplyDelete
  2. please select the type post then after check..

    ReplyDelete
  3. Thanks.. You save my time.

    ReplyDelete
  4. it is better to use:
    $post = Yii::app()->request->rawBody
    instead of
    $post = file_get_contents("php://input");

    ReplyDelete