Retrieve JSON POST data in CodeIgniter
Asked Answered
T

7

16

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':ISBNNumber,'qty':finalqty,'price':finalprice,'name':bookTitle};

        var base_url = '<?php echo site_url() ?>';
        $.ajax({
            url: "<?php echo base_url() ?>index.php/user/Add_to_cart/addProductsToCart",
            type: 'POST',
            data:productDetails,
            dataType:'JSON',
        });

Trying to retrieve in my Controller:

echo $this->input->post("productDetails");

Outputs Nothing.

Here are my headers:

Remote Address:[::1]:80
Request URL:http://localhost/CI/index.php/user/Add_to_cart/addProductsToCart
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Connection:keep-alive
Content-Length:52
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:ci_session=3E5SPro57IrJJkjs2feMNlmMrTqEXrTNN8UyEfleeothNnHwNxuCZDSx4a7cJZGjj7fyr2KLpj%2BPNJeGRSzSPVmcFHVEdhSk4D47ziOl4eZcTUAZlQrWa3EYIeQJVWxMpiGZS26MEfbSXNmfel9e8TcsJTreZHipvfisrJovbXEAW4Uv%2BwrJRep1KCi1MMaDCVJb9UEinRVcDtYe%2F86jhn7kOj4kraVmVzx%2FsOaO0rAxLyAUtez%2Feaa4zBwpN3Td153sAoIb3WxVHoEj2oKyH5prVHigbIhIBR6XZqjBkM6hjBuoD2OSZ2wgLbp9DEENMoqui4WYyHROBuS2DYiJajblcS0KiFga5k%2FQOODvE7p6n%2BozN5ciDliVjJ4PnJ5PD1GaPEmec5%2FbQSlOHYWZk%2F2Blzw3Nw0EtLL7wKDzzQY%3Df645c36bb3548eb8de915b73f8763d97a47783ce
Host:localhost
Origin:http://localhost
Referer:http://localhost/CI/index.php/user/view_available_books/viewAvailableBooks/5
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36
X-Requested-With:XMLHttpRequest
**Form Dataview** sourceview URL encoded
id:234
qty:1
price:0.00
name:dasdadsd2q3e!@!@@

My Response which I can See in Developer tools:

    Array
(
    [id] => 234
    [qty] => 1
    [price] => 0.00
    [name] => dasdadsd2q3e!@!@@
)

But in browser, the output is nothing. I am trying to solve it for more than 4 hours now but in vain.

print_r($_POST); // outputs nothing
echo $data = file_get_contents('php://input'); //outputs nothing
echo $id    = $this->input->post('productDetails');// outputs nothing

My View Code:

<script>
    $('#addtoCart').on('click',function(event){
        event.preventDefault();
        $(this).attr('disabled',"disabled");
        finalprice = $.trim($('#price').val());
        finalqty = $.trim($('#quantity').val());

        var productDetails = JSON.stringify({'id':ISBNNumber,'qty':finalqty,'price':finalprice,'name':bookTitle});

        var base_url = '<?php echo site_url() ?>';
        // console.log($);
        $.ajax({
            url: "<?php echo base_url() ?>index.php/user/Add_to_cart/addProductsToCart",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            data:productDetails,
            dataType:'html',
        });


    });
</script>

Controller Code:

function addProductsToCart(){
        var_dump(json_decode(file_get_contents("php://input")));
        print_r($_POST);
        // $data = json_decode($_POST["productDetails"]);
        // var_dump($data);
        // echo $data = file_get_contents('php://input');
// print_r(json_decode($data));
        // $id    = $this->input->post('id');
        // $qty   = $this

    }
Tallowy answered 19/2, 2015 at 9:36 Comment(8)
two things you did wrong 1. data:{productDetails:productDetails}, 2. $data = json_decode($_POST["productDetails"]);Chiarra
can you show your code what you want to do after you get data in $data variable. second thing you need to return or echo exit something so that you get data back from controller and process that using jquery.Chiarra
I am not getting ant data in the $data variable..thats the point!Tallowy
can you put your controller code in above postChiarra
please see the above code...View and Controller code..nothing works in controllerTallowy
Let us continue this discussion in chat.Chiarra
The problem is that CI doesn't know how to process JSON into $this->input->post(). You need to do it manually. Check my answer below for the explanations.Duff
I had same error. This is a double USD sign issue for me. My eyes tired and didn't see double USD sign. It must be $myObj but I write mistake $$myObj and throws this exception. I hope this comment helps to somebody.Hoofbeat
H
3

General method I use for my Ajax Calls in CI :

JS :

post_array =
{
    "myvar" : "value1",
    "myvar2": "value2"
} 

