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");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!