4

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)

2
  • 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 tips Commented Apr 17, 2012 at 9:02
  • 1
    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. :) Commented Apr 17, 2012 at 9:03

1 Answer 1

3
public function view($param1 = false, $param2 = false) {
       $array = array("Name" => "John");
       header("Content-type: application/json"); // not necessary
       echo json_encode($array);
      exit;
}
Sign up to request clarification or add additional context in comments.

2 Comments

As mentioned above, you cannot just echo an array (stupid mistake by me), you have to use the PHP function json_encode which will encode the array into a json object so that javascript can use it.
it would be cleaner to let the response object take care of sending headers - assuming cake2 (which Mauritz unfortunately forgot to mention)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.