Retrieve JSON POST data in CodeIgniter

后端 未结 5 989
独厮守ぢ
独厮守ぢ 2020-11-28 13:03

I have been trying to retrieve JSON data from my php file.Its giving me a hard time.This is my code

Code in my VIEW:

var productDetails = {\'id\':ISB         


        
5条回答
  •  隐瞒了意图╮
    2020-11-28 13:32

    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 into json. jQuery does this by itself when you set the dataType: '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. The request 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.

提交回复
热议问题