Agent.Logic_ Agent.Logic_ - 5 months ago 45
JSON Question

How to save JSON data in cakephp

I'm using CakePHP v2.2.1 stable. I have a

UsersController
with the action
add()
. I'm trying to send the user info via ajax (from the home page to
/users/add
) and save the data. My code is something like this:

// /app/View/Pages/home.ctp
<?php
$data = array('User' => array('username' => 'vegeta_super_sayajin',
'password' => 'over9000!', 'email' => 'vegeta@supersayajin.com',
'profile_pic' => '/home/pics/scouter.jpg', 'firstname' => 'Vegeta',
'lastname' => 'Vegeta', 'level_id' => '9001'));
?>
<script type="text/javascript">
var data = <?php echo json_encode($data); ?> //convert $data into json format
$.ajax({url: '/users/add', data: "data="+data, type: 'post'});
</script>


How do I receive this data in the
UsersController
, so that I can process and save it?

Currently, I'm trying:

// /app/Controller/UsersController.php
function add() {
if($this->request->is('post') {
//returns "Error: [object Object] in logfile
$this->log($this->request->data);
} else {
$this->Session->setFlash(__("The user could not be saved :("));
}
$this->autoRender = false;
}


$this->log($this->request->data)
returns
Error: [object Object]
in the
/app/tmp/logs/error.log
file, and this user info does not exist in any of
$this->request->params
's indexes. All my googling so far has returned only complicated cakephp v1.3 techniques. How is this done in cakephp v2.2.1?

Answer

You can try the following code. It will work for you.

<?php
$data = array(
'User' => array(
    'username' => 'vegeta_super_sayajin', 
    'password' => 'over9000!',
    'email' => 'vegeta@supersayajin.com', 
    'profile_pic' => '/home/pics/scouter.jpg',
    'firstname' => 'Vegeta', 
    'lastname' => 'Vegeta', 
    'level_id' => '9001')
    );   
?>
<script type="text/javascript">
var data = [<?php echo json_encode($data); ?>] //convert $data into json format
$.ajax({
    url: 'checks/add', 
    data: "data="+JSON.stringify(data), 
    type: 'post'});
</script>

And in your controller's code:

// /app/Controller/UsersController.php
function add() {
if($this->request->is('post') {
    $this->log(json_encode($this->request->data, true)); //returns "Error: [object Object] in logfile
} else {
    $this->Session->setFlash(__("The user could not be saved :("));
}
$this->autoRender = false;
}

Here is the json_decode documentation. The second parameter true will convert the object into an array.