POST data not appearing in CakePHP controller POST data not appearing in CakePHP controller ajax ajax

POST data not appearing in CakePHP controller


Don't encode post data as json

The code in the question won't appear in any php script, the reason is this:

contentType: "json"

It's not a form-url-encoded request, so e.g. the following code:

print_r($_POST);print_r(file_get_contents('php://input'));

will output:

Array()'{"customer":123}'

If you want to submit data as json, you'll need to read the raw request body:

$data = json_decode(file_get_contents('php://input'));

There might be times when that's desirable (api usage), but that isn't the normal way to use $.post.

The normal way

The normal way to submit data, is to let jQuery take care of encoding things for you:

$.ajax({      url: "/orders/finalize_payment",      type: "POST",      dataType: "json",  // this is optional - indicates the expected response format    data: {"customer": customer_id},      success: function(){                     alert("success");      }});

This will submit the post data as application/x-www-form-urlencoded and be available as $this->request->data in the controller.

Why $.post works

I changed the request from AJAX to $.post and it worked. I still have no clue why

Implicitly with the updated code in the question you have:

  • removed the JSON.stringify call
  • changed from submitting json to submitting application/x-www-form-urlencoded

As such, it's not that $.post works and $.ajax didn't ($.post infact just calls $.ajax) - it's that the parameters for the resultant $.ajax call are correct with the syntax in the question.


As you're using CakePHP you may find adding RequestHandler to your components fixes the problem.

public $components = array([snip], 'RequestHandler');

Doing this allowed me to transparently access JSON posted data using $this->request->data. The other answer's advice to not encode POST data as JSON becomes a bit awkward, given that certain JS frameworks, such as Angular, post JSON as default.


Using raw data and json you can use:

$data = $this->request->input('json_decode');

**Data is an object now, not an array.

Then you can use:

  $this->MyModel->save($data).