I'm using this html and javascript to send json data to my php file. http://jsfiddle.net/ExpertSystem/9aWNj/
How to access it from there in php to echo out a given element?
Something along the lines of:
$value = json_decode($_POST["newOrder"])
echo $value[1];
etc
I'm not sure how to retrieve data from this.
try this :
$value = json_decode($_POST["newOrder"], true)
echo "<pre>";
print_r($value);
Note the second parameter true
, that gives you output as array else it will be object.
Check the php manual.
json_decode returns an object as default. use a second param true to return an array.
json_decode($_POST["newOrder"], true)
To use json in PHP like I think you might want to then I suggest you put a true in the json_decode function.
This will give you the following:
$json = json_decode($data,true);
$json["sub-values"]["sub thing"];
Why to send the JSON as a body of POST request? Do it simpler:
$.ajax({
url: "<url_to_php_file>",
type: "POST",
data: { order: JSON.stringify(dataArr) }
});
And on the server side use:
$value = json_decode($_POST["order"]);
echo $value[1];
Here is a jsfiddle to see how the javascript should be in case you're still lost: http://jsfiddle.net/9aWNj/3/
this is your data decoded by php:
`stdClass Object ( [order] => Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 [7] => 9 [8] => 10 [9] => 11 [10] => 1 [11] => 12 ) )`
To access it it will be: example:
$order_0=$value->order[0];
$order_1=$value->order[1];
Or you use the true for json_decode and it will become like this
$order_0=$value['order'][0];
$order_1=$value['order'][1];
Json_decode return result as object by default, to get array you need to put second parameter to true.
$data = json_decode($_POST["newOrder"], false); return result as object
for printing object use
echo $data->something;
$data = json_decode($_POST["newOrder"], true); return result as array
for printing array use
echo $data['something'];
Try this, It may helpful
$FP=fopen(JSON_DIR."JsonArray.txt",'r');
$J_ARRAY=fread($FP,filesize(JSON_DIR."JsonArray.txt"));
$J_ARRAY=json_decode($J_ARRAY,JSON_FORCE_OBJECT);