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
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
objectintojson.jQuerydoes 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. Therequestalready set the'Accept': 'application/json'header.
So, the trick here is to use $this->input->raw_input_stream and decode your data by yourself.