Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: parse JSON from jQuery

Tags:

json

jquery

php

I'm trying to parse a simple JSON string, but I'm not used to do it from PHP. To do my test I've written a page where the data is created; sends request to PHP page to do some tests.

How can I access the JSON data from PHP and have it returned back?

The string from jQuery:

var json_str = '{"id_list":[{"id":"2","checked":"true"},{"id":"1","checked":"false"}]}';
/*'{
    "id_list": [
        {
            "id": "2",
            "checked": "true"
        },{
            "id": "1",
            "checked": "false"
        }
    ]
}'*/
$.post ("php_json_parser.php", { data_to_send:json_str }, function (data_back) {
    alert (data_back);
});

PHP page:

<?php

$data_back = json_decode (stripslashes($_REQUEST['data_to_send']), true);
print $data_back->{'id_list'[0]["id"]}; //??? how can I access to properties?

?>
like image 871
vitto Avatar asked May 26 '26 11:05

vitto


1 Answers

json_decode with the second parameter set to true turns the JSON item into a php array.

So to access the element in your example, you'de use

$data_back['id_list'][0]['id']
like image 146
eCaroth Avatar answered May 27 '26 23:05

eCaroth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!