April 17, 2012
jQuery $.post and cakePHP controller giving 400 bad request
Question by Mauritz Swanepoel
I am trying to use $.post() to retrieve a json array from a cakePHP controller. I figured I would not need a view file as I will turn autorender to false and I am expecing a json array. I manage to get a response when I use $.ajax and $.get, but using $.post I get a 400 Bad Request.
My code:
$.post("controller/action",{id: "1"}, function(data) {
console.log(data);
});
public function action() {
$this->autoRender = false;
$array = $_POST;
header("Content-type: application/json");
echo json_encode($array);
exit;
}
Any help or tips on how to possibly do this better? As mentioned $.get, $.ajax does work, but the data callback does not return anything (but firebug shows response array).
Answer by Starx
One error I see is, no indication to expect a json output.
$.post("controller/action",{id: "1"}, function(data) {
console.log(data);
},"json");