Retrieve JSON POST data in CodeIgniter
I had the exact same problem. CodeIgniter doesn't know how to fetch JSON. I first thought is about the encoding Because I use fetch.js
and not jQuery
. Whatever I was doing I was getting an notting. $_POST
was empty as well as $this->input->post()
. Here is how I've solved the problem.
Send request (as object prop -- because your js lib might vary):
method: 'POST',headers: { 'Accept': 'application/json', 'Content-Type': 'application/json'},body: JSON.stringify({ ready: 'ready'})
Node: I encode my data of type
object
intojson
.jQuery
does this by itself when you set thedataType: 'JSON'
option.
CodeIgniter (3.1 in my case):
$stream_clean = $this->security->xss_clean($this->input->raw_input_stream);$request = json_decode($stream_clean);$ready = $request->ready;
Note: You need to clean your
$this->input->raw_input_stream
. You are not using$this->input->post()
which means this is not done automatically by CodeIgniter.
As for the response:
$response = json_encode($request);header('Content-Type: application/json');echo $response;
Alternatively you can do:
echo $stream_clean;
Note: It is not required to set the
header('Content-Type: application/json')
but I think it is a good practice to do so. Therequest
already set the'Accept': 'application/json'
header.
So, the trick here is to use $this->input->raw_input_stream
and decode your data by yourself.
I had the same problem but I found the solution.
This is the Json that I am sending [{"name":"JOSE ANGEL", "lastname":"Ramirez"}]
$data = json_decode(file_get_contents('php://input'), true);echo json_encode($data);
This code was tested and the result is [{"name":"JOSE ANGEL","lastname":"Ramirez"}]
Although OP seems satisfied, choosen answer doesn't tell us the reason and the real solution . (btw that post_array is not an array it's an object indeed ) @jimasun's answer has the right approach. I will just make things clear and add a solution beyond CI.
So the reason of problem is ;
Not CI or PHP, but your server doesn't know how to handle a request which has an application/json content-type. So you will have no $_POST data. Php has nothing to do with this. Read more at : Reading JSON POST using PHP
And the solution is ;Either don't send request as application/json or process request body to get post data.
For CI @jimasun's answer is precise way of that.
And you can also get request body using pure PHP like this.
$json_request_body = file_get_contents('php://input');