$.post(baseUrl + "/AjaxController/my_function", post_array,
    function(data)
    {
        var res = jQuery.parseJSON(data);
        alert(res.property);
    }  

Controller :

public function my_function()
{
    $myvar = $this->input->post('myvar');
    $myvar2 = $this->input->post('myvar2'); 

    //Stuff

    echo json_encode($myobject);
}
Hamster answered 19/2, 2015 at 9:36 Comment(5)
How about echoing or putting this data in a table of a view file? How would I do that @AdrienXL? What would be my javascript success: function would look like?Fretwork
Where's $myobject come from?Oaken
@Oaken it's the object you've built depending on what you have to do in the //Stuff partHamster
This is more or less what he did but this answer didn't catch the issue. In the OP's issues JSON needs to be fetched using POST. Your answer is opaque because in fact in your code CI does NOT processes the request as JSON. jQuery modifies the request load into another format in the process! If you need to work with JSON as the OS stated, check my answer for full explanation.Duff
I got no clue... would OP can tell us how this answer helped him/herKulda
D
34

TLDR: Use $this->input->raw_input_stream and decode the data by manually.

I had the exact same problem. CodeIgniter doesn't know how to fetch JSON. I first thought that it is about the encoding because I was using fetch.js and not jQuery. Whatever I was trying, I was receiving nothing. $_POST was empty as well as $this->input->post(). Here is how I've solved the problem.

Send the request (shown here 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 have encode the data of type object as 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 the $this->input->raw_input_stream. Not using $this->input->post() means that you need to clean the stream manually (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.

Duff answered 29/7, 2016 at 10:15 Comment(3)
Instead of passing the value through $this->security->xss_clean() we can we can use $this->input->input_stream(null, true) and pass in a second argument as true for XSS filtering.Ey
oh man you save my daysTheseus
you don't need xss_clean here. See CodeIgniter docs: "XSS escaping should be performed on output, not input!"Ailing
C
13

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"}]

Crooks answered 9/2, 2018 at 3:23 Comment(0)
T
8

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');
Tenorrhaphy answered 2/10, 2016 at 22:5 Comment(0)
H
3

General method I use for my Ajax Calls in CI :

JS :

post_array =
{
    "myvar" : "value1",
    "myvar2": "value2"
} 

$.post(baseUrl + "/AjaxController/my_function", post_array,
    function(data)
    {
        var res = jQuery.parseJSON(data);
        alert(res.property);
    }  

Controller :

public function my_function()
{
    $myvar = $this->input->post('myvar');
    $myvar2 = $this->input->post('myvar2'); 

    //Stuff

    echo json_encode($myobject);
}
Hamster answered 19/2, 2015 at 9:36 Comment(5)
How about echoing or putting this data in a table of a view file? How would I do that @AdrienXL? What would be my javascript success: function would look like?Fretwork
Where's $myobject come from?Oaken
@Oaken it's the object you've built depending on what you have to do in the //Stuff partHamster
This is more or less what he did but this answer didn't catch the issue. In the OP's issues JSON needs to be fetched using POST. Your answer is opaque because in fact in your code CI does NOT processes the request as JSON. jQuery modifies the request load into another format in the process! If you need to work with JSON as the OS stated, check my answer for full explanation.Duff
I got no clue... would OP can tell us how this answer helped him/herKulda
E
2

You only have your own answer.

print_r($_POST);

Return :

Array
(
    [id] => 234
    [qty] => 1
    [price] => 0.00
    [name] => dasdadsd2q3e!@!@@
)

Then how will you get : echo $id = $this->input->post('productDetails');

You will get id by echo $id = $this->input->post('id');

Erotica answered 19/2, 2015 at 9:42 Comment(5)
That result array is shown only in developer tools when I click the result tab, but not in that pageTallowy
print_r($_POST); you must have written in php correct code ?Erotica
so if $_POST have value then $this->input->post() will also have the same valueErotica
U r not getting it, I can see the output in developer tools preview tab but cannot retrieve it in that page...I dont know why!! and thts why i have posted this ques!Tallowy
@RanaSoyab the thing is , $_POST is also empty. As jimasun described CI doesnt know how to handle a request which has a application/json content-type.Kulda
L
0

I'm a little bit late but I didn't find the answers here for the same problem in my application. I think it could help others like me in the future.

if none of the above solutions worked for you then be sure that you didn't add a "/" at the end of your post URL. I wasted my 4 hours for this "/" at the end of the post request URL.

CI4 makes an internal redirect for post requests if your URL ended with "/". when it redirect it lost the post data from the request.

Lehet answered 16/3, 2022 at 18:11 Comment(0)
E
0

Following solution works for me -

Ajax -

$.ajax({
        url: "AJAX_URL_HERE", 
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ msg: msg, sendmsg: 1, stdId: stdId }),
        success: function (result) {
            // when call is sucessfull
        },
        error: function (err) {
        // check the err for error details
        }
      }); // ajax call closing

In Controller -

$post_data = json_decode(file_get_contents('php://input'), true);
$post_data['msg'];
$post_data['stdId'];
Epitasis answered 21/9, 2022 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.