views:

38

answers:

3

Hi all,

I am learning cakePHP 1.26. and JQuery
In a Controller, I got two an action with these lines of codes :

function testing(){
$a = $this->User->findallByuser_id(1);
$b = $this->User->Post->findallByuser_id(1);

return a+b; // I was trying to return Array data $a and $b
}

how would you return two groups of Array data ($a and $b) to be accessed by JQuery AJAX?

Please help if you could.

A: 

You need to have a relation between the user and his posts, maybe with a HasMany relation. When you have that set up, you need a query like this

$query['conditions'] = array('User.id' => $user_id);
$query['contain'] = array('Post');
$data = $this->User->find('all', $query);

See http://book.cakephp.org/view/1323/Containable for information on using Containable. Also see http://book.cakephp.org/view/1039/Associations-Linking-Models-Together for information on linking models via associations.

Hope that helps.

Oscar
+3  A: 

I would use json_encode/json_decode and when you access it on you, while at the client side you can use $.parseJSON(json_strong) in order to convert it to object.

Nik
+1 I added an example in my own answer because comments don't handle code, but this is exactly what I'd do.
Rob Wilkerson
+2  A: 

This is essentially Nik's answer and I agree with him completely, but I think an example may be useful:

function testing(){
  $a = $this->User->findallByuser_id(1);
  $b = $this->User->Post->findallByuser_id(1);

  return json_encode( array( 'User' => $a, 'Posts' => $b ) )
}

This is what I do and I've found it to be very effective.

Rob Wilkerson