4
votes

I want to return a JSON array from a cakePHP controller. I effectively have a jquery click event which should send either a post, ajax or get call to the controller (specified with URL) and that controller should just return the array. This makes sense to me because I will not create a view file, I literally send the response to the controller and I can set the header, echo the json array and possibly just exit.

My output only says "Array" on console, and does not echo out any parameters in the array. Any ideas?

// jQuery code:
$("selector").click(function() {
      $.post("/controller/view/param1/param2/",function(data) {
         console.log(data);
      } 
}

// code in my controller:
public function view($param1 = false, $param2 = false) {
       $array = array("Name" => "John");
       header("Content-type: application/json");
       echo $array;
      exit;
}

EDIT: Found the solution - the echo $array must be echo json_encode($array)

1
Haha oopsie, found the solution :) I had to add json_encode($array) and cannot just echo the $array. If anyone else has good tips or ideas please send them for future reference and tipsmauzilla
Exactly. Is there a reason you are using "POST" if not sending anything? It takes 2 requests to do a post, while only 1 using GET/LOAD etc. :)Marco Johannesen

1 Answers

4
votes
public function view($param1 = false, $param2 = false) {
       $array = array("Name" => "John");
       header("Content-type: application/json"); // not necessary
       echo json_encode($array);
      exit;
}