Post JSON to Codeigniter controller

后端 未结 12 1018
鱼传尺愫
鱼传尺愫 2020-12-30 05:03

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          


        
相关标签:
12条回答
  • 2020-12-30 05:18

    This is the correct way to do it.

    $input_data = json_decode(trim(file_get_contents('php://input')), true);
    
    0 讨论(0)
  • 2020-12-30 05:19

    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...(

    0 讨论(0)
  • 2020-12-30 05:22

    try

    json_decode(array($this->input->post()))
    

    OR

    $tmp[] = (array)json_decode($this->input->post());
    
    print_r($tmp);
    
    0 讨论(0)
  • 2020-12-30 05:31

    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

    0 讨论(0)
  • 2020-12-30 05:32

    Just add correct content type to your request header

    Content-Type: application/json
    
    0 讨论(0)
  • 2020-12-30 05:35
    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
    
    0 讨论(0)
提交回复
热议问题