I am trying to receive and parse a JSON object sent in a POST request using Codeigniter but I cannot \"find\" it.
This is my controller code:
public
This is the correct way to do it.
$input_data = json_decode(trim(file_get_contents('php://input')), true);
In order to use the standard CI methods. In index.php, insert a couple of lines:
$json = json_decode(trim(file_get_contents('php://input')), true);
if(!empty($json)) {
$_POST = $json;
}
Either implement in the bootstrap. RIP Codigniter...(
try
json_decode(array($this->input->post()))
OR
$tmp[] = (array)json_decode($this->input->post());
print_r($tmp);
Firze's answer is correct but here is a more elaborated answer. I am not allowed to comment so I am posting it as an answer.
It has to do with CodeIgniter not being able to fetch JSON
. jQuery
does some under the hood tricks and transforms your data into form-data-x
, that's why it works when you don't specify the content type
, don't encode your object, or other situations.
If you want a pure JSON
the solution is to use $this->input->raw_input_stream
to fetch your JSON
and decode it using php
's json_decode
. Check the full answer and code below:
Retrieve JSON POST data in CodeIgniter
Just add correct content type to your request header
Content-Type: application/json
controller:
puplic function exam(){
$obj = file_get_contents('php://input');
$edata = json_decode($obj);
echo $edata->name;
}
Go to post man->type->post
url:http://www.exam.com/exam
formate:json
{
"name":"atm fahim"
}
==>send